text:
using System;
using System.Drawing;
using System.Runtime.ExceptionServices;
using System.Threading;
using BrailleIO.Interface;
using BrailleIO.Structs;

namespace BrailleIO
{
    ///
    /// Basic structure to hold content that should been displayed on an output device
    ///
    public class BrailleIOViewRange : AbstractViewBoxModelBase, IContrastThreshold, IZoomable, IBrailleIOContentChangedEventSupplier
    {
        #region Members

        private int threshold = 130;

        // type of?
        private bool is_matrix = false;
        private bool is_image = false;
        private bool is_text = false;
        private bool is_other = false;

        private object syncRoot = new object();

        // raw data
        private volatile bool[,] matrix;

        bool[,] Matrix
        {
            get { return matrix; }
            set { matrix = value; }
        }
        private Bitmap _img;
        private readonly Object _imgLock = new Object();
        private Bitmap image
        {
            get
            {
                lock (_imgLock)
                {
                    return _img;
                }
            }
            set
            {
                lock (_imgLock)
                {
                    _img = value;
                }
            }
        }
        private Size imageSize = new Size();
        private String text;
        private Object otherContent;

        // zoom multiplier
        private double zoom = 1.0;

        ///
        /// The maximal zoom level that can be applied.
        ///
        public double MAX_ZOOM_LEVEL = 5;

        private bool _invert_image = false;
        ///
        /// Gets or sets a value indicating whether the image should be inverted or not.
        ///
        /// <value>
        ///   <c>true</c> if [invert the image]; otherwise, <c>false</c>.
        /// </value>
        public bool InvertImage
        {
            get { return _invert_image; }
            set
            {
                bool fire = _invert_image != value;
                _invert_image = value;
                if (fire) firePropertyChangedEvent("InvertImage");
            }
        }

        private BrailleIOScreen _parent = null;
        ///
        /// Gets or sets the parent <see cref="BrailleIOScreen"/>.
        ///
        /// <value>
        /// The parent Screen.
        /// </value>
        public BrailleIOScreen Parent
        {
            get { return _parent; }
            protected set
            {
                bool fire = _parent != value;
                _parent = value;
                if (fire) firePropertyChangedEvent("Parent");
            }
        }

        volatile bool _render = true;

        ///
        /// Gets or sets a flag indicating whether this <see cref="BrailleIOViewRange"/> should be re-rendered because of the content was changed.
        ///
        /// <value><c>true</c> if the renderer should re-render the content; otherwise, <c>false</c>.</value>
        public bool Render
        {
            get { return _render; }
            internal set
            {
                _render = value;
            }
        }

        #region for sorting

        //private volatile int tstamp;

        private int zIndex;

        #endregion

        #region Renderer

        private readonly BrailleIO.Renderer.BrailleIOImageToMatrixRenderer _ir = new Renderer.BrailleIOImageToMatrixRenderer();
        private readonly BrailleIO.Renderer.BrailleIOViewMatixRenderer _mr = new BrailleIO.Renderer.BrailleIOViewMatixRenderer();
        private readonly BrailleIO.Renderer.MatrixBrailleRenderer _tr = new BrailleIO.Renderer.MatrixBrailleRenderer();

        private IBrailleIOContentRenderer _cr;
        ///
        /// Gets the currently used render for the specific content.
        ///
        /// <value>
        /// The content render.
        /// </value>
        public IBrailleIOContentRenderer ContentRender
        {
            get { return _cr; }
            private set
            {
                bool fire = _cr != value;
                _cr = value;
                if (fire) fireRendererChanged();
            }
        }

        ///
        /// Updates the size of the content.
        ///
        public void UpdateContentSize()
        {
            if (Render)
            {
                if (ContentRender != null)
                {
                    Object cnt = GetContent();
                    ContentRender.RenderMatrix(this, cnt);

                    ////clean up the cloned elements (e.g. images)
                    //if (cnt is IDisposable) { ((IDisposable)cnt).Dispose(); }
                    //else { cnt = null; }
                }
            }
        }

        #endregion

        #endregion

        #region Constructors

        #region Image Constructors
        ///
        /// Initializes a new instance of the <see cref="BrailleIOViewRange"/> class.
        ///
        /// <param name="left">The left position inside the parent Screen.</param>
        /// <param name="top">The top position inside the parent screen.</param>
        /// <param name="width">The overall width.</param>
        /// <param name="height">The overall height.</param>
        /// <param name="image">The content image.</param>
        public BrailleIOViewRange(int left, int top, int width, int height, Bitmap image)
        {
            this.ViewBox = new Rectangle(left, top, width, height);
            SetBitmap(image);
        }

        #endregion

        #region Text Constructors
        ///
        /// Initializes a new instance of the <see cref="BrailleIOViewRange" /> class.
        ///
        /// <param name="left">The left position inside the parent Screen.</param>
        /// <param name="top">The top position inside the parent screen.</param>
        /// <param name="width">The overall width.</param>
        /// <param name="height">The overall height.</param>
        /// <param name="text">The content text.</param>
        public BrailleIOViewRange(int left, int top, int width, int height, String text)
        {
            this.ViewBox = new Rectangle(left, top, width, height);
            SetText(text);
        }

        #endregion

        #region Matrix Constructors
        ///
        /// Initializes a new instance of the <see cref="BrailleIOViewRange" /> class.
        ///
        /// <param name="left">The left position inside the parent Screen.</param>
        /// <param name="top">The top position inside the parent screen.</param>
        /// <param name="width">The overall width.</param>
        /// <param name="height">The overall height.</param>
        public BrailleIOViewRange(int left, int top, int width, int height)
            : this(left, top, width, height, new bool[0, 0]) { }

        ///
        /// Initializes a new instance of the <see cref="BrailleIOViewRange" /> class.
        ///
        /// <param name="left">The left position inside the parent Screen.</param>
        /// <param name="top">The top position inside the parent screen.</param>
        /// <param name="width">The overall width.</param>
        /// <param name="height">The overall height.</param>
        /// <param name="matrix">The content matrix.</param>
        public BrailleIOViewRange(int left, int top, int width, int height, bool[,] matrix)
        {
            this.ViewBox = new Rectangle(left, top, width, height);
            SetMatrix(matrix);
        }
        #endregion

        #endregion

        /// Sets the parent Screen.
        /// <param name="parent">The parent.</param>
        /// <returns><c>true</c> if the parent was changed successfully; otherwise, <c>false</c>.</returns>
        public bool SetParent(BrailleIOScreen parent)
        {
            bool success = false;
            if (parent != null)
            {
                if (parent.GetViewRange(Name) == null || !parent.GetViewRange(Name).Equals(this))
                    parent.AddViewRange(this.Name, this);
                Parent = parent;
                success = true;
                firePropertyChangedEvent("Parent");
            }
            return success;
        }

        ///
        /// set matrix
        ///
        /// <param name="matrix">
        /// bool[,] matrix
        /// </param>
        public void SetMatrix(bool[,] matrix)
        {
            if (Monitor.TryEnter(syncRoot, new TimeSpan(0, 0, 1)))
            {
                try
                {
                    Matrix = matrix;
                    this.is_matrix = true;
                    this.is_text = this.is_image = this.is_other = false;
                    this.ContentRender = _mr;
                    Render = true;
                }
                finally
                {
                    Monitor.Exit(syncRoot);
                }
            }
            fireContentChangedEvent();
        }

        /// Gets the matrix.
        /// <returns>the <c>bool</c> matrix set as content if set; otherwise, <c>null</c>.</returns>
        public bool[,] GetMatrix()
        {
            if (Monitor.TryEnter(syncRoot, new TimeSpan(0, 0, 1)))
            {
                try
                {
                    return Matrix;
                }
                finally
                {
                    Monitor.Exit(syncRoot);
                }
            }
            return Matrix;
        }

        ///
        /// Sets the bitmap that should be rendered.
        ///
        /// <param name="img">The image.</param>
        [HandleProcessCorruptedStateExceptions]
        public void SetBitmap(Bitmap img)
        {
            if (Monitor.TryEnter(syncRoot, new TimeSpan(0, 0, 1)))
            {
                try
                {
                    //clean up the memory
                    if (this.image != null) this.image.Dispose();
                    if (img == null) img = new Bitmap(1, 1);

                    int tries = 0;
                    while (tries++ < 5)
                    {
                        try
                        {
                            this.image = img.Clone() as Bitmap;
                        }
                        catch (InvalidOperationException) { Thread.Sleep(5); }
                        catch (AccessViolationException) { Thread.Sleep(5); }
                        catch (Exception)
                        {
                            break;
                        }
                    }
                    imageSize = new Size(img.Width, img.Height);
                    this.is_image = true;
                    this.is_text = this.is_matrix = this.is_other = false;
                    this.ContentRender = _ir;
                    img.Dispose();
                    Render = true;
                }
                catch { }
                finally
                {
                    Monitor.Exit(syncRoot);
                }
                fireContentChangedEvent();
            }
        }
        ///
        /// Sets the bitmap that should be rendered.
        ///
        /// <param name="img">The content image.</param>
        public void SetBitmap(Image img)
        {
            try
            {
                if (img != null) SetBitmap(new Bitmap(img));
                else
                {
                    SetBitmap(null);
                    Render = true;
                    fireContentChangedEvent();
                }
            }
            catch (ArgumentException) { }
        }

        /// Gets the image to render.
        /// <returns>The image set as content if set; otherwise; <c>null</c>.</returns>
        [HandleProcessCorruptedStateExceptions]
        public Bitmap GetImage()
        {
            if (Monitor.TryEnter(syncRoot, new TimeSpan(0, 0, 1)))
            {
                try
                {
                    int i = 0;
                    while (i++ < 5)
                    {
                        try
                        {
                            return this.image.Clone() as Bitmap;
                        }
                        catch (InvalidOperationException)
                        {
                            Thread.Sleep(5);
                        }
                        catch (AccessViolationException)
                        {
                            Thread.Sleep(5);
                        }
                        catch (System.Exception) { break; }
                    }
                }
                finally
                {
                    Monitor.Exit(syncRoot);
                }
            }
            return null;
        }

        ///
        /// Determines whether this instance should render a matrix.
        ///
        /// <returns>
        /// 	<c>true</c> if this instance renders a matrix; otherwise, <c>false</c>.
        /// </returns>
        public bool IsMatrix()
        {
            return this.is_matrix;
        }

        ///
        /// Determines whether this instance should render an image.
        ///
        /// <returns>
        /// 	<c>true</c> if this instance renders an image; otherwise, <c>false</c>.
        /// </returns>
        public bool IsImage()
        {
            return this.is_image;
        }

        ///
        /// Determines whether this instance should render a text.
        ///
        /// <returns>
        /// 	<c>true</c> if this instance renders a text; otherwise, <c>false</c>.
        /// </returns>
        public bool IsText()
        {
            return this.is_text;
        }

        /// Gets the text to render.
        /// <returns>The text content if set; otherwise, <c>null</c></returns>
        public string GetText()
        {
            if (Monitor.TryEnter(syncRoot, new TimeSpan(0, 0, 1)))
            {
                try
                {
                    return this.text;
                }
                finally
                {
                    Monitor.Exit(syncRoot);
                }
            }
            return this.text;
        }

        ///
        /// Sets the text that should be rendered.
        ///
        /// <param name="text">The text.</param>
        public void SetText(string text)
        {
            if (Monitor.TryEnter(syncRoot, new TimeSpan(0, 0, 1)))
            {
                try
                {
                    this.text = text;
                    this.is_text = true;
                    this.is_image = this.is_matrix = this.is_other = false;
                    this.ContentRender = _tr;
                    Render = true;
                }
                finally
                {
                    Monitor.Exit(syncRoot);
                }
            }
            fireContentChangedEvent();
        }

        ///
        /// Sets an generic content and a related renderer for this type.
        ///
        /// <param name="content">The content.</param>
        /// <param name="renderer">The renderer - can not be null.</param>
        public void SetOtherContent(Object content, IBrailleIOContentRenderer renderer)
        {
            if (renderer == null)
            {
                throw new ArgumentException("No content render set! The content renderer can not be null.", "renderer");
            }

            if (Monitor.TryEnter(syncRoot, new TimeSpan(0, 0, 1)))
            {
                try
                {
                    this.otherContent = content;
                    if (renderer != null) this.ContentRender = renderer;
                    this.is_other = true;
                    this.is_image = this.is_matrix = this.is_text = false;
                    Render = true;
                }
                finally
                {
                    Monitor.Exit(syncRoot);
                }
            }
            fireContentChangedEvent();
        }

        /// Gets the content that is not of the standard types.
        /// <returns>The non-standard content object if set; otherwise, <c>null</c>.</returns>
        public object GetOtherContent()
        {
            if (Monitor.TryEnter(syncRoot, new TimeSpan(0, 0, 1)))
            {
                try
                {
                    return this.otherContent;
                }
                finally
                {
                    Monitor.Exit(syncRoot);
                }
            }
            return this.otherContent;
        }

        ///
        /// Determines whether this instance has a special type of content that can not been rendered with one of the standard renderer.
        ///
        /// <returns>
        /// 	<c>true</c> if this instance has an specialized content type other; otherwise, <c>false</c>.
        /// </returns>
        public bool IsOther()
        {
            return this.is_other;
        }

        ///
        /// Gets the actual zoom-level.
        ///
        /// <returns>Zoom value as ratio</returns>
        public double GetZoom()
        {
            if (zoom <= 0 && IsImage()) // get zoom to fit in the view range
            {
                if (ContentBox != null && imageSize != null)
                {
                    double wr = (double)ContentBox.Width / (double)imageSize.Width;
                    double hr = (double)ContentBox.Height / (double)imageSize.Height;
                    zoom = Math.Min(wr, hr);
                }
            }
            else if (zoom > MAX_ZOOM_LEVEL) { zoom = MAX_ZOOM_LEVEL; }
            return this.zoom;
        }

        ///
        /// Sets the actual zoom.
        ///
        /// <param name="zoom">The zoom value as ratio.</param>
        public void SetZoom(double zoom) { SetZoom(zoom, true); }

        ///
        /// Sets the actual zoom.
        ///
        /// <param name="zoom">The zoom value as ratio.</param>
        /// <param name="rerender">if set to <c>true</c> to force a rerendering and an update of the content size.</param>
        /// <exception cref="System.ArgumentException">The zoom level is with a value of " + zoom + "to high. The zoom level should not be more than " + MAX_ZOOM_LEVEL + ". - zoom</exception>
        public void SetZoom(double zoom, bool rerender = true)
        {
            if (zoom > MAX_ZOOM_LEVEL) throw new ArgumentException("The zoom level is with a value of " + zoom + "to high. The zoom level should not be more than " + MAX_ZOOM_LEVEL + ".", "zoom");
            //TODO: update the content size
            if (this.zoom != zoom)
            {
                this.zoom = zoom;
                Render = true;
                if (rerender) UpdateContentSize();
                firePropertyChangedEvent("Zoom");
            }
        }

        ///
        /// Sets the contrast threshold for image contrast rastering.
        /// If lightness of a color is lower than this threshold, the pin will be lowered.
        /// A higher threshold leads lighter points to raise pins.
        /// A low threshold leads darker pins to stay lowered.
        /// Threshold has to be between 0 and 255.
        ///
        /// <param name="threshold">The threshold.</param>
        /// <returns>the new threshold</returns>
        public int SetContrastThreshold(int threshold)
        {
            Render = true;
            return this.threshold = Math.Max(Math.Min(threshold, 255), 0);
        }

        ///
        /// Gets the contrast for image contrast rastering.
        /// If lightness of a color is lower than this threshold, the pin will be lowered.
        /// A higher threshold leads lighter points to raise pins.
        /// A low threshold leads darker pins to stay lowered.
        /// Have to be between 0 and 255.
        ///
        /// <returns>the set threshold</returns>
        public int GetContrastThreshold() { return threshold; }

        ///
        /// Sets the z-index of the view range. A lager z-index overlays a smaller.
        ///
        /// <param name="zIndex">the z-index of the viewRange.</param>
        public void SetZIndex(int zIndex)
        {
            this.zIndex = zIndex;
            firePropertyChangedEvent("ZIndex");
        }
        ///
        /// Gets the z-index of the view range. A lager z-index overlays a smaller.
        ///
        /// <returns>the z-index of the viewRange.</returns>
        public int GetZIndex() { return this.zIndex; }

        ///
        /// Get the Generic content
        ///
        /// <returns>the untyped content of this view range</returns>
        public Object GetContent()
        {
            object cnt = null;
            if (is_image)
            {
                cnt = GetImage();
            }
            else if (is_matrix)
            {
                cnt = GetMatrix();
            }
            else if (is_text)
            {
                cnt = GetText();
            }
            else
            {
                cnt = GetOtherContent();
            }
            return cnt;
        }

        ///
        /// Occurs when the renderer was changed.
        ///
        public event EventHandler<EventArgs> RendererChanged;

        private void fireRendererChanged()
        {
            if (RendererChanged != null)
            {
                RendererChanged.Invoke(this, null);
            }
        }

        #region IBrailleIOContentChangedEventSupplier

        ///
        /// Occurs when the content has been changed.
        ///
        public event EventHandler<EventArgs> ContentChanged;

        private void fireContentChangedEvent()
        {
            if (ContentRender != null && ContentRender is BrailleIO.Renderer.ICacheingRenderer)
            {
                ((BrailleIO.Renderer.ICacheingRenderer)ContentRender).ContentOrViewHasChanged(this, GetContent());
            }
            if (ContentChanged != null)
            {
                ContentChanged.Invoke(this, null);
            }
        }

        #endregion

        #region Override
        /*
         * Overrides setters for firing property changed events
         */

        #region AbstractViewBoxModelBase

        ///
        /// Rectangle given dimensions and position of the whole view range or screen
        /// including the ContentBox, margin, padding and border (see BoxModel).
        ///
        /// <value>ViewBox of this view (position and size)</value>
        public override Rectangle ViewBox
        {
            set
            {
                bool fire = !ViewBox.Equals(value);
                base.ViewBox = value;
                firePropertyChangedEvent("ViewBox");
            }
        }

        ///
        /// Rectangle given dimensions and position of the view range or screen that can be used for displaying content.
        /// The position is the top-left position of ContentBox inside the viewRange.
        /// The size is the visible size inside the view range --> ViewBox size without margin, border and padding.
        /// BrailleIOScreen                                     ViewBox
        /// ┌────────────────────────────────────────────────╱─┐
        /// │              BrailleIOViewRange              ╱   │
        /// │╔═ Margin ════════════════════════════════════════╗│
        /// │║   Border                                        ║│
        /// │║    Padding                                      ║│
        /// │║  ┌╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴┐ ║│
        /// │║  │                                            │ ║│
        /// │║  │                                            │ ║│
        /// │║  │                                            │ ║│
        /// │║  │              ContentBox                    │ ║│
        /// │║  │      = space to present content            │ ║│
        /// │║  │                                            │ ║│
        /// │║  │                                            │ ║│
        /// │║  │                                            │ ║│
        /// │║  └╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴┘ ║│
        /// │║                                                 ║│
        /// │╚═════════════════════════════════════════════════╝│
        /// │╔═════════════════════════════════════════════════╗│
        /// │║           another BrailleIOViewRange            ║│
        /// │╚═════════════════════════════════════════════════╝│
        /// └───────────────────────────────────────────────────┘
        ///
        /// <value>the available space for the content</value>
        public override Rectangle ContentBox
        {
            set
            {
                bool fire = !ContentBox.Equals(value);
                base.ContentBox = value;
                if (fire) firePropertyChangedEvent("ContentBox");
            }
        }

        ///
        /// Sets the offset position. This is the relation between the
        /// content's position to the visible view. This value is added to the
        /// contents positions to compute the points rendered to the output.
        /// Standard is 0,0 which is means, the content is started rendered in the
        /// top-left corner of the viewBox. To move the content to the top - which is
        /// something like a pan down - you have to set the y-position to a negative
        /// value. To move the content down, you have to add a positive offset. The
        /// same happens for horizontal movement. A negative value will move the
        /// content to the left - which is a pan to the right - and a positive value
        /// will move the content to the right.
        ///
        /// <value>
        /// The offset position.
        /// </value>
        public override Point OffsetPosition
        {
            set
            {
                bool fire = !OffsetPosition.Equals(value);
                base.OffsetPosition = value;
                if (fire) firePropertyChangedEvent("OffsetPosition");
            }
        }

        #endregion

        #region Collision Tests

        ///
        /// Determines whether this view contains a specific point on the display.
        /// Attention: a <c>true</c> does not mean that the point is in the content.
        /// It can be on a spacing or the border.
        ///
        /// <param name="x">The horizontal position on the display.</param>
        /// <param name="y">The vertical position on the display.</param>
        /// <returns><c>true</c> if this view contain the point; otherwise <c>false</c>.</returns>
        public bool ContainsPoint(int x, int y) { return ContainsPoint((double)x, (double)y); }
        ///
        /// Determines whether this view contains a specific point on the display.
        /// Attention: a <c>true</c> does not mean that the point is in the content.
        /// It can be on a spacing or the border.
        ///
        /// <param name="x">The horizontal position on the display.</param>
        /// <param name="y">The vertical position on the display.</param>
        /// <returns><c>true</c> if this view contain the point; otherwise <c>false</c>.</returns>
        public bool ContainsPoint(double x, double y)
        {
            if (x >= ViewBox.X && x < ViewBox.X + ViewBox.Width
                && y >= ViewBox.Y && y < ViewBox.Height + ViewBox.Y
                )
                return true;

            return false;
        }

        ///
        /// Chef if the contents contains the point.
        ///
        /// <param name="x">The x position to check.</param>
        /// <param name="y">The y position to check.</param>
        /// <returns><c>true</c> if the point is inside the content area; otherwise, <c>false</c>.</returns>
        public bool ContentContainsPoint(int x, int y) { return ContentContainsPoint((double)x, (double)y); }
        ///
        /// Chef if the contents contains the point.
        ///
        /// <param name="x">The x position to check.</param>
        /// <param name="y">The y position to check.</param>
        /// <returns><c>true</c> if the point is inside the content area; otherwise, <c>false</c>.</returns>
        public bool ContentContainsPoint(double x, double y)
        {
            if (ContainsPoint(x, y))
            {
                double _x = x - ViewBox.X;
                double _y = y - ViewBox.Y;

                if (_x >= ContentBox.X && _x < ContentBox.Right
                    && _y >= ContentBox.Y && _y < ContentBox.Bottom
                    )
                    return true;
            }
            return false;
        }

        ///
        /// Translates the device position into a position inside the content with respect to
        /// ViewRange-, ContenBox- and Offset-Position.
        ///
        /// <param name="x">The horizontal position on the device.</param>
        /// <param name="y">The vertical position on the device.</param>
        /// <returns>A point with the position inside the content if possible; otherwise a point with the coordinates -1,-1.</returns>
        public Point TranslateDevicePositionToContentPosition(int x, int y)
        {
            var p = TranslateDevicePositionToContentPosition((float)x, (float)y);
            return new Point(
                (int)Math.Round(p.X, 0, MidpointRounding.AwayFromZero),
                (int)Math.Round(p.Y, 0, MidpointRounding.AwayFromZero)
                );
        }
        ///
        /// Translates the device position into a position inside the content with respect to
        /// ViewRange-, ContenBox- and Offset-Position.
        ///
        /// <param name="x">The horizontal position on the device.</param>
        /// <param name="y">The vertical position on the device.</param>
        /// <returns>A point with the position inside the content if possible; otherwise a point with the coordinates -1,-1.</returns>
        public PointF TranslateDevicePositionToContentPosition(double x, double y) { return TranslateDevicePositionToContentPosition((float)x, (float)y); }
        ///
        /// Translates the device position into a position inside the content with respect to
        /// ViewRange-, ContenBox- and Offset-Position.
        ///
        /// <param name="x">The horizontal position on the device.</param>
        /// <param name="y">The vertical position on the device.</param>
        /// <returns>A point with the position inside the content if possible; otherwise a point with the coordinates -1,-1.</returns>
        public PointF TranslateDevicePositionToContentPosition(float x, float y)
        {
            PointF p = new PointF(-1, -1);

            //if (ContentContainsPoint((int)x, (int)y))
            //{
                float _x = x - ViewBox.X - ContentBox.X;
                float _y = y - ViewBox.Y - ContentBox.Y;

                p.X = _x - OffsetPosition.X;
                p.Y = _y - OffsetPosition.Y;
            //}
            return p;
        }

        #endregion

        #region AbstractViewBorderBase

        ///
        /// Gets or sets the border.
        ///
        /// <value>
        /// The border.
        /// </value>
        public override BoxModel Border
        {
            set
            {
                bool fire = !Border.Equals(value);
                base.Border = value;
                if (fire) firePropertyChangedEvent("Border");
            }
        }

        #endregion

        #region AbstractViewPaddingBase

        ///
        /// Gets or sets the padding. The padding is the inner space between the border and the content.
        ///
        /// <value>
        /// The padding.
        /// </value>
        public override BoxModel Padding
        {
            set
            {
                bool fire = !Padding.Equals(value);
                base.Padding = value;
                if (fire) firePropertyChangedEvent("Padding");
            }
        }

        #endregion

        #region AbstractViewMarginBase

        ///
        /// Gets or sets the margin. The margin is the outer space around an area. Space between the objects and the border.
        ///
        /// <value>
        /// The margin.
        /// </value>
        public override BoxModel Margin
        {
            set
            {
                bool fire = !Margin.Equals(value);
                base.Margin = value;
                if (fire) firePropertyChangedEvent("Margin");
            }
        }

        #endregion

        #endregion

    }
}


text:
package de.uni_hildesheim.sse.qmApp.editors;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

import de.uni_hildesheim.sse.ConstraintSyntaxException;
import de.uni_hildesheim.sse.ModelUtility;
import de.uni_hildesheim.sse.qmApp.dialogs.Dialogs;
import de.uni_hildesheim.sse.qmApp.dialogs.DialogsUtil;
import de.uni_hildesheim.sse.qmApp.model.ModelAccess;
import de.uni_hildesheim.sse.ui.embed.EditorUtils;
import net.ssehub.easy.basics.logger.EASyLoggerFactory;
import net.ssehub.easy.basics.modelManagement.ModelInfo;
import net.ssehub.easy.basics.modelManagement.ModelManagementException;
import net.ssehub.easy.dslCore.ui.Activator;
import net.ssehub.easy.dslCore.ui.editors.IEmbeddedEditor;
import net.ssehub.easy.dslCore.ui.editors.IEmbeddedEditor.IValidationStateListener;
import net.ssehub.easy.varModel.confModel.IDecisionVariable;
import net.ssehub.easy.varModel.cst.CSTSemanticException;
import net.ssehub.easy.varModel.cst.ConstraintSyntaxTree;
import net.ssehub.easy.varModel.cst.Parenthesis;
import net.ssehub.easy.varModel.management.VarModel;
import net.ssehub.easy.varModel.model.AbstractVariable;
import net.ssehub.easy.varModel.model.Constraint;
import net.ssehub.easy.varModel.model.ContainableModelElement;
import net.ssehub.easy.varModel.model.DecisionVariableDeclaration;
import net.ssehub.easy.varModel.model.IConstraintHolder;
import net.ssehub.easy.varModel.model.IDecisionVariableContainer;
import net.ssehub.easy.varModel.model.IModelElement;
import net.ssehub.easy.varModel.model.Project;
import net.ssehub.easy.varModel.model.ProjectImport;
import net.ssehub.easy.varModel.model.datatypes.Compound;
import net.ssehub.easy.varModel.model.datatypes.ConstraintType;
import net.ssehub.easy.varModel.model.datatypes.Container;
import net.ssehub.easy.varModel.model.values.ConstraintValue;
import net.ssehub.easy.varModel.model.values.ContainerValue;
import net.ssehub.easy.varModel.model.values.Value;
import net.ssehub.easy.varModel.persistency.ConstraintSplitWriter.IConstraintFilter;
import net.ssehub.easy.varModel.persistency.IVMLWriter;
import net.ssehub.easy.varModel.persistency.StringProvider;

/**
 * Implements an (cell) editor dialog for modifying a single constraints.
 *
 * @author Holger Eichelberger
 */
class ConstraintEditorDialog extends Dialog implements IValidationStateListener {

    private static File tmpFile;

    /**
     * Defines a (wrapping) interface for a constraint editor.
     *
     * @author Holger Eichelberger
     */
    interface IConstraintEditor {

        /**
         * Changes the constraint.
         *
         * @param constraint the new constraint in IVML syntax (may be null or empty)
         */
        public void setConstraint(String constraint);

        /**
         * Returns the constraint.
         *
         * @return the constraint in IVML syntax, possibly empty
         */
        public String getConstraint();

        /**
         * Returns the underlying SWT control.
         *
         * @return the SWT control
         */
        public Control getControl();

        /**
         * Defines the layout data.
         *
         * @param layoutData the layout data
         */
        public void setLayoutData(Object layoutData);

        /**
         * Adds a validation state listener.
         *
         * @param listener the listener
         */
        public void addValidationStateListener(IValidationStateListener listener);

        /**
         * Removes a given validation state listener.
         *
         * @param listener the listener to be removed
         */
        public void removeValidationStateListener(IValidationStateListener listener);

        /**
         * Closes the editor.
         */
        public void close();
    }

    private String constraint;
    private IConstraintEditor editor;
    private IDecisionVariable context;

    /**
     * Creates the dialog.
     *
     * @param context the variable the constraint shall be created in
     * @param parentShell the parent shell
     * @param constraint the initial constraint
     */
    ConstraintEditorDialog(Shell parentShell, IDecisionVariable context, String constraint) {
        super(parentShell);
        this.constraint = constraint;
        this.context = context;
    }

    /**
     * Returns the constraint as text.
     *
     * @return the constraint as text (IVML syntax, separated by ";")
     */
    public String getConstraintText() {
        return constraint;
    }

    @Override
    protected Control createDialogArea(Composite parent) {
        final Composite composite = (Composite) super.createDialogArea(parent);
        composite.setLayout(new GridLayout(1, false));

        Label label = new Label(composite, SWT.NONE);
        label.setText("Variables in current context:");
        TableViewer tableViewer = createContextVariablesTableViewer(composite);
        GridData gridData = new GridData();
        gridData.horizontalAlignment = SWT.FILL;
        gridData.grabExcessHorizontalSpace = true;
        gridData.heightHint = 200;
        tableViewer.getTable().setLayoutData(gridData);

        label = new Label(composite, SWT.NONE);
        label.setText("Constraint (OCL-like syntax, see Help, <Strg>+<Space> = content assist):");

        editor = createConstraintEditor(composite, context, constraint);
        gridData = new GridData();
        gridData.horizontalAlignment = SWT.FILL;
        gridData.grabExcessHorizontalSpace = true;
        gridData.verticalAlignment = SWT.FILL;
        gridData.grabExcessVerticalSpace = true;
        editor.setLayoutData(gridData);
        return composite;
    }

    /**
     * Creates the context variables table viewer.
     *
     * @param parent the parent composite
     * @return the table viewer
     */
    private TableViewer createContextVariablesTableViewer(Composite parent) {
        TableViewer viewer = new TableViewer(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
        Table table = viewer.getTable();
        TableLayout layout = new TableLayout();
        table.setLayout(layout);
        table.setHeaderVisible(true);
        table.setLinesVisible(true);

        TableColumn column = new TableColumn(table, SWT.NONE);
        layout.addColumnData(new ColumnWeightData(3, 30, true));
        column.setText("variable name");
        column.setResizable(true);

        column = new TableColumn(table, SWT.NONE);
        layout.addColumnData(new ColumnWeightData(3, 30, true));
        column.setText("description");
        column.setResizable(true);

        column = new TableColumn(table, SWT.NONE);
        layout.addColumnData(new ColumnWeightData(3, 30, true));
        column.setText("help text");
        column.setResizable(true);

        AbstractVariable var = context.getParent().getDeclaration();
        Set<AbstractVariable> done = new HashSet<AbstractVariable>();
        if (var.getType() instanceof Compound) {
            addVariables((Compound) var.getType(), done);
        }
        IModelElement par = var.getTopLevelParent();
        if (par instanceof Project) {
            addVariables((Project) par, done);
        }
        AbstractVariable[] vars = new AbstractVariable[done.size()];
        done.toArray(vars);
        Arrays.sort(vars, new VariableNameComparator());

        for (int i = 0; i < vars.length; i++) {
            AbstractVariable v = vars[i];
            String comment = ModelAccess.getDescription(v);
            if (null != comment && comment.trim().length() > 0) {
                String[] text = new String[3];
                text[0] = v.getName();
                text[1] = comment;
                text[2] = ModelAccess.getHelpText(v);
                TableItem item = new TableItem(table, SWT.NONE);
                item.setText(text);
            }
        }
        return viewer;
    }

    /**
     * A comparator for abstract variable names.
     *
     * @author Holger Eichelberger
     */
    private static class VariableNameComparator implements Comparator<AbstractVariable> {

        @Override
        public int compare(AbstractVariable o1, AbstractVariable o2) {
            return o1.getName().compareTo(o2.getName());
        }

    }

    /**
     * Adds variables considered as constraint context to done.
     *
     * @param type the type to add variables from
     * @param done the variables
     */
    private void addVariables(IDecisionVariableContainer type, Set<AbstractVariable> done) {
        if (null != type) {
            for (int i = 0; i < type.getDeclarationCount(); i++) {
                AbstractVariable var = type.getDeclaration(i);
                if (!ConstraintType.TYPE.isAssignableFrom(var.getType())
                    && !Container.isContainer(var.getType(), ConstraintType.TYPE)) {
                    if (!done.contains(var)) {
                        done.add(type.getDeclaration(i));
                    }
                }
            }
            for (int a = 0; a < type.getAssignmentCount(); a++) {
                addVariables(type.getAssignment(a), done);
            }
            if (type instanceof Compound) {
                Compound cmp = (Compound) type;
                for (int r = 0; r < cmp.getRefinesCount(); r++) {
                    addVariables(cmp.getRefines(r), done);
                }
            }
        }
    }

    /**
     * Adds variables considered as constraint context to done.
     *
     * @param project the project to add variables from
     * @param done the variables
     */
    private void addVariables(Project project, Set<AbstractVariable> done) {
        for (int c = 0; c < project.getElementCount(); c++) {
            ContainableModelElement elt = project.getElement(c);
            if (elt instanceof DecisionVariableDeclaration) { // no attributes here for now
                done.add((DecisionVariableDeclaration) elt);
            }
        }
    }

    @Override
    protected Control createContents(Composite parent) {
        // create buttons first
        Control result = super.createContents(parent);
        editor.addValidationStateListener(this);
        return result;
    }

    @Override
    protected void okPressed() {
        try {
            String tmp = editor.getConstraint();
            IModelElement parentContext = context.getParent().getDeclaration();
            // context.getDeclaration().getParent()
            ModelUtility.INSTANCE.createExpression(tmp, parentContext);
            constraint = tmp; // if ok, no exception
            super.okPressed();
        } catch (CSTSemanticException e) {
            Dialogs.showErrorDialog("Constraint error", e.getMessage());
        } catch (ConstraintSyntaxException e) {
            Dialogs.showErrorDialog("Constraint error", e.getMessage());
        }
    }

    @Override
    protected void configureShell(Shell newShell) {
        super.configureShell(newShell);
        newShell.setText("Edit constraint");
        DialogsUtil.centerShell(newShell);
    }

    @Override
    protected Point getInitialSize() {
        return new Point(450, 600);
    }

    /**
     * Implements a constraint filter for textually given constraints in a certain context.
     * Having the actual constraint objects would be much more efficient, but the pipeline
     * editor model does not support this. Potentially, we can separate the implementation
     * between the dialog having the constraint object and the pipeline editor somehow, but
     * this is currently the initial implementation.
     *
     * @author Holger Eichelberger
     */
    private static class ConstraintFilter implements IConstraintFilter {

        private Constraint constraint;

        /**
         * Creates a constraint filter.
         *
         * @param constraint the actual constraint to filter for
         */
        private ConstraintFilter(Constraint constraint) {
            this.constraint = constraint;
        }

        @Override
        public boolean splitAt(IModelElement context, ConstraintSyntaxTree constraint) {
            boolean split = false;
            // context = constraint variable
            if (null != this.constraint && constraint == this.constraint.getConsSyntax()) {
                split = true;
            }
            return split;
        }

    }

    /**
     * Creates a constraint editor.
     *
     * @param parent the parent composite
     * @param context the IVML element the constraint is located in
     * @param constraint the initial constraint (may be null for empty)
     * @return the constraint editor (a simple editor will be returned if the real constraint editor cannot be created)
     */
    static IConstraintEditor createConstraintEditor(Composite parent, final IDecisionVariable context,
        String constraint) {
        AbstractVariable decl = context.getDeclaration();
        IConstraintEditor result = null;
        FakeContext tmp = createFakeContext(context, constraint);
        if (null != tmp) {
            result = createEmbeddedEditor(parent, tmp, decl, constraint);
        } else {
            result = createFallbackEditor(parent, constraint);
        }
        return result;
    }

    /**
     * Create a fake context project importing the original containing project. If the constraint(s)
     * in the dialog is/are on project level, they will be stated on project level. Else, a refining
     * compound is created and the constraint(s) is/are placed within. We place each constraint into an own
     * parenthesis and cut this out of the model into prefix / postfix in order to implicitly narrow down the
     * content assist proposal scope.
     *
     * @param context the context of the constraint in terms of a variable (potentially a container of
     *   constraint variables)
     * @param text the constraint text
     * @return the fake context
     */
    private static FakeContext createFakeContext(IDecisionVariable context, String text) {
        FakeContext result = null;
        Project cfg = context.getConfiguration().getProject();
        AbstractVariable decl = context.getParent().getDeclaration();
        IModelElement parent = null;
        if (decl.getType() instanceof Compound) {
            parent = (Compound) decl.getType();
        }
        Project prj = new Project("tmp");
        Constraint constraint = null;
        try {
            ProjectImport imp = new ProjectImport(cfg.getName(), null); // interfaces are ignored for temp models :o ;)
            imp.setResolved(cfg);
            prj.addImport(imp);
            IConstraintHolder constraintParent;
            if (parent instanceof Compound) {
                Compound pCompound = (Compound) parent;
                Compound cmp = new Compound("cmp", prj, pCompound);
                prj.add(cmp);
                constraintParent = cmp;
            } else {
                constraintParent = prj;
            }
            if (Container.isContainer(decl.getType(), ConstraintType.TYPE)) {
                if (context.getValue() instanceof ContainerValue) {
                    ContainerValue val = (ContainerValue) context.getValue();
                    for (int e = 0; e < val.getElementSize(); e++) {
                        constraint = addConstraint(val.getElement(e), constraint, text, constraintParent);
                    }
                }
            } else if (ConstraintType.TYPE.isAssignableFrom(decl.getType())) {
                constraint = addConstraint(context.getValue(), constraint, text, constraintParent);
            }
            if (null == constraint) {
                if (null == text || 0 == text.length()) {
                    text = "(true)";
                }
                ConstraintSyntaxTree cst = ModelUtility.INSTANCE.createExpression(text, context.getDeclaration());
                constraint = new Constraint(cst, constraintParent);
                constraintParent.addConstraint(constraint);
            }
            if (null == tmpFile) {
                tmpFile = File.createTempFile("qmiconf", "cst");
                tmpFile.deleteOnExit();
            }
            FileWriter out = new FileWriter(tmpFile);
            IVMLWriter writer = IVMLWriter.getInstance(out);
            prj.accept(writer);
            IVMLWriter.releaseInstance(writer);
            out.close();
            result = new FakeContext();
            result.info = VarModel.INSTANCE.availableModels().createTempInfo(prj, tmpFile.toURI());
            result.constraint = constraint;
        } catch (ModelManagementException e) {
            EASyLoggerFactory.INSTANCE.getLogger(ConstraintEditorDialog.class, Activator.PLUGIN_ID).exception(e);
        } catch (CSTSemanticException e) {
            EASyLoggerFactory.INSTANCE.getLogger(ConstraintEditorDialog.class, Activator.PLUGIN_ID).exception(e);
        } catch (ConstraintSyntaxException e) {
            EASyLoggerFactory.INSTANCE.getLogger(ConstraintEditorDialog.class, Activator.PLUGIN_ID).exception(e);
        } catch (IOException e) {
            EASyLoggerFactory.INSTANCE.getLogger(ConstraintEditorDialog.class, Activator.PLUGIN_ID).exception(e);
        }
        return result;
    }

    /**
     * Represents the temporary project embedding the textual constraint into the right
     * context so that variables can be resolved properly. Contains the constraint object
     * representing the textual constraint.
     *
     * @author Holger Eichelberger
     */
    private static class FakeContext {
        private ModelInfo<Project> info;
        private Constraint constraint;
    }

    /**
     * Adds a configured constraint to the fake context.
     *
     * @param val the constraint value (may be null, ignored then)
     * @param actual the actual constraint corresponding to the initially given text
     * @param text the constraint text (may be null or empty)
     * @param constraintParent the parent element to store the constraints within
     * @return actual or the constraint created in this method
     */
    private static Constraint addConstraint(Value val, Constraint actual, String text,
        IConstraintHolder constraintParent) {
        if (val instanceof ConstraintValue) {
            ConstraintValue cValue = (ConstraintValue) val;
            ConstraintSyntaxTree cst = cValue.getValue();
            if (null != cst) {
                try {
                    Constraint constraint = new Constraint(new Parenthesis(cst), constraintParent);
                    if (null != text && text.length() > 0 && null == actual) {
                        if (text.equals(StringProvider.toIvmlString(cst))) {
                            actual = constraint;
                        }
                    }
                    constraintParent.addConstraint(constraint);
                } catch (CSTSemanticException e) {
                    EASyLoggerFactory.INSTANCE
                        .getLogger(ConstraintEditorDialog.class, Activator.PLUGIN_ID).exception(e);
                }
            }
        }
        return actual;
    }

    /**
     * Finds a constraint in the fake context model.
     *
     * @param info the fake context model
     * @param constraintText the constraint text to seach for
     * @return the resulting constraint
     */
    private static Constraint findConstraint(FakeContext info, String constraintText) {
        Constraint result = null;
        Project prj = info.info.getResolved();
        if (null != prj) {
            for (int e = 0; null == result && e < prj.getElementCount(); e++) {
                ContainableModelElement elt = prj.getElement(e);
                if (elt instanceof Compound) {
                    Compound cmp = (Compound) elt;
                    for (int c = 0; null == result && c < cmp.getConstraintsCount(); c++) {
                        result = checkConstraint(cmp.getConstraint(c), constraintText, result);
                    }
                } else if (elt instanceof Constraint) {
                    result = checkConstraint((Constraint) elt, constraintText, result);
                }
            }
        }
        return result;
    }

    /**
     * Checks a constraint in the fake context model against the given constraintText. Considers
     * artificial inserted parenthesis.
     *
     * @param constraint the constraint to check
     * @param constraintText the constraint text to search for
     * @param result the resulting constraint found so far (match checking happens only if null)
     * @return constraint if match or result otherways
     */
    private static Constraint checkConstraint(Constraint constraint, String constraintText, Constraint result) {
        if (null == result) {
            ConstraintSyntaxTree cst = constraint.getConsSyntax();
            if (cst instanceof Parenthesis) { // strip artificial parenthesis
                cst = ((Parenthesis) cst).getExpr();
            }
            if (StringProvider.toIvmlString(cst).equals(constraintText)) {
                result = constraint;
            }
        }
        return result;
    }

    /**
     * Creates the embedded xText constraint editor.
     *
     * @param parent the parent composite
     * @param info the model info of the fake context
     * @param context the IVML element the constraint is located in
     * @param constraint the initial constraint (may be null for empty)
     * @return the embedded editor or, if not possible, {@link #createFallbackEditor(Composite)}
     */
    private static IConstraintEditor createEmbeddedEditor(Composite parent, final FakeContext info,
        final IModelElement context, String constraint) {
        IConstraintEditor result;
        IConstraintFilter filter = new ConstraintFilter(info.constraint);
        final IEmbeddedEditor editor = EditorUtils.embedIvmlConstraintEditor(info.info, parent, filter, true);
        if (null != editor) {
            result = new IConstraintEditor() {
                @Override
                public void setConstraint(String constraintText) {
                    EditorUtils.setConstraint(editor, info.info,
                        new ConstraintFilter(findConstraint(info, constraintText)), true);
                }

                @Override
                public String getConstraint() {
                    return editor.getEditableContent();
                }

                @Override
                public Control getControl() {
                    return editor.getViewer().getControl();
                }

                @Override
                public void setLayoutData(Object layoutData) {
                    getControl().setLayoutData(layoutData);
                }

                @Override
                public void addValidationStateListener(IValidationStateListener listener) {
                    editor.addValidationStateListener(listener);
                }

                @Override
                public void removeValidationStateListener(IValidationStateListener listener) {
                    editor.removeValidationStateListener(listener);
                }

                @Override
                public void close() {
                    VarModel.INSTANCE.availableModels().releaseTempInfo(info.info);
                }

            };
        } else {
            result = createFallbackEditor(parent, constraint);
        }
        return result;
    }

    /**
     * Creates the fallback editor.
     *
     * @param parent the parent composite
     * @param constraint the initial constraint (may be null for empty)
     * @return the fallback editor
     */
    private static IConstraintEditor createFallbackEditor(Composite parent, String constraint) {
        final Text xTextEditor = new Text(parent, SWT.BORDER);
        xTextEditor.setEnabled(false);
        if (null != constraint) {
            xTextEditor.setText(constraint);
        }
        return new IConstraintEditor() {
            @Override
            public void setConstraint(String constraint) {
                String text = null == constraint ? "" : constraint;
                xTextEditor.setText(text);
            }

            @Override
            public String getConstraint() {
                return xTextEditor.getText();
            }

            @Override
            public Control getControl() {
                return xTextEditor;
            }

            @Override
            public void setLayoutData(Object layoutData) {
                xTextEditor.setLayoutData(layoutData);
            }

            @Override
            public void addValidationStateListener(IValidationStateListener listener) {
                // ignore
            }

            @Override
            public void removeValidationStateListener(IValidationStateListener listener) {
                // ignore
            }

            @Override
            public void close() {
                // ignore
            }

        };
    }

    @Override
    public void notifyValidationState(final boolean hasErrors) {
        // not regularly called, button state may be wrong
        /*getShell().getDisplay().asyncExec(new Runnable() {

            @Override
            public void run() {
                getButton(IDialogConstants.OK_ID).setEnabled(!hasErrors);
            }

        });*/
    }

    @Override
    public boolean close() {
        editor.removeValidationStateListener(this);
        return super.close();
    }

}

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://travis-ci.org/afonsof/NHibernateBootstrap.png?branch=master)](https://travis-ci.org/afonsof/NHibernateBootstrap)
[![Built with Grunt](https://cdn.gruntjs.com/builtwith.png)](http://gruntjs.com/)
NHibernateBootstrap
===================

Start a NHibernate Repository application in seconds

## Getting Started

#### 1. Setting Up

1.1 Create a project and install NHibernateBootstrap using Nuget:
```
PM> Install-Package NHibernateBootstrap
```

1.2 Install a Database provider (for example: MySQL)
```
PM> Install-Package MySql.Data
```

#### 2. Create entity classes
All entity classes must implement ``IHaveId`` interface and all properties must be virtual according with the following example:
```c#
public class Person : IHaveId
{
    public virtual int Id { get; set; }

    [Required]
    public virtual string Name { get; set; }

    [Required]
    public virtual string Phone { get; set; }

    [Required]
    public virtual string Email { get; set; }
}
```

#### 3. Create a UnitOfWork class inhreriting UnitOfWorkBase class. This class will be used to store and manage your repositories:

```c#
public class UnitOfWork: UnitOfWorkBase
{
    private IRepository<Person> _person;

    //On demand repository initialization
    public IRepository<Person> PersonRepository
    {
        get { return _person ?? (_person = new Repository<Person>(this)); }
    }
}
```

#### 4. Call the Setup method in Application Startup. It can be used in global.asax Application_Start method:
```c#
protected void Application_Start()
{
    var cs = "Server=localhost;Database=myapp;Uid=root;Pwd=root;"
    NHibernateBuilder.Setup<UnitOfWork>(MySQLConfiguration.Standard.ConnectionString(cs));
    ...
}
```
In this case we're using a raw connection string, but you can read it in web.config.

You will need to pass to Setup method any class of entities' assembly. Here the created ``UnitOfWork`` class were used.

When the application begins the Database schema will always be created/updated.

#### 5. Use the UnitOfWork wherever you want, including in MVC Controllers:
```c#
public class PersonController : Controller
{
    private readonly UnitOfWork _db = new UnitOfWork();

    public ActionResult Index()
    {
        return View(_db.PersonRepository.AsQueryable().ToList());
    }

    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Person person)
    {
        if (ModelState.IsValid)
        {
            _db.PersonRepository.Add(person);
            _db.Commit();
            return RedirectToAction("Index");
        }
        return View(person);
    }

    public ActionResult Edit(int id = 0)
    {
        var person = _db.PersonRepository.Find(id);
        return View(person);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Person person)
    {
        if (ModelState.IsValid)
        {
            _db.PersonRepository.Edit(person);
            _db.Commit();
            return RedirectToAction("Index");
        }
        return View(vm);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Delete(int id = 0)
    {
        var person = _db.PersonRepository.Find(id);
        _db.PersonRepository.Remove(person);
        _db.Commit();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        _db.Dispose();
        base.Dispose(disposing);
    }
}
```

## Contributing

Please use the issue tracker and pull requests.

## License
Copyright (c) 2014 Afonso França
Licensed under the MIT license.


text:
package controllers.helpers;

import java.util.List;
import java.util.ArrayList;
import models.core.ChoiceText;

public class ChoiceTextHolder {
	public String rightChoice;
	public List<String> wrongChoice = new ArrayList<String>();
}


text:
package org.joda.beans;

import java.util.Map;

/**
 * A map of properties that is linked to a specific bean.
 *

 * For a JavaBean, this will ultimately wrap get/set method pairs.
 * Alternate implementations may perform any logic to obtain the value.
 *
 * @author Stephen Colebourne
 */
public interface PropertyMap extends Map<String, Property<?>> {

    /**
     * Flattens the contents of this property map to a {@code Map}.
     *

     * The returned map will contain all the properties from the bean with their actual values.
     *
     * @return the unmodifiable map of property name to value, not null
     */
    Map<String, Object> flatten();

}


text:
<!DOCTYPE html>
<html lang="pt-br">
<head>
<script type="text/javascript">
window.location = 'http://kabanas.info/imprint';
</script>
</head>
</html>


text:
var version = require('./version')

module.exports = factory = (function() {
  function header() {
    return "COUL " + version + " "
  }

  function process_body(body) {
    if (body.slice(-1) != "\n") {
      return body + "\n"
    } else {
      return body;
    }
  }

  this.ping = function() {
    return header() + "PING\n\n"
  }

  this.pong = function() {
    return header() + "PONG\n\n"
  }

  this.smsg = function(nick, server, channel, timestamp, message) {
    message = process_body(message)
    return header() + "SMSG " + nick + "@" + server + " " + channel + " " + timestamp + "\n" + message + "\n"
  }

  this.msg = function(channel, message) {
    message = process_body(message)
    return header() + "MSG " + channel + "\n" + message + "\n"
  }

  this.alert = function(source, timestamp, message) {
    if (source != "SERVER" && source != "NETWORK") {
      throw new Error("Source needs to be SERVER or NETWORK")
    }
    message = process_body(message)
    return header() + "ALERT " + source + " " + timestamp + "\n" + message + "\n"
  }

  this.now = {
  }

  this.now.smsg = function(nick, server, channel, message) {
    var now = new Date() / 1000;
    return factory.smsg(nick, server, channel, now, message);
  }

  this.now.alert = function(source, message) {
    var now = new Date() / 1000;
    return factory.alert(source, now, message);
  }

  return this;

})()


text:
import { ChartBullet24 } from "../../";

export = ChartBullet24;


text:
#ifndef WEBRTC_MODULES_AUDIO_PROCESSING_AEC_DUMP_WRITE_TO_FILE_TASK_H_
#define WEBRTC_MODULES_AUDIO_PROCESSING_AEC_DUMP_WRITE_TO_FILE_TASK_H_

#include <memory>
#include <string>
#include <utility>

#include "webrtc/base/checks.h"
#include "webrtc/base/event.h"
#include "webrtc/base/ignore_wundef.h"
#include "webrtc/base/platform_file.h"
#include "webrtc/base/task_queue.h"
#include "webrtc/system_wrappers/include/file_wrapper.h"

// Files generated at build-time by the protobuf compiler.
RTC_PUSH_IGNORING_WUNDEF()
#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
#include "external/webrtc/webrtc/modules/audio_processing/debug.pb.h"
#else
#include "webrtc/modules/audio_processing/debug.pb.h"
#endif
RTC_POP_IGNORING_WUNDEF()

namespace webrtc {

class WriteToFileTask : public rtc::QueuedTask {
 public:
  WriteToFileTask(webrtc::FileWrapper* debug_file,
                  int64_t* num_bytes_left_for_log);
  ~WriteToFileTask() override;

  audioproc::Event* GetEvent();

 private:
  bool IsRoomForNextEvent(size_t event_byte_size) const;

  void UpdateBytesLeft(size_t event_byte_size);

  bool Run() override;

  webrtc::FileWrapper* debug_file_;
  audioproc::Event event_;
  int64_t* num_bytes_left_for_log_;
};

}  // namespace webrtc

#endif  // WEBRTC_MODULES_AUDIO_PROCESSING_AEC_DUMP_WRITE_TO_FILE_TASK_H_


text:
namespace mi
{
        template <typename T>
        class WatershedProcessor
        {
        private:
                const VolumeData<float>& _weightData;
        public:
                WatershedProcessor ( const VolumeData<float>& weightData ) :  _weightData( weightData ) {
                        return;
                }

                bool process ( VolumeData<T>& labelData ) {
                        const VolumeInfo& info = const_cast<VolumeData<T>&>( labelData ).getInfo();
                        Range range( info.getMin(), info.getMax() );

                        if ( 1 ) { //@ the program will be failed when "if" is removed.
                                PriorityQueue <Point3i> pq;

                                for( Range::iterator iter = range.begin() ; iter != range.end() ; ++iter ) {
                                        const Point3i& p = *iter;
                                        if ( labelData.get( p ) > 0 && this->_weightData.get( p ) > 0 ) {
                                                pq.push( p, -this->_weightData.get( p ) ) ;
                                        }
                                }

                                while( !pq.empty() ) {
                                        const Point3i p = pq.getTopIndex();
                                        pq.pop();
                                        const int labelId = labelData.get( p ); // Label ID to be propagated.
                                        for( Neighbor::iterator diter = Neighbor::begin() ; diter != Neighbor::end( 6 ) ; ++diter ) {
                                                const Point3i np = *diter + p;
                                                if ( ! info.isValid( np ) ) continue;
                                                if ( labelData.get( np ) != 0 ) continue;
                                                if( this->_weightData.get( np ) > 0 ) {
                                                        labelData.set( np, labelId );
                                                        pq.push( np, -this->_weightData.get( np ) );
                                                }
                                        }
                                }
                        }
                        return true;
                }
        };
}
#endif// MI_WATERSHED_PROCESSOR_HPP


text:
package com.opengamma.strata.product.swap.type;

import java.time.LocalDate;
import java.time.Period;

import org.joda.convert.FromString;
import org.joda.convert.ToString;

import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.basics.ReferenceDataNotFoundException;
import com.opengamma.strata.basics.date.Tenor;
import com.opengamma.strata.collect.ArgChecker;
import com.opengamma.strata.collect.named.ExtendedEnum;
import com.opengamma.strata.collect.named.Named;
import com.opengamma.strata.product.TradeInfo;
import com.opengamma.strata.product.common.BuySell;
import com.opengamma.strata.product.swap.SwapTrade;

/**
 * A market convention for Ibor-Ibor swap trades.
 *

 * This defines the market convention for a Ibor-Ibor single currency swap.
 * The convention is formed by combining two swap leg conventions in the same currency.
 *

 * The market price is for the difference (spread) between the values of the two legs.
 * This convention has two legs, the "spread leg" and the "flat leg". The spread will be
 * added to the "spread leg", which is typically the leg with the shorter underlying tenor.
 * The payment frequency is typically determined by the longer underlying tenor, with
 * compounding applied.
 *

 * For example, a 'USD 3s1s' basis swap has 'USD-LIBOR-1M' as the spread leg and 'USD-LIBOR-3M'
 * as the flat leg. Payment is every 3 months, with the one month leg compounded.
 *

 * To manually create a convention, see {@link ImmutableIborIborSwapConvention}.
 * To register a specific convention, see {@code IborIborSwapConvention.ini}.
 */
public interface IborIborSwapConvention
    extends SingleCurrencySwapConvention, Named {

  /**
   * Obtains an instance from the specified unique name.
   *
   * @param uniqueName  the unique name
   * @return the convention
   * @throws IllegalArgumentException if the name is not known
   */
  @FromString
  public static IborIborSwapConvention of(String uniqueName) {
    ArgChecker.notNull(uniqueName, "uniqueName");
    return extendedEnum().lookup(uniqueName);
  }

  /**
   * Gets the extended enum helper.
   *

   * This helper allows instances of the convention to be looked up.
   * It also provides the complete set of available instances.
   *
   * @return the extended enum helper
   */
  public static ExtendedEnum<IborIborSwapConvention> extendedEnum() {
    return IborIborSwapConventions.ENUM_LOOKUP;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the market convention of the floating leg that has the spread applied.
   *

   * The spread is the market price of the instrument.
   * It is added to the observed interest rate.
   *
   * @return the spread leg convention
   */
  public abstract IborRateSwapLegConvention getSpreadLeg();

  /**
   * Gets the market convention of the floating leg that does not have the spread applied.
   *
   * @return the flat leg convention
   */
  public abstract IborRateSwapLegConvention getFlatLeg();

  //-------------------------------------------------------------------------
  /**
   * Creates a spot-starting trade based on this convention.
   *

   * This returns a trade based on the specified tenor. For example, a tenor
   * of 5 years creates a swap starting on the spot date and maturing 5 years later.
   *

   * The notional is unsigned, with buy/sell determining the direction of the trade.
   * If buying the swap, the rate of the flat leg is received from the counterparty,
   * with the rate of the spread leg being paid. If selling the swap, the opposite occurs.
   *
   * @param tradeDate  the date of the trade
   * @param tenor  the tenor of the swap
   * @param buySell  the buy/sell flag
   * @param notional  the notional amount
   * @param spread  the spread, typically derived from the market
   * @param refData  the reference data, used to resolve the trade dates
   * @return the trade
   * @throws ReferenceDataNotFoundException if an identifier cannot be resolved in the reference data
   */
  @Override
  public default SwapTrade createTrade(
      LocalDate tradeDate,
      Tenor tenor,
      BuySell buySell,
      double notional,
      double spread,
      ReferenceData refData) {

    // override for Javadoc
    return SingleCurrencySwapConvention.super.createTrade(tradeDate, tenor, buySell, notional, spread, refData);
  }

  /**
   * Creates a forward-starting trade based on this convention.
   *

   * This returns a trade based on the specified period and tenor. For example, a period of
   * 3 months and a tenor of 5 years creates a swap starting three months after the spot date
   * and maturing 5 years later.
   *

   * The notional is unsigned, with buy/sell determining the direction of the trade.
   * If buying the swap, the rate of the flat leg is received from the counterparty,
   * with the rate of the spread leg being paid. If selling the swap, the opposite occurs.
   *
   * @param tradeDate  the date of the trade
   * @param periodToStart  the period between the spot date and the start date
   * @param tenor  the tenor of the swap
   * @param buySell  the buy/sell flag
   * @param notional  the notional amount
   * @param spread  the spread, typically derived from the market
   * @param refData  the reference data, used to resolve the trade dates
   * @return the trade
   * @throws ReferenceDataNotFoundException if an identifier cannot be resolved in the reference data
   */
  @Override
  public default SwapTrade createTrade(
      LocalDate tradeDate,
      Period periodToStart,
      Tenor tenor,
      BuySell buySell,
      double notional,
      double spread,
      ReferenceData refData) {

    // override for Javadoc
    return SingleCurrencySwapConvention.super.createTrade(tradeDate, periodToStart, tenor, buySell, notional, spread, refData);
  }

  /**
   * Creates a trade based on this convention.
   *

   * This returns a trade based on the specified dates.
   *

   * The notional is unsigned, with buy/sell determining the direction of the trade.
   * If buying the swap, the rate of the flat leg is received from the counterparty,
   * with the rate of the spread leg being paid. If selling the swap, the opposite occurs.
   *
   * @param tradeDate  the date of the trade
   * @param startDate  the start date
   * @param endDate  the end date
   * @param buySell  the buy/sell flag
   * @param notional  the notional amount
   * @param spread  the spread, typically derived from the market
   * @return the trade
   */
  @Override
  public default SwapTrade toTrade(
      LocalDate tradeDate,
      LocalDate startDate,
      LocalDate endDate,
      BuySell buySell,
      double notional,
      double spread) {

    // override for Javadoc
    return SingleCurrencySwapConvention.super.toTrade(tradeDate, startDate, endDate, buySell, notional, spread);
  }

  /**
   * Creates a trade based on this convention.
   *

   * This returns a trade based on the specified dates.
   *

   * The notional is unsigned, with buy/sell determining the direction of the trade.
   * If buying the swap, the rate of the flat leg is received from the counterparty,
   * with the rate of the spread leg being paid. If selling the swap, the opposite occurs.
   *
   * @param tradeInfo  additional information about the trade
   * @param startDate  the start date
   * @param endDate  the end date
   * @param buySell  the buy/sell flag
   * @param notional  the notional amount
   * @param spread  the spread, typically derived from the market
   * @return the trade
   */
  @Override
  public abstract SwapTrade toTrade(
      TradeInfo tradeInfo,
      LocalDate startDate,
      LocalDate endDate,
      BuySell buySell,
      double notional,
      double spread);

  //-------------------------------------------------------------------------
  /**
   * Gets the name that uniquely identifies this convention.
   *

   * This name is used in serialization and can be parsed using {@link #of(String)}.
   *
   * @return the unique name
   */
  @ToString
  @Override
  public abstract String getName();

}


text:
import time

import gevent

import pytest

from concurrently import concurrently, GeventEngine, UnhandledExceptions

from . import EngineTest, paramz_conc_count, paramz_data_count

def process(data):
    gevent.sleep(data)
    return time.time()

class TestGeventEngine(EngineTest):

    @paramz_conc_count
    @paramz_data_count
    def test_concurrently(self, conc_count, data_count):
        data = range(data_count)
        i_data = iter(data)
        results = {}
        start_time = time.time()

        @concurrently(conc_count, engine=GeventEngine)
        def _parallel():
            for d in i_data:
                res = process(d)
                results[d] = res

        _parallel()

        def calc_delta(n):
            if n // conc_count == 0:
                return n
            return n + calc_delta(n - conc_count)

        assert len(results) == data_count
        for n, v in results.items():
            delta = v - start_time
            assert int(delta) == calc_delta(n)

    def test_stop(self):
        data = range(3)
        i_data = iter(data)
        results = {}
        start_time = time.time()

        @concurrently(2, engine=GeventEngine)
        def _parallel():
            for d in i_data:
                r = process(d)
                results[d] = r

        gevent.sleep(0.5)
        _parallel.stop()

        assert len(results) == 1
        assert int(results[0]) == int(start_time)

    def test_exception(self):
        data = range(2)
        i_data = iter(data)

        @concurrently(2, engine=GeventEngine)
        def _parallel():
            for d in i_data:
                if d == 1:
                    raise RuntimeError()

        with pytest.raises(UnhandledExceptions) as exc:
            _parallel()

        assert len(exc.value.exceptions) == 1
        assert isinstance(exc.value.exceptions[0], RuntimeError)

    def test_exception_suppress(self):
        data = range(2)
        i_data = iter(data)
        results = {}
        start_time = time.time()

        @concurrently(2, engine=GeventEngine)
        def _parallel():
            for d in i_data:
                if d == 1:
                    raise RuntimeError()
                res = process(d)
                results[d] = res

        _parallel(suppress_exceptions=True)

        assert len(results) == 1
        assert int(results[0]) == int(start_time)

        exc_list = _parallel.exceptions()
        assert len(exc_list) == 1
        assert isinstance(exc_list[0], RuntimeError)

    def test_fail_hard(self):
        i_data = iter(range(4))
        results = {}

        @concurrently(3, engine=GeventEngine)
        def _parallel():
            for d in i_data:
                if d == 1:
                    raise RuntimeError()
                gevent.sleep(d)
                results[d] = True

        with pytest.raises(RuntimeError):
            _parallel(fail_hard=True)

        assert len(results) == 1
        assert results[0]


text:
<#PSScriptInfo

.VERSION 1.0.0

.GUID 80d306fa-8bd4-4a8d-9f7a-bf40df95e661

.AUTHOR DSC Community

.COMPANYNAME DSC Community

.COPYRIGHT DSC Community contributors. All rights reserved.

.TAGS

.LICENSEURI https://github.com/dsccommunity/SharePointDsc/blob/master/LICENSE

.PROJECTURI https://github.com/dsccommunity/SharePointDsc

.ICONURI https://dsccommunity.org/images/DSC_Logo_300p.png

.EXTERNALMODULEDEPENDENCIES

.REQUIREDSCRIPTS

.EXTERNALSCRIPTDEPENDENCIES

.RELEASENOTES
Updated author, copyright notice, and URLs.

.PRIVATEDATA

#>

<#

.DESCRIPTION
 This example shows how to apply site use and deletion settings to the specified web application

#>

Configuration Example
{
    param
    (
        [Parameter(Mandatory = $true)]
        [PSCredential]
        $SetupAccount
    )

    Import-DscResource -ModuleName SharePointDsc

    node localhost
    {
        SPWebAppSiteUseAndDeletion ConfigureSiteUseAndDeletion
        {
            WebAppUrl                                = "http://example.contoso.local"
            SendUnusedSiteCollectionNotifications    = $true
            UnusedSiteNotificationPeriod             = 90
            AutomaticallyDeleteUnusedSiteCollections = $true
            UnusedSiteNotificationsBeforeDeletion    = 24
            PsDscRunAsCredential                     = $SetupAccount
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<title>Python: module PshellControl</title>
<meta charset="utf-8">

<big><big>PshellControl</big></big>	index
/home/riovine/tools/pshell/python/src/PshellControl.py

<tt>A Python module to invoke pshell commands in another process

This API provides the ability for a client program to invoke pshell commands

that are registered in a remote program that is running a pshell UDP or UNIX

server.  The format of the command string that is sent to the pshell should

be in the same usage format that the given command is expecting.  This

provides a very lightweight way to provide a control mechanism into a program

that is running a PshellServer, this is analagous to a remote procedure call (rpc).

This module provides the same functionality as the PshellControl.h API and

the libpshell-control linkable 'C' library, but implemented as a Python

module.

A complete example of the usage of the API can be found in the included

demo programs pshellControlDemo.py and pshellAggregatorDemo.py

Functions:

  connectServer()        -- connect to a remote pshell server

  disconnectServer()     -- disconnect from a remote pshell server

  disconnectAllServers() -- disconnect from all connected remote pshell servers

  setDefaultTimeout()    -- set the default server response timeout

  extractCommands()      -- extract all commands from remote server

  addMulticast()         -- add a command keyword to a multicast group

  sendMulticast()        -- send a command to a multicast group

  sendCommand1()         -- send command to server using default timeout, no results extracted

  sendCommand2()         -- send command to server using timeout override, no results extracted

  sendCommand3()         -- send command to server using default timeout, results extracted

  sendCommand4()         -- send command to server using timeout override, results extracted

  getResponseString()    -- return the human readable form of one of the command response return codes

  setLogLevel()          -- set the internal log level for this module

  setLogFunction()       -- register a user function to receive all logs

Integer constants:

Helpful items used for the server response timeout values

  NO_WAIT

  WAIT_FOREVER

  ONE_MSEC

  ONE_SEC

  ONE_MINUTE

  ONE_HOUR

These are returned from the sendCommandN functions

  COMMAND_SUCCESS

  COMMAND_NOT_FOUND

  COMMAND_INVALID_ARG_COUNT

  SOCKET_SEND_FAILURE

  SOCKET_SELECT_FAILURE

  SOCKET_RECEIVE_FAILURE

  SOCKET_TIMEOUT

  SOCKET_NOT_CONNECTED

Constants to let the host program set the internal debug log level,

if the user of this API does not want to see any internal message

printed out, set the debug log level to LOG_LEVEL_NONE, the default

log level is LOG_LEVEL_ALL

  LOG_LEVEL_NONE

  LOG_LEVEL_ERROR

  LOG_LEVEL_WARNING

  LOG_LEVEL_INFO

  LOG_LEVEL_ALL

  LOG_LEVEL_DEFAULT

String constants:

This is used for the host when connecting to a server running

at the loopback localhost address

  LOCALHOST

Use this as the "port" identifier for the connectServer

call when using a UNIX domain server

  UNIX

Specifies if the addMulticast should add the given command to all specified

multicast receivers or if all control destinations should receive the given

multicast command

  MULTICAST_ALL</tt>

<big>Modules</big>

<tt>      </tt>

fcntl

fnmatch

os

	random

select

socket

	struct

sys

time

<big>Functions</big>

<tt>      </tt>

addMulticast(command, controlList)

<tt>This command will add a controlList of multicast receivers to a multicast

group, multicast groups are based either on a specified command, or if the

special argument PSHELL_MULTICAST_ALL is used, the given controlList will

receive all multicast commands, the format of the controlList is a CSV formatted

list of all the desired controlNames (as provided in the first argument of the

PshellControl.connectServer command) that will receive this multicast command

or if the PSHELL_MULTICAST_ALL is used then all control destinations will receive

the given multicast command, see examples below

ex 1: multicast command sent to receivers in CSV controlList

  PshellControl.addMulticast("command", "control1,control2,control3")

ex 2: all multicast commands sent to receivers in CSV controlList

  PshellControl.addMulticast(PshellControl.MULTICAST_ALL, "control1,control2,control3")

ex 3: multicast command sent to all receivers

  PshellControl.addMulticast("command", PshellControl.MULTICAST_ALL)

ex 4: all multicast commands sent to all receivers

  PshellControl.addMulticast(PshellControl.MULTICAST_ALL, PshellControl.MULTICAST_ALL)

  Args:

      command (str)     : The multicast command that will be distributed to the

                          following controlList, if the special MULTICAST_ALL

                          identifier is used, then the controlList will receive

                          all multicast initiated commands

      controlList (str) : A CSV formatted list of all the desired controlNames

                          (as provided in the first argument of the connectServer

                          command) that will receive this multicast command, if

                          the special MULTICAST_ALL identifier is used, then

                          all control destinations will receive the command

  Returns:

      none</tt>

connectServer(controlName, remoteServer, port, defaultTimeout)

<tt>Connect to a pshell server in another process, note that this does

not do any handshaking to the remote pshell or maintain a connection

state, it meerly sets the internal destination remote pshell server

information to use when sending commands via the sendCommandN

functions and sets up any resources necessary for the source socket,

the timeout value is the number of milliseconds to wait for a response

from the remote command in the sendCommandN functions, a timeout

value of 0 will not wait for a response, in which case the function

will return either SOCKET_NOT_CONNECTED, SOCKET_SEND_FAILURE, or

COMMAND_SUCCESS, the timeout value entered in this function will

be used as the default timeout for all calls to sendCommandN that

do not provide an override timeout value, for a UDP server, the

remoteServer must be either a valid hostname or IP address and a

valid destination port must be provided, for a UNIX server, only

a valid server name must be provided along with the identifier

PshellControl.UNIX for the 'port' parameter

  Args:

      controlName (str)    : The logical name of the control server

      remoteServer (str)   : The server name (UNIX) or hostname/IP address (UDP) of the remote server

      port (str)           : The UDP port of the remote server

      defaultTimeout (int) : The default timeout (in msec) for the remote server response

  Returns:

      bool: Indicates if the local source endpoint is successfully created</tt>

disconnectAllServers()

<tt>Use this function to cleanup any resources for all connected servers, this

function should be called upon program termination, either in a graceful

termination or within an exception signal handler, it is especially important

that this be called when a unix server is used since there are associated file

handles that need to be cleaned up

  Args:

      none

  Returns:

      none</tt>

disconnectServer(controlName)

<tt>Cleanup any resources associated with the server connection, including

releasing any temp file handles, closing any local socket handles etc.

  Args:

      controlName (string) : The control name used in the ConnectServer call

  Returns:

      none</tt>

extractCommands(controlName, includeName=True)

<tt>This function will extract all the commands of a remote pshell server and

present them in a human readable form, this is useful when writing a multi

server control aggregator, see the demo program pshellAggregatorDemo.py in

the demo directory for examples

  Args:

      controlName (string) : The control name used in the ConnectServer call

      includeName (bool)   : Include server name in banner

  Returns:

      str : The remote server's command list in human readable form</tt>

getResponseString(retCode)

<tt>Return the human readable form of one of the command response return codes

  Args:

      retCode (int) : One of the return codes from the above sendCommand

                      functions

  Returns:

      str: The human readable results of the command response</tt>

sendCommand1(controlName, command)

<tt>Send a command using the default timeout setup in the connectServer call,

if the default timeout is 0, the server will not reply with a response and

this function will not wait for one

  Args:

      controlName (string) : The control name used in the ConnectServer call

      command (str)        : The command to send to the remote server

  Returns:

      int: Return code result of the command:

             COMMAND_SUCCESS

             COMMAND_NOT_FOUND

             COMMAND_INVALID_ARG_COUNT

             SOCKET_SEND_FAILURE

             SOCKET_SELECT_FAILURE

             SOCKET_RECEIVE_FAILURE

             SOCKET_TIMEOUT

             SOCKET_NOT_CONNECTED</tt>

sendCommand2(controlName, timeoutOverride, command)

<tt>Send a command overriding the default timeout, if the override timeout is 0,

the server will not reply with a response and this function will not wait for

one

  Args:

      controlName (string)  : The control name used in the ConnectServer call

      timeoutOverride (int) : The server timeout override (in msec) for this command

      command (str)         : The command to send to the remote server

  Returns:

      int: Return code result of the command:

             COMMAND_SUCCESS

             COMMAND_NOT_FOUND

             COMMAND_INVALID_ARG_COUNT

             SOCKET_SEND_FAILURE

             SOCKET_SELECT_FAILURE

             SOCKET_RECEIVE_FAILURE

             SOCKET_TIMEOUT

             SOCKET_NOT_CONNECTED</tt>

sendCommand3(controlName, command)

<tt>Send a command using the default timeout setup in the connectServer call and

return any results received in the payload, if the default timeout is 0, the

server will not reply with a response and this function will not wait for one,

and no results will be extracted

  Args:

      controlName (string) : The control name used in the ConnectServer call

      command (str)        : The command to send to the remote server

  Returns:

      str: The human readable results of the command response or NULL

           if no results or command failure

      int: Return code result of the command:

             COMMAND_SUCCESS

             COMMAND_NOT_FOUND

             COMMAND_INVALID_ARG_COUNT

             SOCKET_SEND_FAILURE

             SOCKET_SELECT_FAILURE

             SOCKET_RECEIVE_FAILURE

             SOCKET_TIMEOUT

             SOCKET_NOT_CONNECTED</tt>

sendCommand4(controlName, timeoutOverride, command)

<tt>Send a command overriding the default timeout and return any results received

in the payload, if the timeout override default timeout is 0, the server will

not reply with a response and this function will not wait for one, and no

results will be extracted

  Args:

      controlName (string)  : The control name used in the ConnectServer call

      timeoutOverride (int) : The server timeout override (in msec) for this command

      command (str)         : The command to send to the remote server

  Returns:

      str: The human readable results of the command response or NULL

           if no results or command failure

      int: Return code result of the command:

             COMMAND_SUCCESS

             COMMAND_NOT_FOUND

             COMMAND_INVALID_ARG_COUNT

             SOCKET_SEND_FAILURE

             SOCKET_SELECT_FAILURE

             SOCKET_RECEIVE_FAILURE

             SOCKET_TIMEOUT

             SOCKET_NOT_CONNECTED</tt>

sendMulticast(command)

<tt>This command will send a given command to all the registered multicast

receivers for this multicast group, multicast groups are based on the

command's keyword, this function will issue the command as a best effort

fire-and-forget command to each receiver in the multicast group, no

results will be requested or expected, and no response will be requested

or expected

  Args:

      command (str) : The command to send to the remote server

  Returns:

      none</tt>

setDefaultTimeout(controlName, defaultTimeout)

<tt>Set the default server response timeout that is used in the 'send' commands

that don't take a timeout override

  Args:

      controlName (string) : The control name used in the ConnectServer call

      defaultTimeout (int) : The default timeout (in msec) for the remote server response

  Returns:

      none</tt>

setLogFunction(function)

<tt>Provide a user callback function to send the logs to, this allows an

application to get all the logs issued by this module to put in it's

own logfile.  If a log function is not set, all internal logs are just

sent to the 'print' function.

  Args:

      function (ptr) : Log callback function

  Returns:

      None</tt>

setLogLevel(level)

<tt>Set the internal log level, valid levels are:

LOG_LEVEL_ERROR

LOG_LEVEL_WARNING

LOG_LEVEL_INFO

LOG_LEVEL_ALL

LOG_LEVEL_DEFAULT

Where the default is LOG_LEVEL_ALL

  Args:

      level (int) : The desired log level to set

  Returns:

      None</tt>

<big>Data</big>

<tt>      </tt>
COMMAND_INVALID_ARG_COUNT = 2

COMMAND_NOT_FOUND = 1

COMMAND_SUCCESS = 0

LOCALHOST = 'localhost'

LOG_LEVEL_ALL = 3

LOG_LEVEL_DEFAULT = 3

LOG_LEVEL_ERROR = 1

LOG_LEVEL_INFO = 3

LOG_LEVEL_NONE = 0

LOG_LEVEL_WARNING = 2

MULTICAST_ALL = '__multicast_all__'

NO_WAIT = 0

ONE_HOUR = 3600000

ONE_MINUTE = 60000

ONE_MSEC = 1

ONE_SEC = 1000

SOCKET_NOT_CONNECTED = 7

SOCKET_RECEIVE_FAILURE = 5

SOCKET_SELECT_FAILURE = 4

SOCKET_SEND_FAILURE = 3

SOCKET_TIMEOUT = 6

UNIX = 'unix'

WAIT_FOREVER = -1


text:
package skip

import (
	"net/http"
	"testing"

	"github.com/google/martian/v3"
	"github.com/google/martian/v3/parse"
)

func TestRoundTrip(t *testing.T) {
	m := NewRoundTrip()
	req, err := http.NewRequest("GET", "http://example.com", nil)
	if err != nil {
		t.Fatalf("http.NewRequest(): got %v, want no error", err)
	}

	ctx, remove, err := martian.TestContext(req, nil, nil)
	if err != nil {
		t.Fatalf("martian.TestContext(): got %v, want no error", err)
	}
	defer remove()

	if ctx.SkippingRoundTrip() {
		t.Fatal("ctx.SkippingRoundTrip(): got true, want false")
	}

	if err := m.ModifyRequest(req); err != nil {
		t.Fatalf("ModifyRequest(): got %v, want no error", err)
	}

	if !ctx.SkippingRoundTrip() {
		t.Fatal("ctx.SkippingRoundTrip(): got false, want true")
	}
}

func TestFromJSON(t *testing.T) {
	msg := []byte(`{
			"skip.RoundTrip": {}
	}`)

	r, err := parse.FromJSON(msg)
	if err != nil {
		t.Fatalf("parse.FromJSON(): got %v, want no error", err)
	}

	reqmod := r.RequestModifier()
	if _, ok := reqmod.(*RoundTrip); !ok {
		t.Fatal("reqmod.(*RoundTrip): got !ok, want ok")
	}
}


text:
<?php

namespace Oro\Bundle\ApiBundle\Processor\Create;

use Oro\Component\ChainProcessor\ContextInterface;
use Oro\Component\ChainProcessor\ProcessorInterface;
use Oro\Bundle\ApiBundle\Model\Error;
use Oro\Bundle\ApiBundle\Request\Constraint;
use Oro\Bundle\ApiBundle\Request\EntityIdTransformerInterface;

/**
 * Checks whether a string representation of entity identifier exists in the Context,
 * and if so, converts it to its original type.
 */
class NormalizeEntityId implements ProcessorInterface
{
    /** @var EntityIdTransformerInterface */
    protected $entityIdTransformer;

    /**
     * @param EntityIdTransformerInterface $entityIdTransformer
     */
    public function __construct(EntityIdTransformerInterface $entityIdTransformer)
    {
        $this->entityIdTransformer = $entityIdTransformer;
    }

    /**
     * {@inheritdoc}
     */
    public function process(ContextInterface $context)
    {
        /** @var CreateContext $context */

        $entityId = $context->getId();
        if (!is_string($entityId)) {
            // an entity identifier does not exist or it is already normalized
            return;
        }

        if ($context->getMetadata()->hasIdentifierGenerator()) {
            // keep an entity identifier as is if the entity has a generator for identifier value
            return;
        }

        try {
            $context->setId(
                $this->entityIdTransformer->reverseTransform($context->getClassName(), $entityId)
            );
        } catch (\Exception $e) {
            $context->addError(
                Error::createValidationError(Constraint::ENTITY_ID)->setInnerException($e)
            );
        }
    }
}