context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using NPOI.OpenXmlFormats.Spreadsheet; using System; using System.Xml; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel.Extensions; using NPOI.XSSF.Model; namespace NPOI.XSSF.UserModel { /** * * High level representation of the the possible formatting information for the contents of the cells on a sheet in a * SpreadsheetML document. * * @see NPOI.xssf.usermodel.XSSFWorkbook#CreateCellStyle() * @see NPOI.xssf.usermodel.XSSFWorkbook#getCellStyleAt(short) * @see NPOI.xssf.usermodel.XSSFCell#setCellStyle(NPOI.ss.usermodel.CellStyle) */ public class XSSFCellStyle : ICellStyle { private int _cellXfId; private StylesTable _stylesSource; private CT_Xf _cellXf; private CT_Xf _cellStyleXf; private XSSFFont _font; private XSSFCellAlignment _cellAlignment; private ThemesTable _theme; /** * Creates a Cell Style from the supplied parts * @param cellXfId The main XF for the cell. Must be a valid 0-based index into the XF table * @param cellStyleXfId Optional, style xf. A value of <code>-1</code> means no xf. * @param stylesSource Styles Source to work off */ public XSSFCellStyle(int cellXfId, int cellStyleXfId, StylesTable stylesSource, ThemesTable theme) { _cellXfId = cellXfId; _stylesSource = stylesSource; _cellXf = stylesSource.GetCellXfAt(this._cellXfId); _cellStyleXf = cellStyleXfId == -1 ? null : stylesSource.GetCellStyleXfAt(cellStyleXfId); _theme = theme; } /** * Used so that StylesSource can figure out our location */ public CT_Xf GetCoreXf() { return _cellXf; } /** * Used so that StylesSource can figure out our location */ public CT_Xf GetStyleXf() { return _cellStyleXf; } /// <summary> /// Creates an empty Cell Style /// </summary> /// <param name="stylesSource"></param> public XSSFCellStyle(StylesTable stylesSource) { _stylesSource = stylesSource; // We need a new CT_Xf for the main styles // TODO decide on a style ctxf _cellXf = new CT_Xf(); _cellStyleXf = null; } /** * Verifies that this style belongs to the supplied Workbook * Styles Source. * Will throw an exception if it belongs to a different one. * This is normally called when trying to assign a style to a * cell, to ensure the cell and the style are from the same * workbook (if they're not, it won't work) * @throws ArgumentException if there's a workbook mis-match */ public void VerifyBelongsToStylesSource(StylesTable src) { if (this._stylesSource != src) { throw new ArgumentException("This Style does not belong to the supplied Workbook Stlyes Source. Are you trying to assign a style from one workbook to the cell of a differnt workbook?"); } } /** * Clones all the style information from another * XSSFCellStyle, onto this one. This * XSSFCellStyle will then have all the same * properties as the source, but the two may * be edited independently. * Any stylings on this XSSFCellStyle will be lost! * * The source XSSFCellStyle could be from another * XSSFWorkbook if you like. This allows you to * copy styles from one XSSFWorkbook to another. */ public void CloneStyleFrom(ICellStyle source) { if (source is XSSFCellStyle) { XSSFCellStyle src = (XSSFCellStyle)source; // Is it on our Workbook? if (src._stylesSource == _stylesSource) { // Nice and easy _cellXf = src.GetCoreXf().Copy(); _cellStyleXf = src.GetStyleXf().Copy(); } else { // Copy the style try { // Remove any children off the current style, to // avoid orphaned nodes if (_cellXf.IsSetAlignment()) _cellXf.UnsetAlignment(); if (_cellXf.IsSetExtLst()) _cellXf.UnsetExtLst(); // Create a new Xf with the same contents _cellXf = src.GetCoreXf().Copy(); // bug 56295: ensure that the fills is available and set correctly CT_Fill fill = CT_Fill.Parse(src.GetCTFill().ToString()); AddFill(fill); // Swap it over _stylesSource.ReplaceCellXfAt(_cellXfId, _cellXf); } catch (XmlException e) { throw new POIXMLException(e); } // Copy the format String fmt = src.GetDataFormatString(); DataFormat = ( (new XSSFDataFormat(_stylesSource)).GetFormat(fmt) ); // Copy the font try { CT_Font ctFont = src.GetFont().GetCTFont().Clone(); XSSFFont font = new XSSFFont(ctFont); font.RegisterTo(_stylesSource); SetFont(font); } catch (XmlException e) { throw new POIXMLException(e); } } // Clear out cached details _font = null; _cellAlignment = null; } else { throw new ArgumentException("Can only clone from one XSSFCellStyle to another, not between HSSFCellStyle and XSSFCellStyle"); } } private void AddFill(CT_Fill fill) { int idx = _stylesSource.PutFill(new XSSFCellFill(fill)); _cellXf.fillId = (uint)(idx); _cellXf.applyFill = (true); } public HorizontalAlignment Alignment { get { return GetAlignmentEnum(); } set { GetCellAlignment().Horizontal = value; } } /// <summary> /// Get the type of horizontal alignment for the cell /// </summary> /// <returns>the type of alignment</returns> internal HorizontalAlignment GetAlignmentEnum() { CT_CellAlignment align = _cellXf.alignment; if (align != null && align.IsSetHorizontal()) { return (HorizontalAlignment)align.horizontal; } return HorizontalAlignment.General; } public BorderStyle BorderBottom { get { if (!_cellXf.applyBorder) return BorderStyle.None; int idx = (int)_cellXf.borderId; CT_Border ct = _stylesSource.GetBorderAt(idx).GetCTBorder(); if (!ct.IsSetBottom()) { return BorderStyle.None; } else { return (BorderStyle)ct.bottom.style; } } set { CT_Border ct = GetCTBorder(); CT_BorderPr pr = ct.IsSetBottom() ? ct.bottom : ct.AddNewBottom(); if (value == BorderStyle.None) ct.unsetBottom(); else pr.style = (ST_BorderStyle)value; int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme)); _cellXf.borderId = (uint)idx; _cellXf.applyBorder = (true); } } public BorderStyle BorderLeft { get { if (!_cellXf.applyBorder) return BorderStyle.None; int idx = (int)_cellXf.borderId; CT_Border ct = _stylesSource.GetBorderAt(idx).GetCTBorder(); if (!ct.IsSetLeft()) { return BorderStyle.None; } else { return (BorderStyle)ct.left.style; } } set { CT_Border ct = GetCTBorder(); CT_BorderPr pr = ct.IsSetLeft() ? ct.left : ct.AddNewLeft(); if (value == BorderStyle.None) ct.unsetLeft(); else pr.style = (ST_BorderStyle)value; int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme)); _cellXf.borderId = (uint)idx; _cellXf.applyBorder = (true); } } /// <summary> /// Get the type of border to use for the right border of the cell /// </summary> public BorderStyle BorderRight { get { if (!_cellXf.applyBorder) return BorderStyle.None; int idx = (int)_cellXf.borderId; CT_Border ct = _stylesSource.GetBorderAt(idx).GetCTBorder(); if (!ct.IsSetRight()) { return BorderStyle.None; } else { return (BorderStyle)ct.right.style; } } set { CT_Border ct = GetCTBorder(); CT_BorderPr pr = ct.IsSetRight() ? ct.right : ct.AddNewRight(); if (value == BorderStyle.None) ct.unsetRight(); else pr.style = (ST_BorderStyle)value; int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme)); _cellXf.borderId = (uint)idx; _cellXf.applyBorder = (true); } } public BorderStyle BorderTop { get { if (!_cellXf.applyBorder) return BorderStyle.None; int idx = (int)_cellXf.borderId; CT_Border ct = _stylesSource.GetBorderAt(idx).GetCTBorder(); if (!ct.IsSetTop()) { return BorderStyle.None; } else { return (BorderStyle)ct.top.style; } } set { CT_Border ct = GetCTBorder(); CT_BorderPr pr = ct.IsSetTop() ? ct.top : ct.AddNewTop(); if (value == BorderStyle.None) ct.unsetTop(); else pr.style = (ST_BorderStyle)value; int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme)); _cellXf.borderId = (uint)idx; _cellXf.applyBorder = (true); } } /** * Get the color to use for the bottom border * Color is optional. When missing, IndexedColors.Automatic is implied. * @return the index of the color defInition, default value is {@link NPOI.ss.usermodel.IndexedColors#AUTOMATIC} * @see NPOI.ss.usermodel.IndexedColors */ public short BottomBorderColor { get { XSSFColor clr = BottomBorderXSSFColor; return clr == null ? IndexedColors.Black.Index : clr.Indexed; } set { XSSFColor clr = new XSSFColor(); clr.Indexed = value; SetBottomBorderColor(clr); } } /** * Get the color to use for the bottom border as a {@link XSSFColor} * * @return the used color or <code>null</code> if not Set */ public XSSFColor BottomBorderXSSFColor { get { if (!_cellXf.applyBorder) return null; int idx = (int)_cellXf.borderId; XSSFCellBorder border = _stylesSource.GetBorderAt(idx); return border.GetBorderColor(BorderSide.BOTTOM); } } /** * Get the index of the number format (numFmt) record used by this cell format. * * @return the index of the number format */ public short DataFormat { get { return (short)_cellXf.numFmtId; } set { // XSSF supports >32,767 formats SetDataFormat(value & 0xFFFF); } } /** * Set the index of a data format * * @param fmt the index of a data format */ public void SetDataFormat(int fmt) { _cellXf.applyNumberFormat = (true); _cellXf.numFmtId = (uint)(fmt); } /** * Get the contents of the format string, by looking up * the StylesSource * * @return the number format string */ public String GetDataFormatString() { int idx = DataFormat; return new XSSFDataFormat(_stylesSource).GetFormat((short)idx); } /// <summary> /// Get the background fill color. /// Note - many cells are actually filled with a foreground fill, not a background fill /// </summary> public short FillBackgroundColor { get { XSSFColor clr = (XSSFColor)this.FillBackgroundColorColor; return clr == null ? IndexedColors.Automatic.Index : clr.Indexed; } set { XSSFColor clr = new XSSFColor(); clr.Indexed = (value); SetFillBackgroundColor(clr); } } /** * Get the background fill color. * <p> * Note - many cells are actually Filled with a foreground * Fill, not a background fill - see {@link #getFillForegroundColor()} * </p> * @see NPOI.xssf.usermodel.XSSFColor#getRgb() * @return XSSFColor - fill color or <code>null</code> if not Set */ public IColor FillBackgroundColorColor { get { return this.FillBackgroundXSSFColor; } set { this.FillBackgroundXSSFColor = (XSSFColor)value; } } public XSSFColor FillBackgroundXSSFColor { get { // bug 56295: handle missing applyFill attribute as "true" because Excel does as well if (_cellXf.IsSetApplyFill() && !_cellXf.applyFill) return null; int fillIndex = (int)_cellXf.fillId; XSSFCellFill fg = _stylesSource.GetFillAt(fillIndex); XSSFColor fillBackgroundColor = fg.GetFillBackgroundColor(); if (fillBackgroundColor != null && _theme != null) { _theme.InheritFromThemeAsRequired(fillBackgroundColor); } return fillBackgroundColor; } set { CT_Fill ct = GetCTFill(); CT_PatternFill ptrn = ct.patternFill; if (value == null) { if (ptrn != null) ptrn.UnsetBgColor(); } else { if (ptrn == null) ptrn = ct.AddNewPatternFill(); ptrn.bgColor = (value.GetCTColor()); } AddFill(ct); } } /** * Get the foreground fill color. * <p> * Many cells are Filled with this, instead of a * background color ({@link #getFillBackgroundColor()}) * </p> * @see IndexedColors * @return fill color, default value is {@link NPOI.ss.usermodel.IndexedColors#AUTOMATIC} */ public short FillForegroundColor { get { XSSFColor clr = (XSSFColor)this.FillForegroundColorColor; return clr == null ? IndexedColors.Automatic.Index : clr.Indexed; } set { XSSFColor clr = new XSSFColor(); clr.Indexed = (value); SetFillForegroundColor(clr); } } /// <summary> /// Get the foreground fill color. /// </summary> public IColor FillForegroundColorColor { get { return this.FillForegroundXSSFColor; } set { this.FillForegroundXSSFColor = (XSSFColor)value; } } /// <summary> /// Get the foreground fill color. /// </summary> public XSSFColor FillForegroundXSSFColor { get { // bug 56295: handle missing applyFill attribute as "true" because Excel does as well if (_cellXf.IsSetApplyFill() && !_cellXf.applyFill) return null; int fillIndex = (int)_cellXf.fillId; XSSFCellFill fg = _stylesSource.GetFillAt(fillIndex); XSSFColor fillForegroundColor = fg.GetFillForegroundColor(); if (fillForegroundColor != null && _theme != null) { _theme.InheritFromThemeAsRequired(fillForegroundColor); } return fillForegroundColor; } set { CT_Fill ct = GetCTFill(); CT_PatternFill ptrn = ct.patternFill; if (value == null) { if (ptrn != null) ptrn.UnsetFgColor(); } else { if (ptrn == null) ptrn = ct.AddNewPatternFill(); ptrn.fgColor = (value.GetCTColor()); } AddFill(ct); } } public FillPattern FillPattern { get { // bug 56295: handle missing applyFill attribute as "true" because Excel does as well if (_cellXf.IsSetApplyFill() && !_cellXf.applyFill) return 0; int FillIndex = (int)_cellXf.fillId; XSSFCellFill fill = _stylesSource.GetFillAt(FillIndex); ST_PatternType ptrn = fill.GetPatternType(); if(ptrn == ST_PatternType.none) return FillPattern.NoFill; return (FillPattern)((int)ptrn); } set { CT_Fill ct = GetCTFill(); CT_PatternFill ptrn = ct.IsSetPatternFill() ? ct.GetPatternFill() : ct.AddNewPatternFill(); if (value == FillPattern.NoFill && ptrn.IsSetPatternType()) ptrn.UnsetPatternType(); else ptrn.patternType = (ST_PatternType)(value); AddFill(ct); } } /** * Gets the font for this style * @return Font - font */ public XSSFFont GetFont() { if (_font == null) { _font = _stylesSource.GetFontAt(FontId); } return _font; } /** * Gets the index of the font for this style * * @return short - font index * @see NPOI.xssf.usermodel.XSSFWorkbook#getFontAt(short) */ public short FontIndex { get { return (short)FontId; } } /** * Get whether the cell's using this style are to be hidden * * @return bool - whether the cell using this style is hidden */ public bool IsHidden { get { if (!_cellXf.IsSetProtection() || !_cellXf.protection.IsSetHidden()) { return false; } return _cellXf.protection.hidden; } set { if (!_cellXf.IsSetProtection()) { _cellXf.AddNewProtection(); } _cellXf.protection.hidden = (value); } } /** * Get the number of spaces to indent the text in the cell * * @return indent - number of spaces */ public short Indention { get { CT_CellAlignment align = _cellXf.alignment; return (short)(align == null ? 0 : align.indent); } set { GetCellAlignment().Indent = value; } } /** * Get the index within the StylesTable (sequence within the collection of CT_Xf elements) * * @return unique index number of the underlying record this style represents */ public short Index { get { return (short)this._cellXfId; } } protected internal int UIndex { get { return this._cellXfId; } } /** * Get the color to use for the left border * * @return the index of the color defInition, default value is {@link NPOI.ss.usermodel.IndexedColors#BLACK} * @see NPOI.ss.usermodel.IndexedColors */ public short LeftBorderColor { get { XSSFColor clr = LeftBorderXSSFColor; return clr == null ? IndexedColors.Black.Index : clr.Indexed; } set { XSSFColor clr = new XSSFColor(); clr.Indexed = (value); SetLeftBorderColor(clr); } } public XSSFColor DiagonalBorderXSSFColor { get { if (!_cellXf.applyBorder) return null; int idx = (int)_cellXf.borderId; XSSFCellBorder border = _stylesSource.GetBorderAt(idx); return border.GetBorderColor(BorderSide.DIAGONAL); } } /** * Get the color to use for the left border * * @return the index of the color defInition or <code>null</code> if not Set * @see NPOI.ss.usermodel.IndexedColors */ public XSSFColor LeftBorderXSSFColor { get { if (!_cellXf.applyBorder) return null; int idx = (int)_cellXf.borderId; XSSFCellBorder border = _stylesSource.GetBorderAt(idx); return border.GetBorderColor(BorderSide.LEFT); } } /// <summary> /// Get whether the cell's using this style are locked /// </summary> public bool IsLocked { get { if (!_cellXf.IsSetProtection()) { return true; } return _cellXf.protection.locked; } set { if (!_cellXf.IsSetProtection()) { _cellXf.AddNewProtection(); } _cellXf.protection.locked = value; } } /// <summary> /// Get the color to use for the right border /// </summary> public short RightBorderColor { get { XSSFColor clr = RightBorderXSSFColor; return clr == null ? IndexedColors.Black.Index : clr.Indexed; } set { XSSFColor clr = new XSSFColor(); clr.Indexed = (value); SetRightBorderColor(clr); } } /// <summary> /// Get the color to use for the right border /// </summary> /// <returns></returns> public XSSFColor RightBorderXSSFColor { get { if (!_cellXf.applyBorder) return null; int idx = (int)_cellXf.borderId; XSSFCellBorder border = _stylesSource.GetBorderAt(idx); return border.GetBorderColor(BorderSide.RIGHT); } } /// <summary> /// Get the degree of rotation (between 0 and 180 degrees) for the text in the cell /// </summary> /// <example> /// Expressed in degrees. Values range from 0 to 180. The first letter of /// the text is considered the center-point of the arc. /// For 0 - 90, the value represents degrees above horizon. For 91-180 the degrees below the horizon is calculated as: /// <code>[degrees below horizon] = 90 - textRotation.</code> /// </example> public short Rotation { get { CT_CellAlignment align = _cellXf.alignment; return (short)(align == null ? 0 : align.textRotation); } set { GetCellAlignment().TextRotation = value; } } /** * Get the color to use for the top border * * @return the index of the color defInition, default value is {@link NPOI.ss.usermodel.IndexedColors#BLACK} * @see NPOI.ss.usermodel.IndexedColors */ public short TopBorderColor { get { XSSFColor clr = TopBorderXSSFColor; return clr == null ? IndexedColors.Black.Index : clr.Indexed; } set { XSSFColor clr = new XSSFColor(); clr.Indexed = (value); SetTopBorderColor(clr); } } /// <summary> /// Get the color to use for the top border /// </summary> /// <returns></returns> public XSSFColor TopBorderXSSFColor { get { if (!_cellXf.applyBorder) return null; int idx = (int)_cellXf.borderId; XSSFCellBorder border = _stylesSource.GetBorderAt(idx); return border.GetBorderColor(BorderSide.TOP); } } /// <summary> /// Get the type of vertical alignment for the cell /// </summary> public VerticalAlignment VerticalAlignment { get { return GetVerticalAlignmentEnum(); } set { GetCellAlignment().Vertical = value; } } /// <summary> /// Get the type of vertical alignment for the cell /// </summary> /// <returns></returns> internal VerticalAlignment GetVerticalAlignmentEnum() { CT_CellAlignment align = _cellXf.alignment; if (align != null && align.IsSetVertical()) { return (VerticalAlignment)align.vertical; } return VerticalAlignment.Bottom; } /// <summary> /// Whether the text in a cell should be line-wrapped within the cell. /// </summary> public bool WrapText { get { CT_CellAlignment align = _cellXf.alignment; return align != null && align.wrapText; } set { GetCellAlignment().WrapText = value; } } /** * Set the color to use for the bottom border * * @param color the color to use, null means no color */ public void SetBottomBorderColor(XSSFColor color) { CT_Border ct = GetCTBorder(); if (color == null && !ct.IsSetBottom()) return; CT_BorderPr pr = ct.IsSetBottom() ? ct.bottom : ct.AddNewBottom(); if (color != null) pr.SetColor(color.GetCTColor()); else pr.UnsetColor(); int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme)); _cellXf.borderId = (uint)idx; _cellXf.applyBorder = (true); } /** * Set the background fill color represented as a {@link XSSFColor} value. * <p> * For example: * <pre> * cs.SetFillPattern(XSSFCellStyle.FINE_DOTS ); * cs.SetFillBackgroundXSSFColor(new XSSFColor(java.awt.Color.RED)); * </pre> * optionally a Foreground and background fill can be applied: * <i>Note: Ensure Foreground color is set prior to background</i> * <pre> * cs.SetFillPattern(XSSFCellStyle.FINE_DOTS ); * cs.SetFillForegroundColor(new XSSFColor(java.awt.Color.BLUE)); * cs.SetFillBackgroundColor(new XSSFColor(java.awt.Color.GREEN)); * </pre> * or, for the special case of SOLID_FILL: * <pre> * cs.SetFillPattern(XSSFCellStyle.SOLID_FOREGROUND ); * cs.SetFillForegroundColor(new XSSFColor(java.awt.Color.GREEN)); * </pre> * It is necessary to set the fill style in order * for the color to be shown in the cell. * * @param color - the color to use */ public void SetFillBackgroundColor(XSSFColor color) { CT_Fill ct = GetCTFill(); CT_PatternFill ptrn = ct.GetPatternFill(); if (color == null) { if (ptrn != null) ptrn.UnsetBgColor(); } else { if (ptrn == null) ptrn = ct.AddNewPatternFill(); ptrn.bgColor = color.GetCTColor(); } int idx = _stylesSource.PutFill(new XSSFCellFill(ct)); _cellXf.fillId = (uint)idx; _cellXf.applyFill = (true); } /** * Set the foreground fill color represented as a {@link XSSFColor} value. * <br/> * <i>Note: Ensure Foreground color is Set prior to background color.</i> * @param color the color to use * @see #setFillBackgroundColor(NPOI.xssf.usermodel.XSSFColor) ) */ public void SetFillForegroundColor(XSSFColor color) { CT_Fill ct = GetCTFill(); CT_PatternFill ptrn = ct.GetPatternFill(); if (color == null) { if (ptrn != null) ptrn.UnsetFgColor(); } else { if (ptrn == null) ptrn = ct.AddNewPatternFill(); ptrn.fgColor = (color.GetCTColor()); } int idx = _stylesSource.PutFill(new XSSFCellFill(ct)); _cellXf.fillId = (uint)idx; _cellXf.applyFill = (true); } /** * Get a <b>copy</b> of the currently used CT_Fill, if none is used, return a new instance. */ public CT_Fill GetCTFill() { CT_Fill ct; // bug 56295: handle missing applyFill attribute as "true" because Excel does as well if (!_cellXf.IsSetApplyFill() || _cellXf.applyFill) { int FillIndex = (int)_cellXf.fillId; XSSFCellFill cf = _stylesSource.GetFillAt(FillIndex); ct = (CT_Fill)cf.GetCTFill().Copy(); } else { ct = new CT_Fill(); } return ct; } /** * Get a <b>copy</b> of the currently used CT_Border, if none is used, return a new instance. */ public CT_Border GetCTBorder() { CT_Border ctBorder; if (_cellXf.applyBorder) { int idx = (int)_cellXf.borderId; XSSFCellBorder cf = _stylesSource.GetBorderAt(idx); ctBorder = (CT_Border)cf.GetCTBorder(); } else { ctBorder = new CT_Border(); ctBorder.AddNewLeft(); ctBorder.AddNewRight(); ctBorder.AddNewTop(); ctBorder.AddNewBottom(); ctBorder.AddNewDiagonal(); } return ctBorder; } /** * Set the font for this style * * @param font a font object Created or retreived from the XSSFWorkbook object * @see NPOI.xssf.usermodel.XSSFWorkbook#CreateFont() * @see NPOI.xssf.usermodel.XSSFWorkbook#getFontAt(short) */ public void SetFont(IFont font) { if (font != null) { long index = font.Index; this._cellXf.fontId = (uint)index; this._cellXf.fontIdSpecified = true; this._cellXf.applyFont = (true); } else { this._cellXf.applyFont = (false); } } public void SetDiagonalBorderColor(XSSFColor color) { CT_Border ct = GetCTBorder(); if (color == null && !ct.IsSetDiagonal()) return; CT_BorderPr pr = ct.IsSetDiagonal() ? ct.diagonal : ct.AddNewDiagonal(); if (color != null) pr.color = (color.GetCTColor()); else pr.UnsetColor(); int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme)); _cellXf.borderId = (uint)idx; _cellXf.applyBorder = (true); } /** * Set the color to use for the left border as a {@link XSSFColor} value * * @param color the color to use */ public void SetLeftBorderColor(XSSFColor color) { CT_Border ct = GetCTBorder(); if (color == null && !ct.IsSetLeft()) return; CT_BorderPr pr = ct.IsSetLeft() ? ct.left : ct.AddNewLeft(); if (color != null) pr.color = (color.GetCTColor()); else pr.UnsetColor(); int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme)); _cellXf.borderId = (uint)idx; _cellXf.applyBorder = (true); } /** * Set the color to use for the right border as a {@link XSSFColor} value * * @param color the color to use */ public void SetRightBorderColor(XSSFColor color) { CT_Border ct = GetCTBorder(); if (color == null && !ct.IsSetRight()) return; CT_BorderPr pr = ct.IsSetRight() ? ct.right : ct.AddNewRight(); if (color != null) pr.color = (color.GetCTColor()); else pr.UnsetColor(); int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme)); _cellXf.borderId = (uint)(idx); _cellXf.applyBorder = (true); } /** * Set the color to use for the top border as a {@link XSSFColor} value * * @param color the color to use */ public void SetTopBorderColor(XSSFColor color) { CT_Border ct = GetCTBorder(); if (color == null && !ct.IsSetTop()) return; CT_BorderPr pr = ct.IsSetTop() ? ct.top : ct.AddNewTop(); if (color != null) pr.color = color.GetCTColor(); else pr.UnsetColor(); int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme)); _cellXf.borderId = (uint)idx; _cellXf.applyBorder = (true); } /** * Set the type of vertical alignment for the cell * * @param align - align the type of alignment * @see NPOI.ss.usermodel.CellStyle#VERTICAL_TOP * @see NPOI.ss.usermodel.CellStyle#VERTICAL_CENTER * @see NPOI.ss.usermodel.CellStyle#VERTICAL_BOTTOM * @see NPOI.ss.usermodel.CellStyle#VERTICAL_JUSTIFY * @see NPOI.ss.usermodel.VerticalAlignment */ public void SetVerticalAlignment(short align) { GetCellAlignment().Vertical = (VerticalAlignment)align; } /** * Gets border color * * @param side the border side * @return the used color */ public XSSFColor GetBorderColor(BorderSide side) { switch (side) { case BorderSide.BOTTOM: return BottomBorderXSSFColor; case BorderSide.RIGHT: return RightBorderXSSFColor; case BorderSide.TOP: return TopBorderXSSFColor; case BorderSide.LEFT: return LeftBorderXSSFColor; default: throw new ArgumentException("Unknown border: " + side); } } /** * Set the color to use for the selected border * * @param side - where to apply the color defInition * @param color - the color to use */ public void SetBorderColor(BorderSide side, XSSFColor color) { switch (side) { case BorderSide.BOTTOM: SetBottomBorderColor(color); break; case BorderSide.RIGHT: SetRightBorderColor(color); break; case BorderSide.TOP: SetTopBorderColor(color); break; case BorderSide.LEFT: SetLeftBorderColor(color); break; } } private int FontId { get { if (_cellXf.IsSetFontId()) { return (int)_cellXf.fontId; } return (int)_cellStyleXf.fontId; } } /** * Get the cellAlignment object to use for manage alignment * @return XSSFCellAlignment - cell alignment */ internal XSSFCellAlignment GetCellAlignment() { if (this._cellAlignment == null) { this._cellAlignment = new XSSFCellAlignment(GetCTCellAlignment()); } return this._cellAlignment; } /** * Return the CT_CellAlignment instance for alignment * * @return CT_CellAlignment */ internal CT_CellAlignment GetCTCellAlignment() { if (_cellXf.alignment == null) { _cellXf.alignment = new CT_CellAlignment(); } return _cellXf.alignment; } /** * Returns a hash code value for the object. The hash is derived from the underlying CT_Xf bean. * * @return the hash code value for this style */ public override int GetHashCode() { return _cellXf.ToString().GetHashCode(); } /** * Checks is the supplied style is equal to this style * * @param o the style to check * @return true if the supplied style is equal to this style */ public override bool Equals(Object o) { if (o == null || !(o is XSSFCellStyle)) return false; XSSFCellStyle cf = (XSSFCellStyle)o; return _cellXf.ToString().Equals(cf.GetCoreXf().ToString()); } /** * Make a copy of this style. The underlying CT_Xf bean is Cloned, * the references to Fills and borders remain. * * @return a copy of this style */ public Object Clone() { CT_Xf xf = (CT_Xf)_cellXf.Copy(); int xfSize = _stylesSource.StyleXfsSize; int indexXf = _stylesSource.PutCellXf(xf); return new XSSFCellStyle(indexXf - 1, xfSize - 1, _stylesSource, _theme); } #region ICellStyle Members public IFont GetFont(IWorkbook parentWorkbook) { return this.GetFont(); } public bool ShrinkToFit { get { CT_CellAlignment align = _cellXf.alignment; return align != null && align.shrinkToFit; } set { GetCTCellAlignment().shrinkToFit = value; } } public short BorderDiagonalColor { get { XSSFColor clr = DiagonalBorderXSSFColor; return clr == null ? IndexedColors.Black.Index : clr.Indexed; } set { XSSFColor clr = new XSSFColor(); clr.Indexed = (value); SetDiagonalBorderColor(clr); } } public BorderStyle BorderDiagonalLineStyle { get { if (!_cellXf.applyBorder) return BorderStyle.None; int idx = (int)_cellXf.borderId; CT_Border ct = _stylesSource.GetBorderAt(idx).GetCTBorder(); if (!ct.IsSetDiagonal()) { return BorderStyle.None; } else { return (BorderStyle)ct.diagonal.style; } } set { CT_Border ct = GetCTBorder(); CT_BorderPr pr = ct.IsSetDiagonal() ? ct.diagonal : ct.AddNewDiagonal(); if (value == BorderStyle.None) ct.unsetDiagonal(); else pr.style = (ST_BorderStyle)value; int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme)); _cellXf.borderId = (uint)idx; _cellXf.applyBorder = (true); } } public BorderDiagonal BorderDiagonal { get { CT_Border ct = GetCTBorder(); if (ct.diagonalDown == true && ct.diagonalUp == true) return BorderDiagonal.Both; else if (ct.diagonalDown == true) return BorderDiagonal.Backward; else if (ct.diagonalUp == true) return BorderDiagonal.Forward; else return BorderDiagonal.None; } set { CT_Border ct = GetCTBorder(); if (value == BorderDiagonal.Both) { ct.diagonalDown = true; ct.diagonalDownSpecified = true; ct.diagonalUp = true; ct.diagonalUpSpecified = true; } else if (value == BorderDiagonal.Forward) { ct.diagonalDown = false; ct.diagonalDownSpecified = false; ct.diagonalUp = true; ct.diagonalUpSpecified = true; } else if (value == BorderDiagonal.Backward) { ct.diagonalDown = true; ct.diagonalDownSpecified = true; ct.diagonalUp = false; ct.diagonalUpSpecified = false; } else { ct.unsetDiagonal(); ct.diagonalDown = false; ct.diagonalDownSpecified = false; ct.diagonalUp = false; ct.diagonalUpSpecified = false; } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Text { // ASCIIEncoding // // Note that ASCIIEncoding is optimized with no best fit and ? for fallback. // It doesn't come in other flavors. // // Note: ASCIIEncoding is the only encoding that doesn't do best fit (windows has best fit). // // Note: IsAlwaysNormalized remains false because 1/2 the code points are unassigned, so they'd // use fallbacks, and we cannot guarantee that fallbacks are normalized. public class ASCIIEncoding : Encoding { // Allow for devirtualization (see https://github.com/dotnet/coreclr/pull/9230) internal sealed class ASCIIEncodingSealed : ASCIIEncoding { } // Used by Encoding.ASCII for lazy initialization // The initialization code will not be run until a static member of the class is referenced internal static readonly ASCIIEncodingSealed s_default = new ASCIIEncodingSealed(); public ASCIIEncoding() : base(Encoding.CodePageASCII) { } internal sealed override void SetDefaultFallbacks() { // For ASCIIEncoding we just use default replacement fallback this.encoderFallback = EncoderFallback.ReplacementFallback; this.decoderFallback = DecoderFallback.ReplacementFallback; } // WARNING: GetByteCount(string chars), GetBytes(string chars,...), and GetString(byte[] byteIndex...) // WARNING: have different variable names than EncodingNLS.cs, so this can't just be cut & pasted, // WARNING: or it'll break VB's way of calling these. // // The following methods are copied from EncodingNLS.cs. // Unfortunately EncodingNLS.cs is internal and we're public, so we have to re-implement them here. // These should be kept in sync for the following classes: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters if (chars == null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); // If no input, return 0, avoid fixed empty array problem if (count == 0) return 0; // Just call the pointer version fixed (char* pChars = chars) return GetByteCount(pChars + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(string chars) { // Validate input if (chars==null) throw new ArgumentNullException(nameof(chars)); fixed (char* pChars = chars) return GetByteCount(pChars, chars.Length, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters if (chars == null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); // Call it with empty encoder return GetByteCount(chars, count, null); } public override unsafe int GetByteCount(ReadOnlySpan<char> chars) { fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) { return GetByteCount(charsPtr, chars.Length, encoder: null); } } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetBytes(string chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); int byteCount = bytes.Length - byteIndex; fixed (char* pChars = chars) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); // If nothing to encode return 0 if (charCount == 0) return 0; // Just call pointer version int byteCount = bytes.Length - byteIndex; fixed (char* pChars = chars) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) // Remember that byteCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); return GetBytes(chars, charCount, bytes, byteCount, null); } public override unsafe int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes) { fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { return GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length, encoder: null); } } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // If no input just return 0, fixed doesn't like 0 length arrays if (count == 0) return 0; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); return GetCharCount(bytes, count, null); } public override unsafe int GetCharCount(ReadOnlySpan<byte> bytes) { fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { return GetCharCount(bytesPtr, bytes.Length, decoder: null); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if ( bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index); // If no input, return 0 & avoid fixed problem if (byteCount == 0) return 0; // Just call pointer version int charCount = chars.Length - charIndex; fixed (byte* pBytes = bytes) fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); return GetChars(bytes, byteCount, chars, charCount, null); } public override unsafe int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars) { fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) { return GetChars(bytesPtr, bytes.Length, charsPtr, chars.Length, decoder: null); } } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe string GetString(byte[] bytes, int byteIndex, int byteCount) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // Avoid problems with empty input buffer if (byteCount == 0) return string.Empty; fixed (byte* pBytes = bytes) return string.CreateStringFromEncoding( pBytes + byteIndex, byteCount, this); } // // End of standard methods copied from EncodingNLS.cs // // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption internal sealed override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative"); Debug.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder"); char charLeftOver = (char)0; EncoderReplacementFallback fallback = null; // Start by assuming default count, then +/- for fallback characters char* charEnd = chars + charCount; // For fallback we may need a fallback buffer, we know we aren't default fallback. EncoderFallbackBuffer fallbackBuffer = null; char* charsForFallback; if (encoder != null) { charLeftOver = encoder._charLeftOver; Debug.Assert(charLeftOver == 0 || char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; // We mustn't have left over fallback data when counting if (encoder.InternalHasFallbackBuffer) { // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary fallbackBuffer = encoder.FallbackBuffer; if (fallbackBuffer.Remaining > 0 && encoder._throwOnOverflow) throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType())); // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false); } // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert Debug.Assert(!encoder._throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetByteCount]Expected empty fallback buffer"); } else { fallback = this.EncoderFallback as EncoderReplacementFallback; } // If we have an encoder AND we aren't using default fallback, // then we may have a complicated count. if (fallback != null && fallback.MaxCharCount == 1) { // Replacement fallback encodes surrogate pairs as two ?? (or two whatever), so return size is always // same as input size. // Note that no existing SBCS code pages map code points to supplimentary characters, so this is easy. // We could however have 1 extra byte if the last call had an encoder and a funky fallback and // if we don't use the funky fallback this time. // Do we have an extra char left over from last time? if (charLeftOver > 0) charCount++; return (charCount); } // Count is more complicated if you have a funky fallback // For fallback we may need a fallback buffer, we know we're not default fallback int byteCount = 0; // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { Debug.Assert(char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); Debug.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder"); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false); // This will fallback a pair if *chars is a low surrogate charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered fallbackBuffer.InternalFallback(charLeftOver, ref charsForFallback); chars = charsForFallback; } // Now we may have fallback char[] already from the encoder // Go ahead and do it, including the fallback. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Check for fallback, this'll catch surrogate pairs too. // no chars >= 0x80 are allowed. if (ch > 0x7f) { if (fallbackBuffer == null) { // Initialize the buffer if (encoder == null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, false); } // Get Fallback charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered fallbackBuffer.InternalFallback(ch, ref charsForFallback); chars = charsForFallback; continue; } // We'll use this one byteCount++; } Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetByteCount]Expected Empty fallback buffer"); return byteCount; } internal sealed override unsafe int GetBytes( char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null"); Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative"); Debug.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null"); Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback"); // Get any left over characters char charLeftOver = (char)0; EncoderReplacementFallback fallback = null; // For fallback we may need a fallback buffer, we know we aren't default fallback. EncoderFallbackBuffer fallbackBuffer = null; char* charsForFallback; // prepare our end char* charEnd = chars + charCount; byte* byteStart = bytes; char* charStart = chars; if (encoder != null) { charLeftOver = encoder._charLeftOver; fallback = encoder.Fallback as EncoderReplacementFallback; // We mustn't have left over fallback data when counting if (encoder.InternalHasFallbackBuffer) { // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary fallbackBuffer = encoder.FallbackBuffer; if (fallbackBuffer.Remaining > 0 && encoder._throwOnOverflow) throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType())); // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true); } Debug.Assert(charLeftOver == 0 || char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetBytes]leftover character should be high surrogate"); // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert Debug.Assert(!encoder._throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetBytes]Expected empty fallback buffer"); } else { fallback = this.EncoderFallback as EncoderReplacementFallback; } // See if we do the fast default or slightly slower fallback if (fallback != null && fallback.MaxCharCount == 1) { // Fast version char cReplacement = fallback.DefaultString[0]; // Check for replacements in range, otherwise fall back to slow version. if (cReplacement <= (char)0x7f) { // We should have exactly as many output bytes as input bytes, unless there's a left // over character, in which case we may need one more. // If we had a left over character will have to add a ? (This happens if they had a funky // fallback last time, but not this time.) (We can't spit any out though // because with fallback encoder each surrogate is treated as a seperate code point) if (charLeftOver > 0) { // Have to have room // Throw even if doing no throw version because this is just 1 char, // so buffer will never be big enough if (byteCount == 0) ThrowBytesOverflow(encoder, true); // This'll make sure we still have more room and also make sure our return value is correct. *(bytes++) = (byte)cReplacement; byteCount--; // We used one of the ones we were counting. } // This keeps us from overrunning our output buffer if (byteCount < charCount) { // Throw or make buffer smaller? ThrowBytesOverflow(encoder, byteCount < 1); // Just use what we can charEnd = chars + byteCount; } // We just do a quick copy while (chars < charEnd) { char ch2 = *(chars++); if (ch2 >= 0x0080) *(bytes++) = (byte)cReplacement; else *(bytes++) = unchecked((byte)(ch2)); } // Clear encoder if (encoder != null) { encoder._charLeftOver = (char)0; encoder._charsUsed = (int)(chars - charStart); } return (int)(bytes - byteStart); } } // Slower version, have to do real fallback. // prepare our end byte* byteEnd = bytes + byteCount; // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { // Initialize the buffer Debug.Assert(encoder != null, "[ASCIIEncoding.GetBytes]Expected non null encoder if we have surrogate left over"); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback // This will fallback a pair if *chars is a low surrogate charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered fallbackBuffer.InternalFallback(charLeftOver, ref charsForFallback); chars = charsForFallback; } // Now we may have fallback char[] already from the encoder // Go ahead and do it, including the fallback. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Check for fallback, this'll catch surrogate pairs too. // All characters >= 0x80 must fall back. if (ch > 0x7f) { // Initialize the buffer if (fallbackBuffer == null) { if (encoder == null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, true); } // Get Fallback charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered fallbackBuffer.InternalFallback(ch, ref charsForFallback); chars = charsForFallback; // Go ahead & continue (& do the fallback) continue; } // We'll use this one // Bounds check if (bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { Debug.Assert(chars > charStart || bytes == byteStart, "[ASCIIEncoding.GetBytes]Expected chars to have advanced already."); chars--; // don't use last char } else fallbackBuffer.MovePrevious(); // Are we throwing or using buffer? ThrowBytesOverflow(encoder, bytes == byteStart); // throw? break; // don't throw, stop } // Go ahead and add it *bytes = unchecked((byte)ch); bytes++; } // Need to do encoder stuff if (encoder != null) { // Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases if (fallbackBuffer != null && !fallbackBuffer.bUsedEncoder) // Clear it in case of MustFlush encoder._charLeftOver = (char)0; // Set our chars used count encoder._charsUsed = (int)(chars - charStart); } Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || (encoder != null && !encoder._throwOnOverflow), "[ASCIIEncoding.GetBytes]Expected Empty fallback buffer at end"); return (int)(bytes - byteStart); } // This is internal and called by something else, internal sealed override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) { // Just assert, we're called internally so these should be safe, checked already Debug.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null"); Debug.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative"); // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using DecoderReplacementFallback fallback = null; if (decoder == null) fallback = this.DecoderFallback as DecoderReplacementFallback; else { fallback = decoder.Fallback as DecoderReplacementFallback; Debug.Assert(!decoder._throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetCharCount]Expected empty fallback buffer"); } if (fallback != null && fallback.MaxCharCount == 1) { // Just return length, SBCS stay the same length because they don't map to surrogate // pairs and we don't have a decoder fallback. return count; } // Only need decoder fallback buffer if not using default replacement fallback, no best fit for ASCII DecoderFallbackBuffer fallbackBuffer = null; // Have to do it the hard way. // Assume charCount will be == count int charCount = count; byte[] byteBuffer = new byte[1]; // Do it our fast way byte* byteEnd = bytes + count; // Quick loop while (bytes < byteEnd) { // Faster if don't use *bytes++; byte b = *bytes; bytes++; // If unknown we have to do fallback count if (b >= 0x80) { if (fallbackBuffer == null) { if (decoder == null) fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(byteEnd - count, null); } // Use fallback buffer byteBuffer[0] = b; charCount--; // Have to unreserve the one we already allocated for b charCount += fallbackBuffer.InternalFallback(byteBuffer, bytes); } } // Fallback buffer must be empty Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetCharCount]Expected Empty fallback buffer"); // Converted sequence is same length as input return charCount; } internal sealed override unsafe int GetChars( byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS decoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null"); Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative"); Debug.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null"); Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative"); // Do it fast way if using ? replacement fallback byte* byteEnd = bytes + byteCount; byte* byteStart = bytes; char* charStart = chars; // Note: ASCII doesn't do best fit, but we have to fallback if they use something > 0x7f // Only need decoder fallback buffer if not using ? fallback. // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using DecoderReplacementFallback fallback = null; char* charsForFallback; if (decoder == null) fallback = this.DecoderFallback as DecoderReplacementFallback; else { fallback = decoder.Fallback as DecoderReplacementFallback; Debug.Assert(!decoder._throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetChars]Expected empty fallback buffer"); } if (fallback != null && fallback.MaxCharCount == 1) { // Try it the fast way char replacementChar = fallback.DefaultString[0]; // Need byteCount chars, otherwise too small buffer if (charCount < byteCount) { // Need at least 1 output byte, throw if must throw ThrowCharsOverflow(decoder, charCount < 1); // Not throwing, use what we can byteEnd = bytes + charCount; } // Quick loop, just do '?' replacement because we don't have fallbacks for decodings. while (bytes < byteEnd) { byte b = *(bytes++); if (b >= 0x80) // This is an invalid byte in the ASCII encoding. *(chars++) = replacementChar; else *(chars++) = unchecked((char)b); } // bytes & chars used are the same if (decoder != null) decoder._bytesUsed = (int)(bytes - byteStart); return (int)(chars - charStart); } // Slower way's going to need a fallback buffer DecoderFallbackBuffer fallbackBuffer = null; byte[] byteBuffer = new byte[1]; char* charEnd = chars + charCount; // Not quite so fast loop while (bytes < byteEnd) { // Faster if don't use *bytes++; byte b = *(bytes); bytes++; if (b >= 0x80) { // This is an invalid byte in the ASCII encoding. if (fallbackBuffer == null) { if (decoder == null) fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd); } // Use fallback buffer byteBuffer[0] = b; // Note that chars won't get updated unless this succeeds charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered bool fallbackResult = fallbackBuffer.InternalFallback(byteBuffer, bytes, ref charsForFallback); chars = charsForFallback; if (!fallbackResult) { // May or may not throw, but we didn't get this byte Debug.Assert(bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (fallback case)"); bytes--; // unused byte fallbackBuffer.InternalReset(); // Didn't fall this back ThrowCharsOverflow(decoder, chars == charStart); // throw? break; // don't throw, but stop loop } } else { // Make sure we have buffer space if (chars >= charEnd) { Debug.Assert(bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (normal case)"); bytes--; // unused byte ThrowCharsOverflow(decoder, chars == charStart); // throw? break; // don't throw, but stop loop } *(chars) = unchecked((char)b); chars++; } } // Might have had decoder fallback stuff. if (decoder != null) decoder._bytesUsed = (int)(bytes - byteStart); // Expect Empty fallback buffer for GetChars Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetChars]Expected Empty fallback buffer"); return (int)(chars - charStart); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Characters would be # of characters + 1 in case high surrogate is ? * max fallback long byteCount = (long)charCount + 1; if (EncoderFallback.MaxCharCount > 1) byteCount *= EncoderFallback.MaxCharCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less. if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Just return length, SBCS stay the same length because they don't map to surrogate long charCount = (long)byteCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer. if (DecoderFallback.MaxCharCount > 1) charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow); return (int)charCount; } // True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc) public override bool IsSingleByte { get { return true; } } public override Decoder GetDecoder() { return new DecoderNLS(this); } public override Encoder GetEncoder() { return new EncoderNLS(this); } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Ntfs { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; [Flags] internal enum FileRecordFlags : ushort { None = 0x0000, InUse = 0x0001, IsDirectory = 0x0002, IsMetaFile = 0x0004, HasViewIndex = 0x0008 } internal class FileRecord : FixupRecordBase { private ulong _logFileSequenceNumber; private ushort _sequenceNumber; private ushort _hardLinkCount; private ushort _firstAttributeOffset; private FileRecordFlags _flags; private uint _recordRealSize; private uint _recordAllocatedSize; private FileRecordReference _baseFile; private ushort _nextAttributeId; private uint _index; // Self-reference (on XP+) private List<AttributeRecord> _attributes; private bool _haveIndex; private uint _loadedIndex; public FileRecord(int sectorSize) : base("FILE", sectorSize) { } public FileRecord(int sectorSize, int recordLength, uint index) : base("FILE", sectorSize, recordLength) { ReInitialize(sectorSize, recordLength, index); } public uint MasterFileTableIndex { get { return _haveIndex ? _index : _loadedIndex; } } public uint LoadedIndex { get { return _loadedIndex; } set { _loadedIndex = value; } } public ulong LogFileSequenceNumber { get { return _logFileSequenceNumber; } } public ushort SequenceNumber { get { return _sequenceNumber; } set { _sequenceNumber = value; } } public ushort HardLinkCount { get { return _hardLinkCount; } set { _hardLinkCount = value; } } public uint AllocatedSize { get { return _recordAllocatedSize; } } public uint RealSize { get { return _recordRealSize; } } public FileRecordReference BaseFile { get { return _baseFile; } set { _baseFile = value; } } public FileRecordFlags Flags { get { return _flags; } set { _flags = value; } } public List<AttributeRecord> Attributes { get { return _attributes; } } public AttributeRecord FirstAttribute { get { return _attributes.Count > 0 ? _attributes[0] : null; } } public FileRecordReference Reference { get { return new FileRecordReference(MasterFileTableIndex, SequenceNumber); } } public ushort NextAttributeId { get { return _nextAttributeId; } } public bool IsMftRecord { get { return MasterFileTableIndex == MasterFileTable.MftIndex || (_baseFile.MftIndex == MasterFileTable.MftIndex && _baseFile.SequenceNumber != 0); } } public static FileAttributeFlags ConvertFlags(FileRecordFlags source) { FileAttributeFlags result = FileAttributeFlags.None; if ((source & FileRecordFlags.IsDirectory) != 0) { result |= FileAttributeFlags.Directory; } if ((source & FileRecordFlags.HasViewIndex) != 0) { result |= FileAttributeFlags.IndexView; } if ((source & FileRecordFlags.IsMetaFile) != 0) { result |= FileAttributeFlags.Hidden | FileAttributeFlags.System; } return result; } public void ReInitialize(int sectorSize, int recordLength, uint index) { Initialize("FILE", sectorSize, recordLength); _sequenceNumber++; _flags = FileRecordFlags.None; _recordAllocatedSize = (uint)recordLength; _nextAttributeId = 0; _index = index; _hardLinkCount = 0; _baseFile = new FileRecordReference(0); _attributes = new List<AttributeRecord>(); _haveIndex = true; } /// <summary> /// Gets an attribute by it's id. /// </summary> /// <param name="id">The attribute's id</param> /// <returns>The attribute, or <c>null</c></returns> public AttributeRecord GetAttribute(ushort id) { foreach (AttributeRecord attrRec in _attributes) { if (attrRec.AttributeId == id) { return attrRec; } } return null; } /// <summary> /// Gets an unnamed attribute. /// </summary> /// <param name="type">The attribute type</param> /// <returns>The attribute, or <c>null</c>.</returns> public AttributeRecord GetAttribute(AttributeType type) { return GetAttribute(type, null); } /// <summary> /// Gets an named attribute. /// </summary> /// <param name="type">The attribute type</param> /// <param name="name">The name of the attribute</param> /// <returns>The attribute, or <c>null</c>.</returns> public AttributeRecord GetAttribute(AttributeType type, string name) { foreach (AttributeRecord attrRec in _attributes) { if (attrRec.AttributeType == type && attrRec.Name == name) { return attrRec; } } return null; } public override string ToString() { foreach (AttributeRecord attr in _attributes) { if (attr.AttributeType == AttributeType.FileName) { StructuredNtfsAttribute<FileNameRecord> fnAttr = (StructuredNtfsAttribute<FileNameRecord>)NtfsAttribute.FromRecord(null, new FileRecordReference(0), attr); return fnAttr.Content.FileName; } } return "No Name"; } /// <summary> /// Creates a new attribute. /// </summary> /// <param name="type">The type of the new attribute</param> /// <param name="name">The name of the new attribute</param> /// <param name="indexed">Whether the attribute is marked as indexed</param> /// <param name="flags">Flags for the new attribute</param> /// <returns>The id of the new attribute</returns> public ushort CreateAttribute(AttributeType type, string name, bool indexed, AttributeFlags flags) { ushort id = _nextAttributeId++; _attributes.Add( new ResidentAttributeRecord( type, name, id, indexed, flags)); _attributes.Sort(); return id; } /// <summary> /// Creates a new non-resident attribute. /// </summary> /// <param name="type">The type of the new attribute</param> /// <param name="name">The name of the new attribute</param> /// <param name="flags">Flags for the new attribute</param> /// <returns>The id of the new attribute</returns> public ushort CreateNonResidentAttribute(AttributeType type, string name, AttributeFlags flags) { ushort id = _nextAttributeId++; _attributes.Add( new NonResidentAttributeRecord( type, name, id, flags, 0, new List<DataRun>())); _attributes.Sort(); return id; } /// <summary> /// Creates a new attribute. /// </summary> /// <param name="type">The type of the new attribute</param> /// <param name="name">The name of the new attribute</param> /// <param name="flags">Flags for the new attribute</param> /// <param name="firstCluster">The first cluster to assign to the attribute</param> /// <param name="numClusters">The number of sequential clusters to assign to the attribute</param> /// <param name="bytesPerCluster">The number of bytes in each cluster</param> /// <returns>The id of the new attribute</returns> public ushort CreateNonResidentAttribute(AttributeType type, string name, AttributeFlags flags, long firstCluster, ulong numClusters, uint bytesPerCluster) { ushort id = _nextAttributeId++; _attributes.Add( new NonResidentAttributeRecord( type, name, id, flags, firstCluster, numClusters, bytesPerCluster)); _attributes.Sort(); return id; } /// <summary> /// Adds an existing attribute. /// </summary> /// <param name="attrRec">The attribute to add</param> /// <returns>The new Id of the attribute</returns> /// <remarks>This method is used to move an attribute between different MFT records</remarks> public ushort AddAttribute(AttributeRecord attrRec) { attrRec.AttributeId = _nextAttributeId++; _attributes.Add(attrRec); _attributes.Sort(); return attrRec.AttributeId; } /// <summary> /// Removes an attribute by it's id. /// </summary> /// <param name="id">The attribute's id</param> public void RemoveAttribute(ushort id) { for (int i = 0; i < _attributes.Count; ++i) { if (_attributes[i].AttributeId == id) { _attributes.RemoveAt(i); break; } } } public void Reset() { _attributes.Clear(); _flags = FileRecordFlags.None; _hardLinkCount = 0; _nextAttributeId = 0; _recordRealSize = 0; } internal long GetAttributeOffset(ushort id) { int firstAttrPos = (ushort)Utilities.RoundUp((_haveIndex ? 0x30 : 0x2A) + UpdateSequenceSize, 8); int offset = firstAttrPos; foreach (var attr in _attributes) { if (attr.AttributeId == id) { return offset; } offset += attr.Size; } return -1; } internal void Dump(TextWriter writer, string indent) { writer.WriteLine(indent + "FILE RECORD (" + ToString() + ")"); writer.WriteLine(indent + " Magic: " + Magic); writer.WriteLine(indent + " Update Seq Offset: " + UpdateSequenceOffset); writer.WriteLine(indent + " Update Seq Count: " + UpdateSequenceCount); writer.WriteLine(indent + " Update Seq Number: " + UpdateSequenceNumber); writer.WriteLine(indent + " Log File Seq Num: " + _logFileSequenceNumber); writer.WriteLine(indent + " Sequence Number: " + _sequenceNumber); writer.WriteLine(indent + " Hard Link Count: " + _hardLinkCount); writer.WriteLine(indent + " Flags: " + _flags); writer.WriteLine(indent + " Record Real Size: " + _recordRealSize); writer.WriteLine(indent + " Record Alloc Size: " + _recordAllocatedSize); writer.WriteLine(indent + " Base File: " + _baseFile); writer.WriteLine(indent + " Next Attribute Id: " + _nextAttributeId); writer.WriteLine(indent + " Attribute Count: " + _attributes.Count); writer.WriteLine(indent + " Index (Self Ref): " + _index); } protected override void Read(byte[] buffer, int offset) { _logFileSequenceNumber = Utilities.ToUInt64LittleEndian(buffer, offset + 0x08); _sequenceNumber = Utilities.ToUInt16LittleEndian(buffer, offset + 0x10); _hardLinkCount = Utilities.ToUInt16LittleEndian(buffer, offset + 0x12); _firstAttributeOffset = Utilities.ToUInt16LittleEndian(buffer, offset + 0x14); _flags = (FileRecordFlags)Utilities.ToUInt16LittleEndian(buffer, offset + 0x16); _recordRealSize = Utilities.ToUInt32LittleEndian(buffer, offset + 0x18); _recordAllocatedSize = Utilities.ToUInt32LittleEndian(buffer, offset + 0x1C); _baseFile = new FileRecordReference(Utilities.ToUInt64LittleEndian(buffer, offset + 0x20)); _nextAttributeId = Utilities.ToUInt16LittleEndian(buffer, offset + 0x28); if (UpdateSequenceOffset >= 0x30) { _index = Utilities.ToUInt32LittleEndian(buffer, offset + 0x2C); _haveIndex = true; } _attributes = new List<AttributeRecord>(); int focus = _firstAttributeOffset; while (true) { int length; AttributeRecord attr = AttributeRecord.FromBytes(buffer, focus, out length); if (attr == null) { break; } _attributes.Add(attr); focus += (int)length; } } protected override ushort Write(byte[] buffer, int offset) { ushort headerEnd = (ushort)(_haveIndex ? 0x30 : 0x2A); _firstAttributeOffset = (ushort)Utilities.RoundUp(headerEnd + UpdateSequenceSize, 0x08); _recordRealSize = (uint)CalcSize(); Utilities.WriteBytesLittleEndian(_logFileSequenceNumber, buffer, offset + 0x08); Utilities.WriteBytesLittleEndian(_sequenceNumber, buffer, offset + 0x10); Utilities.WriteBytesLittleEndian(_hardLinkCount, buffer, offset + 0x12); Utilities.WriteBytesLittleEndian(_firstAttributeOffset, buffer, offset + 0x14); Utilities.WriteBytesLittleEndian((ushort)_flags, buffer, offset + 0x16); Utilities.WriteBytesLittleEndian(_recordRealSize, buffer, offset + 0x18); Utilities.WriteBytesLittleEndian(_recordAllocatedSize, buffer, offset + 0x1C); Utilities.WriteBytesLittleEndian(_baseFile.Value, buffer, offset + 0x20); Utilities.WriteBytesLittleEndian(_nextAttributeId, buffer, offset + 0x28); if (_haveIndex) { Utilities.WriteBytesLittleEndian((ushort)0, buffer, offset + 0x2A); // Alignment field Utilities.WriteBytesLittleEndian(_index, buffer, offset + 0x2C); } int pos = _firstAttributeOffset; foreach (var attr in _attributes) { pos += attr.Write(buffer, offset + pos); } Utilities.WriteBytesLittleEndian(uint.MaxValue, buffer, offset + pos); return headerEnd; } protected override int CalcSize() { int firstAttrPos = (ushort)Utilities.RoundUp((_haveIndex ? 0x30 : 0x2A) + UpdateSequenceSize, 8); int size = firstAttrPos; foreach (var attr in _attributes) { size += attr.Size; } return Utilities.RoundUp(size + 4, 8); // 0xFFFFFFFF terminator on attributes } } }
using System; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Bandwidth.Net.ApiV2; using LightMock; using Xunit; namespace Bandwidth.Net.Test.ApiV2 { public class MessageTests { public static bool IsValidSendRequest(HttpRequestMessage request) { return request.Method == HttpMethod.Post && request.RequestUri.PathAndQuery == "/v2/users/userId/messages" && request.Content.Headers.ContentType.MediaType == "application/json" && request.Content.ReadAsStringAsync().Result == "{\"from\":\"+12345678901\",\"to\":[\"+12345678902\"],\"text\":\"Hey, check this out!\",\"applicationId\":\"id\"}"; } public static bool IsValidCreateApplicationRequest(HttpRequestMessage request) { return request.RequestUri.AbsoluteUri == "https://dashboard.bandwidth.com/v1.0/api/accounts/AccountId/applications" && request.Method == HttpMethod.Post && request.Headers.Authorization.Parameter == "VXNlck5hbWU6UGFzc3dvcmQ=" && request.Content.ReadAsStringAsync().Result.NormilizeLineEnds() == "<Application>\r\n <AppName>App1</AppName>\r\n <CallbackUrl>url</CallbackUrl>\r\n <CallBackCreds />\r\n</Application>".NormilizeLineEnds(); } public static bool IsValidCreateLocationRequest(HttpRequestMessage request) { return request.RequestUri.AbsoluteUri == "https://dashboard.bandwidth.com/v1.0/api/accounts/AccountId/sites/SubaccountId/sippeers" && request.Method == HttpMethod.Post && request.Headers.Authorization.Parameter == "VXNlck5hbWU6UGFzc3dvcmQ=" && request.Content.ReadAsStringAsync().Result.NormilizeLineEnds() == "<SipPeer>\r\n <PeerName>Location1</PeerName>\r\n <IsDefaultPeer>false</IsDefaultPeer>\r\n</SipPeer>".NormilizeLineEnds(); } public static bool IsEnableSms(HttpRequestMessage request) { return request.RequestUri.AbsoluteUri == "https://dashboard.bandwidth.com/v1.0/api/accounts/AccountId/sites/SubaccountId/sippeers/LocationId/products/messaging/features/sms" && request.Method == HttpMethod.Post && request.Headers.Authorization.Parameter == "VXNlck5hbWU6UGFzc3dvcmQ=" && request.Content.ReadAsStringAsync().Result.NormilizeLineEnds() == "<SipPeerSmsFeature>\r\n <SipPeerSmsFeatureSettings>\r\n <TollFree>true</TollFree>\r\n <ShortCode>false</ShortCode>\r\n <Protocol>HTTP</Protocol>\r\n <Zone1>true</Zone1>\r\n <Zone2>false</Zone2>\r\n <Zone3>false</Zone3>\r\n <Zone4>false</Zone4>\r\n <Zone5>false</Zone5>\r\n </SipPeerSmsFeatureSettings>\r\n <HttpSettings>\r\n <ProxyPeerId>539692</ProxyPeerId>\r\n </HttpSettings>\r\n</SipPeerSmsFeature>".NormilizeLineEnds(); } public static bool IsEnableMms(HttpRequestMessage request) { return request.RequestUri.AbsoluteUri == "https://dashboard.bandwidth.com/v1.0/api/accounts/AccountId/sites/SubaccountId/sippeers/LocationId/products/messaging/features/mms" && request.Method == HttpMethod.Post && request.Headers.Authorization.Parameter == "VXNlck5hbWU6UGFzc3dvcmQ=" && request.Content.ReadAsStringAsync().Result.NormilizeLineEnds() == "<MmsFeature>\r\n <MmsSettings>\r\n <protocol>HTTP</protocol>\r\n </MmsSettings>\r\n <Protocols>\r\n <HTTP>\r\n <HttpSettings>\r\n <ProxyPeerId>539692</ProxyPeerId>\r\n </HttpSettings>\r\n </HTTP>\r\n </Protocols>\r\n</MmsFeature>".NormilizeLineEnds(); } public static bool IsAssignApplicationToLocationRequest(HttpRequestMessage request) { return request.RequestUri.AbsoluteUri == "https://dashboard.bandwidth.com/v1.0/api/accounts/AccountId/sites/SubaccountId/sippeers/LocationId/products/messaging/applicationSettings" && request.Method == HttpMethod.Put && request.Headers.Authorization.Parameter == "VXNlck5hbWU6UGFzc3dvcmQ=" && request.Content.ReadAsStringAsync().Result.NormilizeLineEnds() == "<ApplicationsSettings>\r\n <HttpMessagingV2AppId>ApplicationId</HttpMessagingV2AppId>\r\n</ApplicationsSettings>".NormilizeLineEnds(); } public static bool IsValidSearchAndOrderNumbersRequest(HttpRequestMessage request) { return request.RequestUri.AbsoluteUri == "https://dashboard.bandwidth.com/v1.0/api/accounts/AccountId/orders" && request.Method == HttpMethod.Post && request.Headers.Authorization.Parameter == "VXNlck5hbWU6UGFzc3dvcmQ=" && request.Content.ReadAsStringAsync().Result.NormilizeLineEnds() == "<Order>\r\n <AreaCodeSearchAndOrderType>\r\n <AreaCode>910</AreaCode>\r\n <Quantity>2</Quantity>\r\n </AreaCodeSearchAndOrderType>\r\n <SiteId>SubaccountId</SiteId>\r\n <PeerId>LocationId</PeerId>\r\n</Order>".NormilizeLineEnds(); } public static bool IsValidGetOrderRequest(HttpRequestMessage request) { return request.RequestUri.AbsoluteUri == "https://dashboard.bandwidth.com/v1.0/api/accounts/AccountId/orders/OrderId" && request.Method == HttpMethod.Get && request.Headers.Authorization.Parameter == "VXNlck5hbWU6UGFzc3dvcmQ="; } [Fact] public async void TestCreateMessagingApplicationAsync() { var authData = new IrisAuthData { AccountId = "AccountId", UserName = "UserName", Password = "Password", SubaccountId = "SubaccountId" }; var context = new MockContext<IHttp>(); var api = Helpers.GetClient(context).V2.Message; context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsValidCreateApplicationRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(new HttpResponseMessage { Content = Helpers.GetXmlContent("CreateMessagingApplicationResponse") })); var response = new HttpResponseMessage(); response.Headers.Location = new Uri("http://localhost/LocationId"); context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsValidCreateLocationRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(response)); context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsEnableSms(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(new HttpResponseMessage())); context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsEnableMms(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(new HttpResponseMessage())); context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsAssignApplicationToLocationRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(new HttpResponseMessage())); var application = await api.CreateMessagingApplicationAsync(authData, new CreateMessagingApplicationData { Name = "App1", CallbackUrl = "url", LocationName = "Location1", SmsOptions = new SmsOptions { TollFreeEnabled = true }, MmsOptions = new MmsOptions { Enabled = true } }); Assert.Equal("ApplicationId", application.ApplicationId); Assert.Equal("LocationId", application.LocationId); } [Fact] public async void TestCreateMessagingApplicationWithoutSmsAndMmsAsync() { var authData = new IrisAuthData { AccountId = "AccountId", UserName = "UserName", Password = "Password", SubaccountId = "SubaccountId" }; var context = new MockContext<IHttp>(); var api = Helpers.GetClient(context).V2.Message; context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsValidCreateApplicationRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(new HttpResponseMessage { Content = Helpers.GetXmlContent("CreateMessagingApplicationResponse") })); var response = new HttpResponseMessage(); response.Headers.Location = new Uri("http://localhost/LocationId"); context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsValidCreateLocationRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(response)); context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsAssignApplicationToLocationRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(new HttpResponseMessage())); var application = await api.CreateMessagingApplicationAsync(authData, new CreateMessagingApplicationData { Name = "App1", CallbackUrl = "url", LocationName = "Location1" }); Assert.Equal("ApplicationId", application.ApplicationId); Assert.Equal("LocationId", application.LocationId); } [Fact] public async void TestCheckResponse() { var authData = new IrisAuthData { AccountId = "AccountId", UserName = "UserName", Password = "Password", SubaccountId = "SubaccountId" }; var context = new MockContext<IHttp>(); var api = Helpers.GetClient(context).V2.Message; context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsValidCreateApplicationRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(new HttpResponseMessage { Content = new StringContent("<Response><ErrorCode>Code</ErrorCode><Description>Description</Description></Response>") })); var err = await Assert.ThrowsAsync<BandwidthIrisException>(() => api.CreateMessagingApplicationAsync(authData, new CreateMessagingApplicationData { Name = "App1", CallbackUrl = "url", LocationName = "Location1" })); Assert.Equal("Code", err.Code); Assert.Equal("Description", err.Message); } [Fact] public async void TestCheckResponse2() { var authData = new IrisAuthData { AccountId = "AccountId", UserName = "UserName", Password = "Password", SubaccountId = "SubaccountId" }; var context = new MockContext<IHttp>(); var api = Helpers.GetClient(context).V2.Message; context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsValidCreateApplicationRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(new HttpResponseMessage { Content = new StringContent("<Response><Error><Code>Code</Code><Description>Description</Description></Error></Response>") })); var err = await Assert.ThrowsAsync<BandwidthIrisException>(() => api.CreateMessagingApplicationAsync(authData, new CreateMessagingApplicationData { Name = "App1", CallbackUrl = "url", LocationName = "Location1" })); Assert.Equal("Code", err.Code); Assert.Equal("Description", err.Message); } [Fact] public async void TestCheckResponse3() { var authData = new IrisAuthData { AccountId = "AccountId", UserName = "UserName", Password = "Password", SubaccountId = "SubaccountId" }; var context = new MockContext<IHttp>(); var api = Helpers.GetClient(context).V2.Message; context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsValidCreateApplicationRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(new HttpResponseMessage { Content = new StringContent("<Response><Errors><Code>Code</Code><Description>Description</Description></Errors></Response>") })); var err = (BandwidthIrisException)(await Assert.ThrowsAsync<AggregateException>(() => api.CreateMessagingApplicationAsync(authData, new CreateMessagingApplicationData { Name = "App1", CallbackUrl = "url", LocationName = "Location1" }))).InnerExceptions.First(); Assert.Equal("Code", err.Code); Assert.Equal("Description", err.Message); } [Fact] public async void TestCheckResponse4() { var authData = new IrisAuthData { AccountId = "AccountId", UserName = "UserName", Password = "Password", SubaccountId = "SubaccountId" }; var context = new MockContext<IHttp>(); var api = Helpers.GetClient(context).V2.Message; context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsValidCreateApplicationRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(new HttpResponseMessage { Content = new StringContent("<Response><resultCode>Code</resultCode><resultMessage>Description</resultMessage></Response>") })); var err = await Assert.ThrowsAsync<BandwidthIrisException>(() => api.CreateMessagingApplicationAsync(authData, new CreateMessagingApplicationData { Name = "App1", CallbackUrl = "url", LocationName = "Location1" })); Assert.Equal("Code", err.Code); Assert.Equal("Description", err.Message); } [Fact] public async void TestCheckResponse5() { var authData = new IrisAuthData { AccountId = "AccountId", UserName = "UserName", Password = "Password", SubaccountId = "SubaccountId" }; var context = new MockContext<IHttp>(); var api = Helpers.GetClient(context).V2.Message; context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsValidCreateApplicationRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(new HttpResponseMessage { StatusCode = HttpStatusCode.NotFound })); await Assert.ThrowsAsync<BandwidthIrisException>(() => api.CreateMessagingApplicationAsync(authData, new CreateMessagingApplicationData { Name = "App1", CallbackUrl = "url", LocationName = "Location1" })); } [Fact] public async void TestSearchAndOrderNumbersAsync() { var authData = new IrisAuthData { AccountId = "AccountId", UserName = "UserName", Password = "Password", SubaccountId = "SubaccountId" }; var context = new MockContext<IHttp>(); var api = Helpers.GetClient(context).V2.Message; context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsValidSearchAndOrderNumbersRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(new HttpResponseMessage { Content = Helpers.GetXmlContent("OrderNumbersResponse") })); context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsValidGetOrderRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(new HttpResponseMessage { Content = Helpers.GetXmlContent("OrderResponse") })); var numbers = await api.SearchAndOrderNumbersAsync(authData, new MessagingApplication { ApplicationId = "ApplicationId", LocationId = "LocationId" }, new AreaCodeSearchAndOrderNumbersQuery { AreaCode = "910", Quantity = 2 }); Assert.Equal(2, numbers.Length); } [Fact] public async void TestSearchAndOrderNumbersAsyncFail() { var authData = new IrisAuthData { AccountId = "AccountId", UserName = "UserName", Password = "Password", SubaccountId = "SubaccountId" }; var context = new MockContext<IHttp>(); var api = Helpers.GetClient(context).V2.Message; context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsValidSearchAndOrderNumbersRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(new HttpResponseMessage { Content = Helpers.GetXmlContent("OrderNumbersResponse") })); context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsValidGetOrderRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(new HttpResponseMessage { Content = Helpers.GetXmlContent("FailedOrderResponse") })); await Assert.ThrowsAsync<BandwidthException>(() => api.SearchAndOrderNumbersAsync(authData, new MessagingApplication { ApplicationId = "ApplicationId", LocationId = "LocationId" }, new AreaCodeSearchAndOrderNumbersQuery { AreaCode = "910", Quantity = 2 })); } [Fact] public async void TestSearchAndOrderNumbersAsyncTimeout() { var authData = new IrisAuthData { AccountId = "AccountId", UserName = "UserName", Password = "Password", SubaccountId = "SubaccountId" }; var context = new MockContext<IHttp>(); var api = Helpers.GetClient(context).V2.Message; context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsValidSearchAndOrderNumbersRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(new HttpResponseMessage { Content = Helpers.GetXmlContent("OrderNumbersResponse") })); context.Arrange(m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsValidGetOrderRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(new HttpResponseMessage { Content = Helpers.GetXmlContent("OrderNumbersResponse") })); await Assert.ThrowsAsync<TimeoutException>(() => api.SearchAndOrderNumbersAsync(authData, new MessagingApplication { ApplicationId = "ApplicationId", LocationId = "LocationId" }, new AreaCodeSearchAndOrderNumbersQuery { AreaCode = "910", Quantity = 2, Timeout = TimeSpan.FromMilliseconds(1) })); } [Fact] public async void TestSend() { var response = new HttpResponseMessage(HttpStatusCode.Accepted); response.Content = new JsonContent(Helpers.GetJsonResourse("SendMessageResponse2")); var context = new MockContext<IHttp>(); context.Arrange( m => m.SendAsync(The<HttpRequestMessage>.Is(r => IsValidSendRequest(r)), HttpCompletionOption.ResponseContentRead, null)).Returns(Task.FromResult(response)); var api = Helpers.GetClient(context).V2.Message; var message = await api.SendAsync(new MessageData { From = "+12345678901", To = new[] {"+12345678902"}, Text = "Hey, check this out!", ApplicationId = "id" }); Assert.Equal("14762070468292kw2fuqty55yp2b2", message.Id); Assert.Equal(MessageDirection.Out, message.Direction); } [Fact] public void TestAreaCodeSearchAndOrderNumbersQuery() { var query = new AreaCodeSearchAndOrderNumbersQuery {AreaCode = "910", Quantity = 1}; Assert.Equal("<AreaCodeSearchAndOrderType>\r\n <AreaCode>910</AreaCode>\r\n <Quantity>1</Quantity>\r\n</AreaCodeSearchAndOrderType>".NormilizeLineEnds(), query.ToXElement().ToString().NormilizeLineEnds()); } [Fact] public void TestRateCenterSearchAndOrdeNumbersQuery() { var query = new RateCenterSearchAndOrdeNumbersQuery { RateCenter = "NC", Quantity = 1 }; Assert.Equal("<RateCenterSearchAndOrderType>\r\n <RateCenter>NC</RateCenter>\r\n <State />\r\n <Quantity>1</Quantity>\r\n</RateCenterSearchAndOrderType>".NormilizeLineEnds(), query.ToXElement().ToString().NormilizeLineEnds()); } [Fact] public void TestNpaNxxSearchAndOrderNumbersQuery() { var query = new NpaNxxSearchAndOrderNumbersQuery { NpaNxx = "911", Quantity = 1 }; Assert.Equal("<NPANXXSearchAndOrderType>\r\n <NpaNxx>911</NpaNxx>\r\n <EnableTNDetail>false</EnableTNDetail>\r\n <EnableLCA>false</EnableLCA>\r\n <Quantity>1</Quantity>\r\n</NPANXXSearchAndOrderType>".NormilizeLineEnds(), query.ToXElement().ToString().NormilizeLineEnds()); } [Fact] public void TestTollFreeVanitySearchAndOrderNumbersQuery() { var query = new TollFreeVanitySearchAndOrderNumbersQuery { TollFreeVanity = "0", Quantity = 1 }; Assert.Equal("<TollFreeVanitySearchAndOrderType>\r\n <TollFreeVanity>0</TollFreeVanity>\r\n <Quantity>1</Quantity>\r\n</TollFreeVanitySearchAndOrderType>".NormilizeLineEnds(), query.ToXElement().ToString().NormilizeLineEnds()); } [Fact] public void TestTollFreeWildCharSearchAndOrderNumbersQuery() { var query = new TollFreeWildCharSearchAndOrderNumbersQuery { TollFreeWildCardPattern = "*", Quantity = 1 }; Assert.Equal("<TollFreeWildCharSearchAndOrderType>\r\n <TollFreeWildCardPattern>*</TollFreeWildCardPattern>\r\n <Quantity>1</Quantity>\r\n</TollFreeWildCharSearchAndOrderType>".NormilizeLineEnds(), query.ToXElement().ToString().NormilizeLineEnds()); } [Fact] public void TestStateSearchAndOrderNumbersQuery() { var query = new StateSearchAndOrderNumbersQuery { State = "NC", Quantity = 1 }; Assert.Equal("<StateSearchAndOrderType>\r\n <State>NC</State>\r\n <Quantity>1</Quantity>\r\n</StateSearchAndOrderType>".NormilizeLineEnds(), query.ToXElement().ToString().NormilizeLineEnds()); } [Fact] public void TestCitySearchAndOrderNumbersQuery() { var query = new CitySearchAndOrderNumbersQuery { State = "NC", City = "Cary", Quantity = 1 }; Assert.Equal("<CitySearchAndOrderType>\r\n <State>NC</State>\r\n <City>Cary</City>\r\n <Quantity>1</Quantity>\r\n</CitySearchAndOrderType>".NormilizeLineEnds(), query.ToXElement().ToString().NormilizeLineEnds()); } [Fact] public void TestZipSearchAndOrderNumbersQuery() { var query = new ZipSearchAndOrderNumbersQuery { Zip = "000", Quantity = 1 }; Assert.Equal("<ZIPSearchAndOrderType>\r\n <Zip>000</Zip>\r\n <Quantity>1</Quantity>\r\n</ZIPSearchAndOrderType>".NormilizeLineEnds(), query.ToXElement().ToString().NormilizeLineEnds()); } [Fact] public void TestLataSearchAndOrderNumbersQuery() { var query = new LataSearchAndOrderNumbersQuery { Lata = "000"}; Assert.Equal("<LATASearchAndOrderType>\r\n <Lata>000</Lata>\r\n <Quantity>10</Quantity>\r\n</LATASearchAndOrderType>".NormilizeLineEnds(), query.ToXElement().ToString().NormilizeLineEnds()); } [Fact] public void TestCombinedSearchAndOrderNumbersQuery() { var query = new CombinedSearchAndOrderNumbersQuery { AreaCode = "900" }; Assert.Equal("<CombinedSearchAndOrderType>\r\n <Quantity>10</Quantity>\r\n <AreaCode>900</AreaCode>\r\n</CombinedSearchAndOrderType>".NormilizeLineEnds(), query.ToXElement().ToString().NormilizeLineEnds()); } } internal static class StringExtensions { public static string NormilizeLineEnds(this string text) { return text.Replace("\r\n", "\n"); } } }
#region namespace using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Security; using System.Configuration; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Security; using Umbraco.Core.Services; using System.Security.Cryptography; using System.Web.Util; using System.Collections.Specialized; using System.Configuration.Provider; using System.Security; using System.Security.Permissions; using System.Runtime.CompilerServices; using Member = umbraco.cms.businesslogic.member.Member; using MemberType = umbraco.cms.businesslogic.member.MemberType; using User = umbraco.BusinessLogic.User; #endregion namespace umbraco.providers.members { /// <summary> /// Custom Membership Provider for Umbraco Members (User authentication for Frontend applications NOT umbraco CMS) /// </summary> [Obsolete("This has been superseded by Umbraco.Web.Security.Providers.MembersMembershipProvider")] public class UmbracoMembershipProvider : UmbracoMembershipProviderBase, IUmbracoMemberTypeMembershipProvider { public UmbracoMembershipProvider() { LockPropertyTypeAlias = Constants.Conventions.Member.IsLockedOut; LastLockedOutPropertyTypeAlias = Constants.Conventions.Member.LastLockoutDate; FailedPasswordAttemptsPropertyTypeAlias = Constants.Conventions.Member.FailedPasswordAttempts; ApprovedPropertyTypeAlias = Constants.Conventions.Member.IsApproved; CommentPropertyTypeAlias = Constants.Conventions.Member.Comments; LastLoginPropertyTypeAlias = Constants.Conventions.Member.LastLoginDate; LastPasswordChangedPropertyTypeAlias = Constants.Conventions.Member.LastPasswordChangeDate; PasswordRetrievalQuestionPropertyTypeAlias = Constants.Conventions.Member.PasswordQuestion; PasswordRetrievalAnswerPropertyTypeAlias = Constants.Conventions.Member.PasswordAnswer; } #region Fields private string _defaultMemberTypeAlias = "Member"; private string _providerName = Member.UmbracoMemberProviderName; private volatile bool _hasDefaultMember = false; private static readonly object Locker = new object(); #endregion public string LockPropertyTypeAlias { get; protected set; } public string LastLockedOutPropertyTypeAlias { get; protected set; } public string FailedPasswordAttemptsPropertyTypeAlias { get; protected set; } public string ApprovedPropertyTypeAlias { get; protected set; } public string CommentPropertyTypeAlias { get; protected set; } public string LastLoginPropertyTypeAlias { get; protected set; } public string LastPasswordChangedPropertyTypeAlias { get; protected set; } public string PasswordRetrievalQuestionPropertyTypeAlias { get; protected set; } public string PasswordRetrievalAnswerPropertyTypeAlias { get; protected set; } /// <summary> /// Override to maintain backwards compatibility with 0 required non-alphanumeric chars /// </summary> public override int DefaultMinNonAlphanumericChars { get { return 0; } } /// <summary> /// Override to maintain backwards compatibility with only 4 required length /// </summary> public override int DefaultMinPasswordLength { get { return 4; } } /// <summary> /// Override to maintain backwards compatibility /// </summary> public override bool DefaultUseLegacyEncoding { get { return true; } } /// <summary> /// For backwards compatibility, this provider supports this option /// </summary> public override bool AllowManuallyChangingPassword { get { return true; } } #region Initialization Method /// <summary> /// Initializes the provider. /// </summary> /// <param name="name">The friendly name of the provider.</param> /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param> /// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception> /// <exception cref="T:System.InvalidOperationException">An attempt is made to call /// <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"></see> on a provider after the provider /// has already been initialized.</exception> /// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception> public override void Initialize(string name, NameValueCollection config) { // Initialize values from web.config if (config == null) throw new ArgumentNullException("config"); if (string.IsNullOrEmpty(name)) name = Constants.Conventions.Member.UmbracoMemberProviderName; base.Initialize(name, config); _providerName = name; // test for membertype (if not specified, choose the first member type available) if (config["defaultMemberTypeAlias"] != null) { _defaultMemberTypeAlias = config["defaultMemberTypeAlias"]; if (_defaultMemberTypeAlias.IsNullOrWhiteSpace()) { throw new ProviderException("No default MemberType alias is specified in the web.config string. Please add a 'defaultMemberTypeAlias' to the add element in the provider declaration in web.config"); } _hasDefaultMember = true; } // test for approve status if (config["umbracoApprovePropertyTypeAlias"] != null) { ApprovedPropertyTypeAlias = config["umbracoApprovePropertyTypeAlias"]; } // test for lock attempts if (config["umbracoLockPropertyTypeAlias"] != null) { LockPropertyTypeAlias = config["umbracoLockPropertyTypeAlias"]; } if (config["umbracoLastLockedPropertyTypeAlias"] != null) { LastLockedOutPropertyTypeAlias = config["umbracoLastLockedPropertyTypeAlias"]; } if (config["umbracoLastPasswordChangedPropertyTypeAlias"] != null) { LastPasswordChangedPropertyTypeAlias = config["umbracoLastPasswordChangedPropertyTypeAlias"]; } if (config["umbracoFailedPasswordAttemptsPropertyTypeAlias"] != null) { FailedPasswordAttemptsPropertyTypeAlias = config["umbracoFailedPasswordAttemptsPropertyTypeAlias"]; } // comment property if (config["umbracoCommentPropertyTypeAlias"] != null) { CommentPropertyTypeAlias = config["umbracoCommentPropertyTypeAlias"]; } // last login date if (config["umbracoLastLoginPropertyTypeAlias"] != null) { LastLoginPropertyTypeAlias = config["umbracoLastLoginPropertyTypeAlias"]; } // password retrieval if (config["umbracoPasswordRetrievalQuestionPropertyTypeAlias"] != null) { PasswordRetrievalQuestionPropertyTypeAlias = config["umbracoPasswordRetrievalQuestionPropertyTypeAlias"]; } if (config["umbracoPasswordRetrievalAnswerPropertyTypeAlias"] != null) { PasswordRetrievalAnswerPropertyTypeAlias = config["umbracoPasswordRetrievalAnswerPropertyTypeAlias"]; } } #endregion #region Methods /// <summary> /// Processes a request to update the password for a membership user. /// </summary> /// <param name="username">The user to update the password for.</param> /// <param name="oldPassword">This property is ignore for this provider</param> /// <param name="newPassword">The new password for the specified user.</param> /// <returns> /// true if the password was updated successfully; otherwise, false. /// </returns> protected override bool PerformChangePassword(string username, string oldPassword, string newPassword) { //NOTE: due to backwards compatibility reasons, this provider doesn't care about the old password and // allows simply setting the password manually so we don't really care about the old password. // This is allowed based on the overridden AllowManuallyChangingPassword option. // in order to support updating passwords from the umbraco core, we can't validate the old password var m = Member.GetMemberFromLoginName(username); if (m == null) return false; string salt; var encodedPassword = EncryptOrHashNewPassword(newPassword, out salt); m.ChangePassword( FormatPasswordForStorage(encodedPassword, salt)); UpdateMemberProperty(m, LastPasswordChangedPropertyTypeAlias, DateTime.Now); m.Save(); return true; } /// <summary> /// Processes a request to update the password question and answer for a membership user. /// </summary> /// <param name="username">The user to change the password question and answer for.</param> /// <param name="password">The password for the specified user.</param> /// <param name="newPasswordQuestion">The new password question for the specified user.</param> /// <param name="newPasswordAnswer">The new password answer for the specified user.</param> /// <returns> /// true if the password question and answer are updated successfully; otherwise, false. /// </returns> protected override bool PerformChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { if (string.IsNullOrEmpty(PasswordRetrievalQuestionPropertyTypeAlias) || string.IsNullOrEmpty(PasswordRetrievalAnswerPropertyTypeAlias)) { throw new NotSupportedException("Updating the password Question and Answer is not valid if the properties aren't set in the config file"); } var m = Member.GetMemberFromLoginName(username); if (m == null) { return false; } UpdateMemberProperty(m, PasswordRetrievalQuestionPropertyTypeAlias, newPasswordQuestion); UpdateMemberProperty(m, PasswordRetrievalAnswerPropertyTypeAlias, newPasswordAnswer); m.Save(); return true; } public override string DefaultMemberTypeAlias { get { if (_hasDefaultMember == false) { lock (Locker) { if (_hasDefaultMember == false) { var types = MemberType.GetAll; if (types.Length == 1) _defaultMemberTypeAlias = types[0].Alias; else throw new ProviderException("No default MemberType alias is specified in the web.config string. Please add a 'defaultMemberTypeAlias' to the add element in the provider declaration in web.config"); _hasDefaultMember = true; } } } return _defaultMemberTypeAlias; } } /// <summary> /// Adds a new membership user to the data source. /// </summary> /// <param name="memberTypeAlias"></param> /// <param name="username">The user name for the new user.</param> /// <param name="password">The password for the new user.</param> /// <param name="email">The e-mail address for the new user.</param> /// <param name="passwordQuestion">The password question for the new user.</param> /// <param name="passwordAnswer">The password answer for the new user</param> /// <param name="isApproved">Whether or not the new user is approved to be validated.</param> /// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param> /// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"></see> enumeration value indicating whether the user was created successfully.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the information for the newly created user. /// </returns> protected override MembershipUser PerformCreateUser(string memberTypeAlias, string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { if (Member.GetMemberFromLoginName(username) != null) { status = MembershipCreateStatus.DuplicateUserName; LogHelper.Warn<UmbracoMembershipProvider>("Cannot create member as username already exists: " + username); return null; } if (Member.GetMemberFromEmail(email) != null && RequiresUniqueEmail) { status = MembershipCreateStatus.DuplicateEmail; LogHelper.Warn<UmbracoMembershipProvider>( "Cannot create member as a member with the same email address exists: " + email); return null; } var memberType = MemberType.GetByAlias(memberTypeAlias); if (memberType == null) { throw new InvalidOperationException("Could not find a member type with alias " + memberTypeAlias + ". Ensure your membership provider configuration is up to date and that the default member type exists."); } var m = Member.MakeNew(username, email, memberType, User.GetUser(0)); string salt; var encodedPassword = EncryptOrHashNewPassword(password, out salt); //set the password on the member m.ChangePassword(FormatPasswordForStorage(encodedPassword, salt)); // custom fields if (string.IsNullOrEmpty(PasswordRetrievalQuestionPropertyTypeAlias) == false) { UpdateMemberProperty(m, PasswordRetrievalQuestionPropertyTypeAlias, passwordQuestion); } if (string.IsNullOrEmpty(PasswordRetrievalAnswerPropertyTypeAlias) == false) { UpdateMemberProperty(m, PasswordRetrievalAnswerPropertyTypeAlias, passwordAnswer); } if (string.IsNullOrEmpty(ApprovedPropertyTypeAlias) == false) { UpdateMemberProperty(m, ApprovedPropertyTypeAlias, isApproved ? 1 : 0); } if (string.IsNullOrEmpty(LastLoginPropertyTypeAlias) == false) { UpdateMemberProperty(m, LastLoginPropertyTypeAlias, DateTime.Now); } if (string.IsNullOrEmpty(LastPasswordChangedPropertyTypeAlias) == false) { UpdateMemberProperty(m, LastPasswordChangedPropertyTypeAlias, DateTime.Now); } var mUser = ConvertToMembershipUser(m); // save m.Save(); status = MembershipCreateStatus.Success; return mUser; } /// <summary> /// Removes a user from the membership data source. /// </summary> /// <param name="username">The name of the user to delete.</param> /// <param name="deleteAllRelatedData"> /// TODO: This setting currently has no effect /// </param> /// <returns> /// true if the user was successfully deleted; otherwise, false. /// </returns> public override bool DeleteUser(string username, bool deleteAllRelatedData) { var m = Member.GetMemberFromLoginName(username); if (m == null) return false; m.delete(); return true; } /// <summary> /// Gets a collection of membership users where the e-mail address contains the specified e-mail address to match. /// </summary> /// <param name="emailToMatch">The e-mail address to search for.</param> /// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param> /// <param name="pageSize">The size of the page of results to return.</param> /// <param name="totalRecords">The total number of matched users.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex. /// </returns> public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) { var byEmail = ApplicationContext.Current.Services.MemberService.FindByEmail(emailToMatch, pageIndex, pageSize, out totalRecords, StringPropertyMatchType.Wildcard).ToArray(); var collection = new MembershipUserCollection(); foreach (var m in byEmail) { collection.Add(ConvertToMembershipUser(m)); } return collection; } /// <summary> /// Gets a collection of membership users where the user name contains the specified user name to match. /// </summary> /// <param name="usernameToMatch">The user name to search for.</param> /// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param> /// <param name="pageSize">The size of the page of results to return.</param> /// <param name="totalRecords">The total number of matched users.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex. /// </returns> public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { var byEmail = ApplicationContext.Current.Services.MemberService.FindByUsername(usernameToMatch, pageIndex, pageSize, out totalRecords, StringPropertyMatchType.Wildcard).ToArray(); var collection = new MembershipUserCollection(); foreach (var m in byEmail) { collection.Add(ConvertToMembershipUser(m)); } return collection; } /// <summary> /// Gets a collection of all the users in the data source in pages of data. /// </summary> /// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param> /// <param name="pageSize">The size of the page of results to return.</param> /// <param name="totalRecords">The total number of matched users.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex. /// </returns> public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { var membersList = new MembershipUserCollection(); var pagedMembers = ApplicationContext.Current.Services.MemberService.GetAll(pageIndex, pageSize, out totalRecords); foreach (var m in pagedMembers) { membersList.Add(ConvertToMembershipUser(m)); } return membersList; } /// <summary> /// Gets the number of users currently accessing the application. /// </summary> /// <returns> /// The number of users currently accessing the application. /// </returns> public override int GetNumberOfUsersOnline() { return ApplicationContext.Current.Services.MemberService.GetCount(MemberCountType.Online); } /// <summary> /// Gets the password for the specified user name from the data source. /// </summary> /// <param name="username">The user to retrieve the password for.</param> /// <param name="answer">The password answer for the user.</param> /// <returns> /// The password for the specified user name. /// </returns> protected override string PerformGetPassword(string username, string answer) { var m = Member.GetMemberFromLoginName(username); if (m == null) { throw new MembershipPasswordException("The supplied user is not found"); } // check if user is locked out if (string.IsNullOrEmpty(LockPropertyTypeAlias) == false) { var isLockedOut = false; bool.TryParse(GetMemberProperty(m, LockPropertyTypeAlias, true), out isLockedOut); if (isLockedOut) { throw new MembershipPasswordException("The supplied user is locked out"); } } if (RequiresQuestionAndAnswer) { // check if password answer property alias is set if (string.IsNullOrEmpty(PasswordRetrievalAnswerPropertyTypeAlias) == false) { // match password answer if (GetMemberProperty(m, PasswordRetrievalAnswerPropertyTypeAlias, false) != answer) { throw new MembershipPasswordException("Incorrect password answer"); } } else { throw new ProviderException("Password retrieval answer property alias is not set! To automatically support password question/answers you'll need to add references to the membertype properties in the 'Member' element in web.config by adding their aliases to the 'umbracoPasswordRetrievalQuestionPropertyTypeAlias' and 'umbracoPasswordRetrievalAnswerPropertyTypeAlias' attributes"); } } var decodedPassword = DecryptPassword(m.GetPassword()); return decodedPassword; } /// <summary> /// Gets information from the data source for a user. Provides an option to update the last-activity date/time stamp for the user. /// </summary> /// <param name="username">The name of the user to get information for.</param> /// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the specified user's information from the data source. /// </returns> public override MembershipUser GetUser(string username, bool userIsOnline) { if (string.IsNullOrEmpty(username)) return null; var m = Member.GetMemberFromLoginName(username); if (m == null) { return null; } if (userIsOnline && LastLoginPropertyTypeAlias.IsNullOrWhiteSpace() == false) { UpdateMemberProperty(m, LastLoginPropertyTypeAlias, DateTime.Now); //don't raise events for this! It just sets the member dates, if we do raise events this will // cause all distributed cache to execute - which will clear out some caches we don't want. // http://issues.umbraco.org/issue/U4-3451 m.Save(false); } return ConvertToMembershipUser(m); } /// <summary> /// Gets information from the data source for a user based on the unique identifier for the membership user. Provides an option to update the last-activity date/time stamp for the user. /// </summary> /// <param name="providerUserKey">The unique identifier for the membership user to get information for.</param> /// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the specified user's information from the data source. /// </returns> public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { var asGuid = providerUserKey.TryConvertTo<Guid>(); if (asGuid.Success) { var m = new Member(asGuid.Result); if (userIsOnline && LastLoginPropertyTypeAlias.IsNullOrWhiteSpace() == false) { UpdateMemberProperty(m, LastLoginPropertyTypeAlias, DateTime.Now); //don't raise events for this! It just sets the member dates, if we do raise events this will // cause all distributed cache to execute - which will clear out some caches we don't want. // http://issues.umbraco.org/issue/U4-3451 m.Save(false); } return ConvertToMembershipUser(m); } var asInt = providerUserKey.TryConvertTo<int>(); if (asInt.Success) { var m = new Member(asInt.Result); if (userIsOnline && LastLoginPropertyTypeAlias.IsNullOrWhiteSpace() == false) { UpdateMemberProperty(m, LastLoginPropertyTypeAlias, DateTime.Now); //don't raise events for this! It just sets the member dates, if we do raise events this will // cause all distributed cache to execute - which will clear out some caches we don't want. // http://issues.umbraco.org/issue/U4-3451 m.Save(false); } return ConvertToMembershipUser(m); } throw new InvalidOperationException("The " + GetType() + " provider only supports GUID or Int as a providerUserKey"); } /// <summary> /// Gets the user name associated with the specified e-mail address. /// </summary> /// <param name="email">The e-mail address to search for.</param> /// <returns> /// The user name associated with the specified e-mail address. If no match is found, return null. /// </returns> public override string GetUserNameByEmail(string email) { var m = Member.GetMemberFromEmail(email); return m == null ? null : m.LoginName; } /// <summary> /// Resets a user's password to a new, automatically generated password. /// </summary> /// <param name="username">The user to reset the password for.</param> /// <param name="answer">The password answer for the specified user (not used with Umbraco).</param> /// <param name="generatedPassword"></param> /// <returns>The new password for the specified user.</returns> protected override string PerformResetPassword(string username, string answer, string generatedPassword) { //TODO: This should be here - but how do we update failure count in this provider?? //if (answer == null && RequiresQuestionAndAnswer) //{ // UpdateFailureCount(username, "passwordAnswer"); // throw new ProviderException("Password answer required for password reset."); //} var m = Member.GetMemberFromLoginName(username); if (m == null) { throw new ProviderException("The supplied user is not found"); } // check if user is locked out if (string.IsNullOrEmpty(LockPropertyTypeAlias) == false) { var isLockedOut = false; bool.TryParse(GetMemberProperty(m, LockPropertyTypeAlias, true), out isLockedOut); if (isLockedOut) { throw new ProviderException("The member is locked out."); } } if (RequiresQuestionAndAnswer) { // check if password answer property alias is set if (string.IsNullOrEmpty(PasswordRetrievalAnswerPropertyTypeAlias) == false) { // match password answer if (GetMemberProperty(m, PasswordRetrievalAnswerPropertyTypeAlias, false) != answer) { throw new ProviderException("Incorrect password answer"); } } else { throw new ProviderException("Password retrieval answer property alias is not set! To automatically support password question/answers you'll need to add references to the membertype properties in the 'Member' element in web.config by adding their aliases to the 'umbracoPasswordRetrievalQuestionPropertyTypeAlias' and 'umbracoPasswordRetrievalAnswerPropertyTypeAlias' attributes"); } } string salt; var encodedPassword = EncryptOrHashNewPassword(generatedPassword, out salt); //set the password on the member m.ChangePassword(FormatPasswordForStorage(encodedPassword, salt)); if (string.IsNullOrEmpty(LastPasswordChangedPropertyTypeAlias) == false) { UpdateMemberProperty(m, LastPasswordChangedPropertyTypeAlias, DateTime.Now); } m.Save(); return generatedPassword; } /// <summary> /// Clears a lock so that the membership user can be validated. /// </summary> /// <param name="userName">The membership user to clear the lock status for.</param> /// <returns> /// true if the membership user was successfully unlocked; otherwise, false. /// </returns> public override bool UnlockUser(string userName) { if (string.IsNullOrEmpty(LockPropertyTypeAlias) == false) { var m = Member.GetMemberFromLoginName(userName); if (m != null) { UpdateMemberProperty(m, LockPropertyTypeAlias, 0); if (string.IsNullOrEmpty(FailedPasswordAttemptsPropertyTypeAlias) == false) { UpdateMemberProperty(m, FailedPasswordAttemptsPropertyTypeAlias, 0); } m.Save(); return true; } throw new ProviderException(string.Format("No member with the username '{0}' found", userName)); } throw new ProviderException("To enable lock/unlocking, you need to add a 'bool' property on your membertype and add the alias of the property in the 'umbracoLockPropertyTypeAlias' attribute of the membership element in the web.config."); } /// <summary> /// Updates e-mail and potentially approved status, lock status and comment on a user. /// </summary> /// <param name="user">A <see cref="T:System.Web.Security.MembershipUser"></see> object that represents the user to update and the updated information for the user.</param> public override void UpdateUser(MembershipUser user) { var m = Member.GetMemberFromLoginName(user.UserName); if (m == null) { throw new ProviderException(string.Format("No member with the username '{0}' found", user.UserName)); } m.Email = user.Email; // if supported, update approve status UpdateMemberProperty(m, ApprovedPropertyTypeAlias, user.IsApproved ? 1 : 0); // if supported, update lock status UpdateMemberProperty(m, LockPropertyTypeAlias, user.IsLockedOut ? 1 : 0); if (user.IsLockedOut) { UpdateMemberProperty(m, LastLockedOutPropertyTypeAlias, DateTime.Now); } // if supported, update comment UpdateMemberProperty(m, CommentPropertyTypeAlias, user.Comment); m.Save(); } /// <summary> /// Verifies that the specified user name and password exist in the data source. /// </summary> /// <param name="username">The name of the user to validate.</param> /// <param name="password">The password for the specified user.</param> /// <returns> /// true if the specified username and password are valid; otherwise, false. /// </returns> public override bool ValidateUser(string username, string password) { var m = Member.GetMemberFromLoginName(username); if (m == null) return false; var authenticated = CheckPassword(password, m.GetPassword()); if (authenticated) { // check for lock status. If locked, then set the member property to null if (string.IsNullOrEmpty(LockPropertyTypeAlias) == false) { string lockedStatus = GetMemberProperty(m, LockPropertyTypeAlias, true); if (string.IsNullOrEmpty(lockedStatus) == false) { var isLocked = false; if (bool.TryParse(lockedStatus, out isLocked)) { if (isLocked) { LogHelper.Info<UmbracoMembershipProvider>("Cannot validate member " + username + " because they are currently locked out"); return false; } } } } //check for approve status. If not approved, then set the member property to null if (CheckApproveStatus(m) == false) { LogHelper.Info<UmbracoMembershipProvider>("Cannot validate member " + username + " because they are not approved"); return false; } // maybe update login date if (string.IsNullOrEmpty(LastLoginPropertyTypeAlias) == false) { UpdateMemberProperty(m, LastLoginPropertyTypeAlias, DateTime.Now); } // maybe reset password attempts if (string.IsNullOrEmpty(FailedPasswordAttemptsPropertyTypeAlias) == false) { UpdateMemberProperty(m, FailedPasswordAttemptsPropertyTypeAlias, 0); } // persist data //don't raise events for this! It just sets the member dates, if we do raise events this will // cause all distributed cache to execute - which will clear out some caches we don't want. // http://issues.umbraco.org/issue/U4-3451 m.Save(false); return true; } // update fail rate if it's approved if (string.IsNullOrEmpty(LockPropertyTypeAlias) == false && string.IsNullOrEmpty(FailedPasswordAttemptsPropertyTypeAlias) == false) { if (CheckApproveStatus(m)) { var failedAttempts = 0; int.TryParse(GetMemberProperty(m, FailedPasswordAttemptsPropertyTypeAlias, false), out failedAttempts); failedAttempts = failedAttempts + 1; UpdateMemberProperty(m, FailedPasswordAttemptsPropertyTypeAlias, failedAttempts); // lock user? if (failedAttempts >= MaxInvalidPasswordAttempts) { UpdateMemberProperty(m, LockPropertyTypeAlias, 1); UpdateMemberProperty(m, LastLockedOutPropertyTypeAlias, DateTime.Now); LogHelper.Info<UmbracoMembershipProvider>("Member " + username + " is now locked out, max invalid password attempts exceeded"); } //don't raise events for this! It just sets the member dates, if we do raise events this will // cause all distributed cache to execute - which will clear out some caches we don't want. // http://issues.umbraco.org/issue/U4-3451 m.Save(false); } } return false; } private static void UpdateMemberProperty(Member m, string propertyTypeAlias, object propertyValue) { if (string.IsNullOrEmpty(propertyTypeAlias) == false) { if (m.getProperty(propertyTypeAlias) != null) { m.getProperty(propertyTypeAlias).Value = propertyValue; } } } private static string GetMemberProperty(Member m, string propertyTypeAlias, bool isBool) { if (string.IsNullOrEmpty(propertyTypeAlias) == false) { if (m.getProperty(propertyTypeAlias) != null && m.getProperty(propertyTypeAlias).Value != null) { if (isBool) { // Umbraco stored true as 1, which means it can be bool.tryParse'd return m.getProperty(propertyTypeAlias).Value.ToString().Replace("1", "true").Replace("0", "false"); } return m.getProperty(propertyTypeAlias).Value.ToString(); } } return null; } private static string GetMemberProperty(IMember m, string propertyTypeAlias, bool isBool) { if (string.IsNullOrEmpty(propertyTypeAlias) == false) { if (m.Properties.Contains(propertyTypeAlias) && m.Properties[propertyTypeAlias] != null && m.Properties[propertyTypeAlias].Value != null) { if (isBool) { // Umbraco stored true as 1, which means it can be bool.tryParse'd return m.Properties[propertyTypeAlias].Value.ToString().Replace("1", "true").Replace("0", "false"); } return m.Properties[propertyTypeAlias].Value.ToString(); } } return null; } private bool CheckApproveStatus(Member m) { var isApproved = false; if (string.IsNullOrEmpty(ApprovedPropertyTypeAlias) == false) { if (m != null) { var approveStatus = GetMemberProperty(m, ApprovedPropertyTypeAlias, true); if (string.IsNullOrEmpty(approveStatus) == false) { //try parsing as bool first (just in case) if (bool.TryParse(approveStatus, out isApproved) == false) { int intStatus; //if that fails, try parsing as int (since its normally stored as 0 or 1) if (int.TryParse(approveStatus, out intStatus)) { isApproved = intStatus != 0; } } } else { //There is no property so we shouldn't use the approve status isApproved = true; } } } else { // if we don't use approve statuses isApproved = true; } return isApproved; } #endregion #region Helper Methods /// <summary> /// Encodes the password. /// </summary> /// <param name="password">The password.</param> /// <returns>The encoded password.</returns> [Obsolete("Do not use this, it is the legacy way to encode a password - use the base class EncryptOrHashExistingPassword instead")] public string EncodePassword(string password) { return LegacyEncodePassword(password); } /// <summary> /// Unencode password. /// </summary> /// <param name="encodedPassword">The encoded password.</param> /// <returns>The unencoded password.</returns> [Obsolete("Do not use this, it is the legacy way to decode a password - use the base class DecodePassword instead")] public string UnEncodePassword(string encodedPassword) { return LegacyUnEncodePassword(encodedPassword); } /// <summary> /// Converts to membership user. /// </summary> /// <param name="m">The m.</param> /// <returns></returns> private MembershipUser ConvertToMembershipUser(Member m) { if (m == null) return null; var lastLogin = DateTime.Now; var lastLocked = DateTime.MinValue; var isApproved = true; var isLocked = false; var comment = ""; var passwordQuestion = ""; // last login if (string.IsNullOrEmpty(LastLoginPropertyTypeAlias) == false) { DateTime.TryParse(GetMemberProperty(m, LastLoginPropertyTypeAlias, false), out lastLogin); } // approved if (string.IsNullOrEmpty(ApprovedPropertyTypeAlias) == false) { bool.TryParse(GetMemberProperty(m, ApprovedPropertyTypeAlias, true), out isApproved); } // locked if (string.IsNullOrEmpty(LockPropertyTypeAlias) == false) { bool.TryParse(GetMemberProperty(m, LockPropertyTypeAlias, true), out isLocked); } // last locked if (string.IsNullOrEmpty(LastLockedOutPropertyTypeAlias) == false) { DateTime.TryParse(GetMemberProperty(m, LastLockedOutPropertyTypeAlias, false), out lastLocked); } // comment if (string.IsNullOrEmpty(CommentPropertyTypeAlias) == false) { comment = GetMemberProperty(m, CommentPropertyTypeAlias, false); } // password question if (string.IsNullOrEmpty(PasswordRetrievalQuestionPropertyTypeAlias) == false) { passwordQuestion = GetMemberProperty(m, PasswordRetrievalQuestionPropertyTypeAlias, false); } return new MembershipUser(_providerName, m.LoginName, m.Id, m.Email, passwordQuestion, comment, isApproved, isLocked, m.CreateDateTime, lastLogin, DateTime.Now, DateTime.Now, lastLocked); } /// <summary> /// Converts to membership user. /// </summary> /// <param name="m">The m.</param> /// <returns></returns> private MembershipUser ConvertToMembershipUser(IMember m) { if (m == null) return null; var lastLogin = DateTime.Now; var lastLocked = DateTime.MinValue; var isApproved = true; var isLocked = false; var comment = ""; var passwordQuestion = ""; // last login if (string.IsNullOrEmpty(LastLoginPropertyTypeAlias) == false) { DateTime.TryParse(GetMemberProperty(m, LastLoginPropertyTypeAlias, false), out lastLogin); } // approved if (string.IsNullOrEmpty(ApprovedPropertyTypeAlias) == false) { bool.TryParse(GetMemberProperty(m, ApprovedPropertyTypeAlias, true), out isApproved); } // locked if (string.IsNullOrEmpty(LockPropertyTypeAlias) == false) { bool.TryParse(GetMemberProperty(m, LockPropertyTypeAlias, true), out isLocked); } // last locked if (string.IsNullOrEmpty(LastLockedOutPropertyTypeAlias) == false) { DateTime.TryParse(GetMemberProperty(m, LastLockedOutPropertyTypeAlias, false), out lastLocked); } // comment if (string.IsNullOrEmpty(CommentPropertyTypeAlias) == false) { comment = GetMemberProperty(m, CommentPropertyTypeAlias, false); } // password question if (string.IsNullOrEmpty(PasswordRetrievalQuestionPropertyTypeAlias) == false) { passwordQuestion = GetMemberProperty(m, PasswordRetrievalQuestionPropertyTypeAlias, false); } return new MembershipUser(_providerName, m.Username, m.Id, m.Email, passwordQuestion, comment, isApproved, isLocked, m.CreateDate, lastLogin, DateTime.Now, DateTime.Now, lastLocked); } #endregion } }
using System.Collections; using UnityEngine; [RequireComponent(typeof (NavMeshAgent))] public class AICharacterControl : MonoBehaviour { public NavMeshAgent agent { get; private set; } // the navmesh agent required for the path finding public Transform target; // target to aim for public GameObject LHand; public GameObject RHand; private Vector3 steeringDirection; private Vector3 targetPosition; private float speed; private float detectAreaMax; //max detect distance private float detectAreaMin; //min detect distance private float attackIdleArea; //area where enemies wait if not in the front attack row private float detectAreaFlee; //distance where it flees private float RNGtimer; private float RNGtimerSet; private float waitingTimer; private float waitingTimerSet; private float wanderTimer; private float wanderTimerSet; private float attackIdleTimer; private float attackIdleTimerSet; private float circleOffset; private float circleRadius; private int atkRNG; private int listPos; private bool enableWandering; private bool move; private bool runRNG; public bool isWandering; public bool flee; public bool attack; public bool attackExt; public bool hitBoundary; public bool returnToSpawn; public string enemyID; // Use this for initialization private void Start() { target = GameObject.Find ("Sanzus").transform; // get the components on the object we need ( should not be null due to require component so no need to check ) agent = GetComponentInChildren<NavMeshAgent>(); agent.updateRotation = false; agent.updatePosition = true; speed = 5.0f; detectAreaMax = 100f; detectAreaMin = 3f; detectAreaFlee = 120f; attackIdleArea = 20f; RNGtimerSet = 1.0f; RNGtimer = RNGtimerSet; waitingTimerSet = 2.0f; waitingTimer = waitingTimerSet; attackIdleTimerSet = UnityEngine.Random.Range (1.0f, 3.0f); attackIdleTimer = attackIdleTimerSet; attack = false; attackExt = false; flee = false; runRNG = true; enableWandering = true; isWandering = false; hitBoundary = false; returnToSpawn = false; agent.SetDestination (target.position); } // Update is called once per frame private void Update() { if (move) { //print ("move"); transform.LookAt(target); agent.SetDestination (target.position); } else { if (enableWandering) { if (!isWandering) { wander(); } else { if (wanderTimer > 0) { wanderTimer -= Time.deltaTime; } else if (wanderTimer <= 0) { wanderTimer = wanderTimerSet; isWandering = false; } } } else { agent.SetDestination(transform.position+=Vector3.zero); } } var player = GameObject.Find ("Sanzus").GetComponent<ThirdPersonLogic>(); var spawn = GameObject.Find ("Enemy Spawn").GetComponent<EnemySpawner> (); if (target != null) { if ((target.position - transform.position).sqrMagnitude > detectAreaMax) { move = false; //if player is beyond enemy's range, don't chase enableWandering = true; } else { if (player.enemyNo < 3) { if (!attack & !flee & player.enemyRefList.Count < 1) { attack = true; move = true; enableWandering = false; player.enemyNo++; //print ("added enemy, " +player.enemyNo); } } else { if (!attack & !attackExt) { attackExt = true; move = true; enableWandering = false; player.enemyRefList.Add(this.gameObject); PlayerData.enemyList++; listPos = PlayerData.enemyList; gameObject.name = "Enemy" +listPos; enemyID = gameObject.name; } } } } else { move = false; enableWandering = true; } if (spawn.enemyCount <= 1) { LHand.GetComponent<EnemyAttackManager>().canHit = false; RHand.GetComponent<EnemyAttackManager>().canHit = false; if (attack) { attack = false; } if (attackExt) { attackExt = false; } flee = true; if ((target.position - transform.position).sqrMagnitude < detectAreaFlee) { transform.LookAt(target); transform.rotation = Quaternion.Inverse(target.rotation); Vector3 moveDir = transform.position - player.transform.position; transform.position += moveDir.normalized * speed * Time.deltaTime; } else { move = false; flee = false; enableWandering = true; } } if (attack) { if ((target.position - transform.position).sqrMagnitude > detectAreaMax) { player.enemyNo--; if (player.enemyNo < 0) { player.enemyNo = 0; } //print ("minus enemy, " +player.enemyNo); attack = false; move = false; enableWandering = true; LHand.GetComponent<EnemyAttackManager>().canHit = false; RHand.GetComponent<EnemyAttackManager>().canHit = false; } else if ((target.position - transform.position).sqrMagnitude < detectAreaMin){ move = false; enableWandering = false; if (RNGtimer > 0) { if (player.isHit == false) { RNGtimer -= Time.deltaTime; if (attackIdleTimer > 0) { attackIdleTimer -= Time.deltaTime; } if (attackIdleTimer <= 0) { attackIdleShift(); } } } if (RNGtimer <= 0) { runAttackRNG(); } } else { if (player.isHit == true) { move = false; enableWandering = false; } move = true; enableWandering = false; } } if (attackExt) { if ((target.position - transform.position).sqrMagnitude > detectAreaMax && player.enemyRefList.Count > 0) { for (int i =0; i < player.enemyRefList.Count; i++) { if (player.enemyRefList[i].gameObject.name == enemyID) { move = false; enableWandering = true; LHand.GetComponent<EnemyAttackManager>().canHit = false; RHand.GetComponent<EnemyAttackManager>().canHit = false; player.enemyRefList.RemoveAt(i); attackExt = false; } } } else if ((target.position - transform.position).sqrMagnitude < attackIdleArea){ move = false; enableWandering = false; if (waitingTimer > 0) { waitingTimer -= Time.deltaTime; } else if (waitingTimer <= 0) { checkEnemyNo(); } } else { move = true; enableWandering = false; } } if (hitBoundary) { wanderTimer = wanderTimerSet; isWandering = false; turnAround(); } if (returnToSpawn) { if (!attack && !attackExt && !flee) { isWandering = false; returnToArea (); } } } void attackIdleShift() { var direction = UnityEngine.Random.Range (1, 3); if (direction == 1) { targetPosition = new Vector3 (transform.position.x + UnityEngine.Random.Range(1,5), transform.position.y, transform.position.z); } else { targetPosition = new Vector3 (transform.position.x - UnityEngine.Random.Range(1,5), transform.position.y, transform.position.z); agent.SetDestination (targetPosition); } attackIdleTimerSet = UnityEngine.Random.Range (1.0f, 6.0f); attackIdleTimer = attackIdleTimerSet; } void checkEnemyNo() { var player = GameObject.Find ("Sanzus").GetComponent<ThirdPersonLogic>(); if (player.enemyNo < 3 && player.enemyRefList.Count > 0) { var playerAttack = GameObject.Find ("Sanzus").GetComponent<AttackManager>(); if (!playerAttack.enemyUpdateDelay && player.enemyRefList.Count > 0) { //print ("pushed forward, " +player.enemyNo); pushForward(); } } waitingTimer = waitingTimerSet; } void pushForward() { var player = GameObject.Find ("Sanzus").GetComponent<ThirdPersonLogic>(); player.enemyRefList[0].GetComponent<AICharacterControl>().attackExt = false; player.enemyRefList[0].GetComponent<AICharacterControl>().attack = true; player.enemyRefList.RemoveAt (0); player.enemyNo++; } void runAttackRNG() { if (runRNG) { atkRNG = UnityEngine.Random.Range (1, 5); //print ("rng: " + atkRNG); if (atkRNG < 4) { RNGtimer = RNGtimerSet; } if (atkRNG == 4) { //print ("attack"); LHand.GetComponent<EnemyAttackManager>().canHit = true; RHand.GetComponent<EnemyAttackManager>().canHit = true; if (GetComponent<EnemyLogic>().health <= 4) { GetComponent<Animation>().Play("EnemyAttack2"); } else { GetComponent<Animation>().Play("EnemyAttack"); } runRNG = false; RNGtimer = RNGtimerSet; StartCoroutine (resetAttack (3.5f)); } } } void wander () { wanderTimerSet = UnityEngine.Random.Range (1, 5); wanderTimer = wanderTimerSet; circleOffset = 5; circleRadius = UnityEngine.Random.Range (3, 10); Vector3 objPos = new Vector3(transform.position.x + (transform.forward.x*circleOffset), transform.position.y ,transform.position.z + (transform.forward.z*circleOffset)); Vector3 source = Random.insideUnitSphere * circleRadius; targetPosition = new Vector3(source.x + objPos.x, objPos.y, source.z + objPos.z); agent.SetDestination (targetPosition); transform.LookAt (targetPosition); isWandering = true; } void turnAround () { targetPosition = GameObject.Find ("Enemy Spawn").transform.position; agent.SetDestination (targetPosition); transform.LookAt (targetPosition); hitBoundary = false; isWandering = true; } void returnToArea() { print ("returnnnnn"); targetPosition = GameObject.Find ("Enemy Spawn").transform.position; agent.SetDestination (targetPosition); transform.LookAt (targetPosition); } IEnumerator resetAttack (float waitTime) { yield return new WaitForSeconds (waitTime); LHand.GetComponent<EnemyAttackManager>().canHit = false; RHand.GetComponent<EnemyAttackManager>().canHit = false; runRNG = true; } public void SetTarget(Transform target) { this.target = target; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Object is the root class for all CLR objects. This class ** defines only the basics. ** ** ===========================================================*/ namespace System { using System; using System.Diagnostics; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using CultureInfo = System.Globalization.CultureInfo; using FieldInfo = System.Reflection.FieldInfo; using BindingFlags = System.Reflection.BindingFlags; // The Object is the root class for all object in the CLR System. Object // is the super class for all other CLR objects and provide a set of methods and low level // services to subclasses. These services include object synchronization and support for clone // operations. // //This class contains no data and does not need to be serializable [Serializable] [ClassInterface(ClassInterfaceType.AutoDual)] [System.Runtime.InteropServices.ComVisible(true)] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Object { // Creates a new instance of an Object. [System.Runtime.Versioning.NonVersionable] public Object() { } // Returns a String which represents the object instance. The default // for an object is to return the fully qualified name of the class. // public virtual String ToString() { return GetType().ToString(); } // Returns a boolean indicating if the passed in object obj is // Equal to this. Equality is defined as object equality for reference // types and bitwise equality for value types using a loader trick to // replace Equals with EqualsValue for value types). // public virtual bool Equals(Object obj) { return RuntimeHelpers.Equals(this, obj); } public static bool Equals(Object objA, Object objB) { if (objA == objB) { return true; } if (objA == null || objB == null) { return false; } return objA.Equals(objB); } [System.Runtime.Versioning.NonVersionable] public static bool ReferenceEquals(Object objA, Object objB) { return objA == objB; } // GetHashCode is intended to serve as a hash function for this object. // Based on the contents of the object, the hash function will return a suitable // value with a relatively random distribution over the various inputs. // // The default implementation returns the sync block index for this instance. // Calling it on the same object multiple times will return the same value, so // it will technically meet the needs of a hash function, but it's less than ideal. // Objects (& especially value classes) should override this method. // public virtual int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } // Returns a Type object which represent this object instance. // [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern Type GetType(); // Allow an object to free resources before the object is reclaimed by the GC. // [System.Runtime.Versioning.NonVersionable] ~Object() { } // Returns a new object instance that is a memberwise copy of this // object. This is always a shallow copy of the instance. The method is protected // so that other object may only call this method on themselves. It is entended to // support the ICloneable interface. // [MethodImplAttribute(MethodImplOptions.InternalCall)] protected extern Object MemberwiseClone(); // Sets the value specified in the variant on the field // private void FieldSetter(String typeName, String fieldName, Object val) { Debug.Assert(typeName != null); Debug.Assert(fieldName != null); // Extract the field info object FieldInfo fldInfo = GetFieldInfo(typeName, fieldName); if (fldInfo.IsInitOnly) throw new FieldAccessException(SR.FieldAccess_InitOnly); // Make sure that the value is compatible with the type // of field Type pt = fldInfo.FieldType; if (pt.IsByRef) { pt = pt.GetElementType(); } if (!pt.IsInstanceOfType(val)) { val = Convert.ChangeType(val, pt, CultureInfo.InvariantCulture); } // Set the value fldInfo.SetValue(this, val); } // Gets the value specified in the variant on the field // private void FieldGetter(String typeName, String fieldName, ref Object val) { Debug.Assert(typeName != null); Debug.Assert(fieldName != null); // Extract the field info object FieldInfo fldInfo = GetFieldInfo(typeName, fieldName); // Get the value val = fldInfo.GetValue(this); } // Gets the field info object given the type name and field name. // private FieldInfo GetFieldInfo(String typeName, String fieldName) { Debug.Assert(typeName != null); Debug.Assert(fieldName != null); Type t = GetType(); while (null != t) { if (t.FullName.Equals(typeName)) { break; } t = t.BaseType; } if (null == t) { throw new ArgumentException(); } FieldInfo fldInfo = t.GetField(fieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (null == fldInfo) { throw new ArgumentException(); } return fldInfo; } } // Internal methodtable used to instantiate the "canonical" methodtable for generic instantiations. // The name "__Canon" will never been seen by users but it will appear a lot in debugger stack traces // involving generics so it is kept deliberately short as to avoid being a nuisance. [ClassInterface(ClassInterfaceType.AutoDual)] [System.Runtime.InteropServices.ComVisible(true)] internal class __Canon { } // This class is used to define the name of the base class library internal class CoreLib { public const string Name = "System.Private.CoreLib"; public static string FixupCoreLibName(string strToFixup) { if (!String.IsNullOrEmpty(strToFixup)) { strToFixup = strToFixup.Replace("mscorlib", System.CoreLib.Name); } return strToFixup; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.Serialization { using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Xml; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Xml.Serialization; using System.Xml.Schema; using System.Security; using System.Linq; #if uapaot public delegate IXmlSerializable CreateXmlSerializableDelegate(); public sealed class XmlDataContract : DataContract #else internal delegate IXmlSerializable CreateXmlSerializableDelegate(); internal sealed class XmlDataContract : DataContract #endif { private XmlDataContractCriticalHelper _helper; public XmlDataContract() : base(new XmlDataContractCriticalHelper()) { _helper = base.Helper as XmlDataContractCriticalHelper; } internal XmlDataContract(Type type) : base(new XmlDataContractCriticalHelper(type)) { _helper = base.Helper as XmlDataContractCriticalHelper; } public override DataContractDictionary KnownDataContracts { get { return _helper.KnownDataContracts; } set { _helper.KnownDataContracts = value; } } internal XmlSchemaType XsdType { get { return _helper.XsdType; } set { _helper.XsdType = value; } } internal bool IsAnonymous { get { return _helper.IsAnonymous; } } public override bool HasRoot { get { return _helper.HasRoot; } set { _helper.HasRoot = value; } } public override XmlDictionaryString TopLevelElementName { get { return _helper.TopLevelElementName; } set { _helper.TopLevelElementName = value; } } public override XmlDictionaryString TopLevelElementNamespace { get { return _helper.TopLevelElementNamespace; } set { _helper.TopLevelElementNamespace = value; } } #if uapaot private CreateXmlSerializableDelegate _createXmlSerializableDelegate; public CreateXmlSerializableDelegate CreateXmlSerializableDelegate #else internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate #endif { #if !uapaot get { // We create XmlSerializableDelegate via CodeGen when CodeGen is enabled; // otherwise, we would create the delegate via reflection. if (DataContractSerializer.Option == SerializationOption.CodeGenOnly || DataContractSerializer.Option == SerializationOption.ReflectionAsBackup) { if (_helper.CreateXmlSerializableDelegate == null) { lock (this) { if (_helper.CreateXmlSerializableDelegate == null) { CreateXmlSerializableDelegate tempCreateXmlSerializable = GenerateCreateXmlSerializableDelegate(); Interlocked.MemoryBarrier(); _helper.CreateXmlSerializableDelegate = tempCreateXmlSerializable; } } } return _helper.CreateXmlSerializableDelegate; } return () => ReflectionCreateXmlSerializable(this.UnderlyingType); } #else get { if (DataContractSerializer.Option == SerializationOption.CodeGenOnly || (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _createXmlSerializableDelegate != null)) { return _createXmlSerializableDelegate; } return () => ReflectionCreateXmlSerializable(this.UnderlyingType); } set { _createXmlSerializableDelegate = value; } #endif } internal override bool CanContainReferences => false; public override bool IsBuiltInDataContract => UnderlyingType == Globals.TypeOfXmlElement || UnderlyingType == Globals.TypeOfXmlNodeArray; private class XmlDataContractCriticalHelper : DataContract.DataContractCriticalHelper { private DataContractDictionary _knownDataContracts; private bool _isKnownTypeAttributeChecked; private XmlDictionaryString _topLevelElementName; private XmlDictionaryString _topLevelElementNamespace; private bool _hasRoot; private CreateXmlSerializableDelegate _createXmlSerializable; private XmlSchemaType _xsdType; internal XmlDataContractCriticalHelper() { } internal XmlDataContractCriticalHelper(Type type) : base(type) { if (type.IsDefined(Globals.TypeOfDataContractAttribute, false)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveDataContract, DataContract.GetClrTypeFullName(type)))); if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveCollectionDataContract, DataContract.GetClrTypeFullName(type)))); XmlSchemaType xsdType; bool hasRoot; XmlQualifiedName stableName; SchemaExporter.GetXmlTypeInfo(type, out stableName, out xsdType, out hasRoot); this.StableName = stableName; this.HasRoot = hasRoot; XmlDictionary dictionary = new XmlDictionary(); this.Name = dictionary.Add(StableName.Name); this.Namespace = dictionary.Add(StableName.Namespace); object[] xmlRootAttributes = (UnderlyingType == null) ? null : UnderlyingType.GetCustomAttributes(Globals.TypeOfXmlRootAttribute, false).ToArray(); if (xmlRootAttributes == null || xmlRootAttributes.Length == 0) { if (hasRoot) { _topLevelElementName = Name; _topLevelElementNamespace = (this.StableName.Namespace == Globals.SchemaNamespace) ? DictionaryGlobals.EmptyString : Namespace; } } else { if (hasRoot) { XmlRootAttribute xmlRootAttribute = (XmlRootAttribute)xmlRootAttributes[0]; string elementName = xmlRootAttribute.ElementName; _topLevelElementName = (elementName == null || elementName.Length == 0) ? Name : dictionary.Add(DataContract.EncodeLocalName(elementName)); string elementNs = xmlRootAttribute.Namespace; _topLevelElementNamespace = (elementNs == null || elementNs.Length == 0) ? DictionaryGlobals.EmptyString : dictionary.Add(elementNs); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IsAnyCannotHaveXmlRoot, DataContract.GetClrTypeFullName(UnderlyingType)))); } } } internal override DataContractDictionary KnownDataContracts { get { if (!_isKnownTypeAttributeChecked && UnderlyingType != null) { lock (this) { if (!_isKnownTypeAttributeChecked) { _knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType); Interlocked.MemoryBarrier(); _isKnownTypeAttributeChecked = true; } } } return _knownDataContracts; } set { _knownDataContracts = value; } } internal XmlSchemaType XsdType { get { return _xsdType; } set { _xsdType = value; } } internal bool IsAnonymous => _xsdType != null; internal override bool HasRoot { get { return _hasRoot; } set { _hasRoot = value; } } internal override XmlDictionaryString TopLevelElementName { get { return _topLevelElementName; } set { _topLevelElementName = value; } } internal override XmlDictionaryString TopLevelElementNamespace { get { return _topLevelElementNamespace; } set { _topLevelElementNamespace = value; } } internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate { get { return _createXmlSerializable; } set { _createXmlSerializable = value; } } } private ConstructorInfo GetConstructor() { Type type = UnderlyingType; if (type.IsValueType) return null; ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>()); if (ctor == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type)))); return ctor; } #if !uapaot internal CreateXmlSerializableDelegate GenerateCreateXmlSerializableDelegate() { Type type = this.UnderlyingType; CodeGenerator ilg = new CodeGenerator(); bool memberAccessFlag = RequiresMemberAccessForCreate(null) && !(type.FullName == "System.Xml.Linq.XElement"); try { ilg.BeginMethod("Create" + DataContract.GetClrTypeFullName(type), typeof(CreateXmlSerializableDelegate), memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag) { RequiresMemberAccessForCreate(securityException); } else { throw; } } if (type.IsValueType) { System.Reflection.Emit.LocalBuilder local = ilg.DeclareLocal(type, type.Name + "Value"); ilg.Ldloca(local); ilg.InitObj(type); ilg.Ldloc(local); } else { // Special case XElement // codegen the same as 'internal XElement : this("default") { }' ConstructorInfo ctor = GetConstructor(); if (!ctor.IsPublic && type.FullName == "System.Xml.Linq.XElement") { Type xName = type.Assembly.GetType("System.Xml.Linq.XName"); if (xName != null) { MethodInfo XName_op_Implicit = xName.GetMethod( "op_Implicit", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, new Type[] { typeof(String) } ); ConstructorInfo XElement_ctor = type.GetConstructor( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, new Type[] { xName } ); if (XName_op_Implicit != null && XElement_ctor != null) { ilg.Ldstr("default"); ilg.Call(XName_op_Implicit); ctor = XElement_ctor; } } } ilg.New(ctor); } ilg.ConvertValue(this.UnderlyingType, Globals.TypeOfIXmlSerializable); ilg.Ret(); return (CreateXmlSerializableDelegate)ilg.EndMethod(); } /// <SecurityNote> /// Review - calculates whether this Xml type requires MemberAccessPermission for deserialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> private bool RequiresMemberAccessForCreate(SecurityException securityException) { if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format(SR.PartialTrustIXmlSerializableTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (ConstructorRequiresMemberAccess(GetConstructor())) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format(SR.PartialTrustIXmlSerialzableNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } return false; } #endif internal IXmlSerializable ReflectionCreateXmlSerializable(Type type) { if (type.IsValueType) { throw new NotImplementedException("ReflectionCreateXmlSerializable - value type"); } else { object o = null; if (type == typeof(System.Xml.Linq.XElement)) { o = new System.Xml.Linq.XElement("default"); } else { ConstructorInfo ctor = GetConstructor(); o = ctor.Invoke(new object[] { }); } return (IXmlSerializable)o; } } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { if (context == null) XmlObjectSerializerWriteContext.WriteRootIXmlSerializable(xmlWriter, obj); else context.WriteIXmlSerializable(xmlWriter, obj); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { object o; if (context == null) { o = XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, this, true /*isMemberType*/); } else { o = context.ReadIXmlSerializable(xmlReader, this, true /*isMemberType*/); context.AddNewObject(o); } xmlReader.ReadEndElement(); return o; } } }
using System; using System.Linq; using System.Collections.Generic; using Orchard.Caching; using Orchard.Environment.Configuration; using Orchard.Environment.Extensions; using Orchard.Environment.ShellBuilders; using Orchard.Environment.State; using Orchard.Environment.Descriptor; using Orchard.Environment.Descriptor.Models; using Orchard.Localization; using Orchard.Logging; using Orchard.Utility.Extensions; namespace Orchard.Environment { public class DefaultOrchardHost : IOrchardHost, IShellSettingsManagerEventHandler, IShellDescriptorManagerEventHandler { private readonly IHostLocalRestart _hostLocalRestart; private readonly IShellSettingsManager _shellSettingsManager; private readonly IShellContextFactory _shellContextFactory; private readonly IRunningShellTable _runningShellTable; private readonly IProcessingEngine _processingEngine; private readonly IExtensionLoaderCoordinator _extensionLoaderCoordinator; private readonly IExtensionMonitoringCoordinator _extensionMonitoringCoordinator; private readonly ICacheManager _cacheManager; private readonly object _syncLock = new object(); private IEnumerable<ShellContext> _shellContexts; private IEnumerable<ShellSettings> _tenantsToRestart; public DefaultOrchardHost( IShellSettingsManager shellSettingsManager, IShellContextFactory shellContextFactory, IRunningShellTable runningShellTable, IProcessingEngine processingEngine, IExtensionLoaderCoordinator extensionLoaderCoordinator, IExtensionMonitoringCoordinator extensionMonitoringCoordinator, ICacheManager cacheManager, IHostLocalRestart hostLocalRestart ) { _shellSettingsManager = shellSettingsManager; _shellContextFactory = shellContextFactory; _runningShellTable = runningShellTable; _processingEngine = processingEngine; _extensionLoaderCoordinator = extensionLoaderCoordinator; _extensionMonitoringCoordinator = extensionMonitoringCoordinator; _cacheManager = cacheManager; _hostLocalRestart = hostLocalRestart; _tenantsToRestart = Enumerable.Empty<ShellSettings>(); T = NullLocalizer.Instance; Logger = NullLogger.Instance; } public Localizer T { get; set; } public ILogger Logger { get; set; } public IList<ShellContext> Current { get { return BuildCurrent().ToReadOnlyCollection(); } } public ShellContext GetShellContext(ShellSettings shellSettings) { return Current .Single(shellContext => shellContext.Settings.Name.Equals(shellSettings.Name)); } void IOrchardHost.Initialize() { Logger.Information("Initializing"); BuildCurrent(); Logger.Information("Initialized"); } void IOrchardHost.ReloadExtensions() { DisposeShellContext(); } void IOrchardHost.BeginRequest() { Logger.Debug("BeginRequest"); BeginRequest(); } void IOrchardHost.EndRequest() { Logger.Debug("EndRequest"); EndRequest(); } IWorkContextScope IOrchardHost.CreateStandaloneEnvironment(ShellSettings shellSettings) { Logger.Debug("Creating standalone environment for tenant {0}", shellSettings.Name); MonitorExtensions(); BuildCurrent(); var shellContext = CreateShellContext(shellSettings); return shellContext.LifetimeScope.CreateWorkContextScope(); } /// <summary> /// Ensures shells are activated, or re-activated if extensions have changed /// </summary> IEnumerable<ShellContext> BuildCurrent() { if (_shellContexts == null) { lock (_syncLock) { if (_shellContexts == null) { SetupExtensions(); MonitorExtensions(); CreateAndActivateShells(); } } } return _shellContexts; } void StartUpdatedShells() { lock (_syncLock) { if (_tenantsToRestart.Any()) { foreach (var settings in _tenantsToRestart.Distinct().ToList()) { ActivateShell(settings); } _tenantsToRestart = Enumerable.Empty<ShellSettings>(); } } } void CreateAndActivateShells() { Logger.Information("Start creation of shells"); // is there any tenant right now ? var allSettings = _shellSettingsManager.LoadSettings().ToArray(); // load all tenants, and activate their shell if (allSettings.Any()) { foreach (var settings in allSettings) { try { var context = CreateShellContext(settings); ActivateShell(context); } catch(Exception e) { Logger.Error(e, "A tenant could not be started: " + settings.Name); } } } // no settings, run the Setup else { var setupContext = CreateSetupContext(); ActivateShell(setupContext); } Logger.Information("Done creating shells"); } /// <summary> /// Start a Shell and register its settings in RunningShellTable /// </summary> private void ActivateShell(ShellContext context) { Logger.Debug("Activating context for tenant {0}", context.Settings.Name); context.Shell.Activate(); _shellContexts = (_shellContexts ?? Enumerable.Empty<ShellContext>()).Union(new [] {context}); _runningShellTable.Add(context.Settings); } ShellContext CreateSetupContext() { Logger.Debug("Creating shell context for root setup"); return _shellContextFactory.CreateSetupContext(new ShellSettings { Name = ShellSettings.DefaultName }); } ShellContext CreateShellContext(ShellSettings settings) { if (settings.State.CurrentState == TenantState.State.Uninitialized) { Logger.Debug("Creating shell context for tenant {0} setup", settings.Name); return _shellContextFactory.CreateSetupContext(settings); } Logger.Debug("Creating shell context for tenant {0}", settings.Name); return _shellContextFactory.CreateShellContext(settings); } private void SetupExtensions() { _extensionLoaderCoordinator.SetupExtensions(); } private void MonitorExtensions() { // This is a "fake" cache entry to allow the extension loader coordinator // notify us (by resetting _current to "null") when an extension has changed // on disk, and we need to reload new/updated extensions. _cacheManager.Get("OrchardHost_Extensions", ctx => { _extensionMonitoringCoordinator.MonitorExtensions(ctx.Monitor); _hostLocalRestart.Monitor(ctx.Monitor); DisposeShellContext(); return ""; }); } /// <summary> /// Terminates all active shell contexts, and dispose their scope, forcing /// them to be reloaded if necessary. /// </summary> private void DisposeShellContext() { Logger.Information("Disposing active shell contexts"); if (_shellContexts != null) { foreach (var shellContext in _shellContexts) { shellContext.Shell.Terminate(); shellContext.LifetimeScope.Dispose(); } _shellContexts = null; } } protected virtual void BeginRequest() { // Ensure all shell contexts are loaded, or need to be reloaded if // extensions have changed MonitorExtensions(); BuildCurrent(); StartUpdatedShells(); } protected virtual void EndRequest() { // Synchronously process all pending tasks. It's safe to do this at this point // of the pipeline, as the request transaction has been closed, so creating a new // environment and transaction for these tasks will behave as expected.) while (_processingEngine.AreTasksPending()) { _processingEngine.ExecuteNextTask(); } } /// <summary> /// Register and activate a new Shell when a tenant is created /// </summary> void IShellSettingsManagerEventHandler.Saved(ShellSettings settings) { lock (_syncLock) { // if a tenant has been altered, and is not invalid, reload it if (settings.State.CurrentState != TenantState.State.Invalid) { _tenantsToRestart = _tenantsToRestart.Where(x => x.Name != settings.Name).Union(new[] { settings }); } } } void ActivateShell(ShellSettings settings) { // look for the associated shell context var shellContext = _shellContexts.FirstOrDefault(c => c.Settings.Name == settings.Name); // is this is a new tenant ? or is it a tenant waiting for setup ? if (shellContext == null || settings.State.CurrentState == TenantState.State.Uninitialized) { // create the Shell var context = CreateShellContext(settings); // activate the Shell ActivateShell(context); } // reload the shell as its settings have changed else { // dispose previous context shellContext.Shell.Terminate(); shellContext.LifetimeScope.Dispose(); var context = _shellContextFactory.CreateShellContext(settings); // activate and register modified context _shellContexts = _shellContexts.Where(shell => shell.Settings.Name != settings.Name).Union(new[] { context }); context.Shell.Activate(); _runningShellTable.Update(settings); } } /// <summary> /// A feature is enabled/disabled /// </summary> void IShellDescriptorManagerEventHandler.Changed(ShellDescriptor descriptor, string tenant) { lock (_syncLock) { if (_shellContexts == null) { return; } var context =_shellContexts.FirstOrDefault(x => x.Settings.Name == tenant); // some shells might need to be started, e.g. created by command line if(context == null) { StartUpdatedShells(); context = _shellContexts.First(x => x.Settings.Name == tenant); } // don't update the settings themselves here if(_tenantsToRestart.Any(x => x.Name == tenant)) { return; } _tenantsToRestart = _tenantsToRestart.Union(new[] { context.Settings }); } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using System; using System.Globalization; using System.Text; using System.Text.RegularExpressions; using NPOI.SS.Util; namespace NPOI.SS.UserModel { /** * A wrapper around a {@link SimpleDateFormat} instance, * which handles a few Excel-style extensions that * are not supported by {@link SimpleDateFormat}. * Currently, the extensions are around the handling * of elapsed time, eg rendering 1 day 2 hours * as 26 hours. */ public class ExcelStyleDateFormatter : SimpleDateFormat { public const char MMMMM_START_SYMBOL = '\ue001'; public const char MMMMM_TRUNCATE_SYMBOL = '\ue002'; public const char H_BRACKET_SYMBOL = '\ue010'; public const char HH_BRACKET_SYMBOL = '\ue011'; public const char M_BRACKET_SYMBOL = '\ue012'; public const char MM_BRACKET_SYMBOL = '\ue013'; public const char S_BRACKET_SYMBOL = '\ue014'; public const char SS_BRACKET_SYMBOL = '\ue015'; public const char L_BRACKET_SYMBOL = '\ue016'; public const char LL_BRACKET_SYMBOL = '\ue017'; public const char QUOTE_SYMBOL = '\ue009'; //add for C# DateTime format private DecimalFormat format1digit = new DecimalFormat("0"); private DecimalFormat format2digits = new DecimalFormat("00"); private DecimalFormat format3digit = new DecimalFormat("0"); private DecimalFormat format4digits = new DecimalFormat("00"); static ExcelStyleDateFormatter() { //DataFormatter.SetExcelStyleRoundingMode(format1digit, RoundingMode.DOWN); //DataFormatter.SetExcelStyleRoundingMode(format2digits, RoundingMode.DOWN); //DataFormatter.SetExcelStyleRoundingMode(format3digit); //DataFormatter.SetExcelStyleRoundingMode(format4digits); } private double dateToBeFormatted = 0.0; public ExcelStyleDateFormatter() : base() { } public ExcelStyleDateFormatter(String pattern) : base(ProcessFormatPattern(pattern)) { } //public ExcelStyleDateFormatter(String pattern, // DateFormatSymbols formatSymbols) //{ // super(processFormatPattern(pattern), formatSymbols); //} //public ExcelStyleDateFormatter(String pattern, Locale locale) //{ // super(processFormatPattern(pattern), locale); //} private static string DateTimeMatchEvaluator(Match match) { return match.Groups[1].Value; } /** * Takes a format String, and Replaces Excel specific bits * with our detection sequences */ private static String ProcessFormatPattern(String f) { String t = f.Replace("MMMMM", MMMMM_START_SYMBOL + "MMM" + MMMMM_TRUNCATE_SYMBOL); t = Regex.Replace(t, "\\[H\\]", (H_BRACKET_SYMBOL).ToString(), RegexOptions.IgnoreCase); t = Regex.Replace(t, "\\[HH\\]", (HH_BRACKET_SYMBOL).ToString(), RegexOptions.IgnoreCase); t = Regex.Replace(t, "\\[m\\]", (M_BRACKET_SYMBOL).ToString(), RegexOptions.IgnoreCase); t = Regex.Replace(t, "\\[mm\\]", (MM_BRACKET_SYMBOL).ToString(), RegexOptions.IgnoreCase); t = Regex.Replace(t, "\\[s\\]", (S_BRACKET_SYMBOL).ToString(), RegexOptions.IgnoreCase); t = Regex.Replace(t, "\\[ss\\]", (SS_BRACKET_SYMBOL).ToString(), RegexOptions.IgnoreCase); t = t.Replace("s.000", "s.fff"); t = t.Replace("s.00", "s." + LL_BRACKET_SYMBOL); t = t.Replace("s.0", "s." + L_BRACKET_SYMBOL); t = t.Replace("\"", QUOTE_SYMBOL.ToString()); //only one char 'M' //see http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#UsingSingleSpecifiers t = Regex.Replace(t, "(?<![M%])M(?!M)", "%M"); return t; } /** * Used to let us know what the date being * formatted is, in Excel terms, which we * may wish to use when handling elapsed * times. */ public void SetDateToBeFormatted(double date) { this.dateToBeFormatted = date; } public override string Format(object obj, CultureInfo culture) { return this.Format((DateTime)obj, new StringBuilder(), culture).ToString(); } public StringBuilder Format(DateTime date, StringBuilder paramStringBuilder, CultureInfo culture) { // Do the normal format string s = string.Empty; if (Regex.IsMatch(pattern, "[yYmMdDhHsS\\-/,. :\"\\\\]+0?[ampAMP/]*")) { s = date.ToString(pattern, culture); } else s = pattern; if (s.IndexOf(QUOTE_SYMBOL) != -1) { s = s.Replace(QUOTE_SYMBOL, '"'); } // Now handle our special cases if (s.IndexOf(MMMMM_START_SYMBOL) != -1) { Regex reg = new Regex(MMMMM_START_SYMBOL + "(\\w)\\w+" + MMMMM_TRUNCATE_SYMBOL, RegexOptions.IgnoreCase); Match m = reg.Match(s); if (m.Success) { s = reg.Replace(s, m.Groups[1].Value); } } if (s.IndexOf(H_BRACKET_SYMBOL) != -1 || s.IndexOf(HH_BRACKET_SYMBOL) != -1) { double hours = dateToBeFormatted * 24 + 0.01; //get the hour part of the time hours = Math.Floor(hours); s = s.Replace( (H_BRACKET_SYMBOL).ToString(), format1digit.Format(hours, culture) ); s = s.Replace( (HH_BRACKET_SYMBOL).ToString(), format2digits.Format(hours, culture) ); } if (s.IndexOf(M_BRACKET_SYMBOL) != -1 || s.IndexOf(MM_BRACKET_SYMBOL) != -1) { double minutes = dateToBeFormatted * 24 * 60 + 0.01; minutes = Math.Floor(minutes); s = s.Replace( (M_BRACKET_SYMBOL).ToString(), format1digit.Format(minutes, culture) ); s = s.Replace( (MM_BRACKET_SYMBOL).ToString(), format2digits.Format(minutes, culture) ); } if (s.IndexOf(S_BRACKET_SYMBOL) != -1 || s.IndexOf(SS_BRACKET_SYMBOL) != -1) { double seconds = (dateToBeFormatted * 24.0 * 60.0 * 60.0) + 0.01; s = s.Replace( (S_BRACKET_SYMBOL).ToString(), format1digit.Format(seconds, culture) ); s = s.Replace( (SS_BRACKET_SYMBOL).ToString(), format2digits.Format(seconds, culture) ); } if (s.IndexOf(L_BRACKET_SYMBOL) != -1 || s.IndexOf(LL_BRACKET_SYMBOL) != -1) { float millisTemp = (float)((dateToBeFormatted - Math.Floor(dateToBeFormatted)) * 24.0 * 60.0 * 60.0); float millis = (millisTemp - (int)millisTemp); s = s.Replace( (L_BRACKET_SYMBOL).ToString(), format3digit.Format(millis * 10, culture) ); s = s.Replace( (LL_BRACKET_SYMBOL).ToString(), format4digits.Format(millis * 100, culture) ); } return new StringBuilder(s); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Linq; using QuantConnect.Util; using QuantConnect.Logging; using QuantConnect.Packets; using QuantConnect.Algorithm; using QuantConnect.Interfaces; using QuantConnect.Configuration; using System.Collections.Generic; using QuantConnect.AlgorithmFactory; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Brokerages.Backtesting; namespace QuantConnect.Lean.Engine.Setup { /// <summary> /// Backtesting setup handler processes the algorithm initialize method and sets up the internal state of the algorithm class. /// </summary> public class BacktestingSetupHandler : ISetupHandler { /// <summary> /// The worker thread instance the setup handler should use /// </summary> public WorkerThread WorkerThread { get; set; } /// <summary> /// Internal errors list from running the setup procedures. /// </summary> public List<Exception> Errors { get; set; } /// <summary> /// Maximum runtime of the algorithm in seconds. /// </summary> /// <remarks>Maximum runtime is a formula based on the number and resolution of symbols requested, and the days backtesting</remarks> public TimeSpan MaximumRuntime { get; protected set; } /// <summary> /// Starting capital according to the users initialize routine. /// </summary> /// <remarks>Set from the user code.</remarks> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public decimal StartingPortfolioValue { get; protected set; } /// <summary> /// Start date for analysis loops to search for data. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(DateTime)"/> public DateTime StartingDate { get; protected set; } /// <summary> /// Maximum number of orders for this backtest. /// </summary> /// <remarks>To stop algorithm flooding the backtesting system with hundreds of megabytes of order data we limit it to 100 per day</remarks> public int MaxOrders { get; protected set; } /// <summary> /// Initialize the backtest setup handler. /// </summary> public BacktestingSetupHandler() { MaximumRuntime = TimeSpan.FromSeconds(300); Errors = new List<Exception>(); StartingDate = new DateTime(1998, 01, 01); } /// <summary> /// Create a new instance of an algorithm from a physical dll path. /// </summary> /// <param name="assemblyPath">The path to the assembly's location</param> /// <param name="algorithmNodePacket">Details of the task required</param> /// <returns>A new instance of IAlgorithm, or throws an exception if there was an error</returns> public virtual IAlgorithm CreateAlgorithmInstance(AlgorithmNodePacket algorithmNodePacket, string assemblyPath) { string error; IAlgorithm algorithm; var debugNode = algorithmNodePacket as BacktestNodePacket; var debugging = debugNode != null && debugNode.IsDebugging || Config.GetBool("debugging", false); if (debugging && !BaseSetupHandler.InitializeDebugging(algorithmNodePacket, WorkerThread)) { throw new AlgorithmSetupException("Failed to initialize debugging"); } // Limit load times to 90 seconds and force the assembly to have exactly one derived type var loader = new Loader(debugging, algorithmNodePacket.Language, BaseSetupHandler.AlgorithmCreationTimeout, names => names.SingleOrAlgorithmTypeName(Config.Get("algorithm-type-name")), WorkerThread); var complete = loader.TryCreateAlgorithmInstanceWithIsolator(assemblyPath, algorithmNodePacket.RamAllocation, out algorithm, out error); if (!complete) throw new AlgorithmSetupException($"During the algorithm initialization, the following exception has occurred: {error}"); return algorithm; } /// <summary> /// Creates a new <see cref="BacktestingBrokerage"/> instance /// </summary> /// <param name="algorithmNodePacket">Job packet</param> /// <param name="uninitializedAlgorithm">The algorithm instance before Initialize has been called</param> /// <param name="factory">The brokerage factory</param> /// <returns>The brokerage instance, or throws if error creating instance</returns> public IBrokerage CreateBrokerage(AlgorithmNodePacket algorithmNodePacket, IAlgorithm uninitializedAlgorithm, out IBrokerageFactory factory) { factory = new BacktestingBrokerageFactory(); var optionMarketSimulation = new BasicOptionAssignmentSimulation(); return new BacktestingBrokerage(uninitializedAlgorithm, optionMarketSimulation); } /// <summary> /// Setup the algorithm cash, dates and data subscriptions as desired. /// </summary> /// <param name="parameters">The parameters object to use</param> /// <returns>Boolean true on successfully initializing the algorithm</returns> public bool Setup(SetupHandlerParameters parameters) { var algorithm = parameters.Algorithm; var job = parameters.AlgorithmNodePacket as BacktestNodePacket; if (job == null) { throw new ArgumentException("Expected BacktestNodePacket but received " + parameters.AlgorithmNodePacket.GetType().Name); } Log.Trace($"BacktestingSetupHandler.Setup(): Setting up job: UID: {job.UserId.ToStringInvariant()}, " + $"PID: {job.ProjectId.ToStringInvariant()}, Version: {job.Version}, Source: {job.RequestSource}" ); if (algorithm == null) { Errors.Add(new AlgorithmSetupException("Could not create instance of algorithm")); return false; } algorithm.Name = job.GetAlgorithmName(); //Make sure the algorithm start date ok. if (job.PeriodStart == default(DateTime)) { Errors.Add(new AlgorithmSetupException("Algorithm start date was never set")); return false; } var controls = job.Controls; var isolator = new Isolator(); var initializeComplete = isolator.ExecuteWithTimeLimit(TimeSpan.FromMinutes(15), () => { try { parameters.ResultHandler.SendStatusUpdate(AlgorithmStatus.Initializing, "Initializing algorithm..."); //Set our parameters algorithm.SetParameters(job.Parameters); algorithm.SetAvailableDataTypes(BaseSetupHandler.GetConfiguredDataFeeds()); //Algorithm is backtesting, not live: algorithm.SetLiveMode(false); //Set the source impl for the event scheduling algorithm.Schedule.SetEventSchedule(parameters.RealTimeHandler); // set the option chain provider algorithm.SetOptionChainProvider(new CachingOptionChainProvider(new BacktestingOptionChainProvider(parameters.DataProvider))); // set the future chain provider algorithm.SetFutureChainProvider(new CachingFutureChainProvider(new BacktestingFutureChainProvider(parameters.DataProvider))); // set the object store algorithm.SetObjectStore(parameters.ObjectStore); // before we call initialize BaseSetupHandler.LoadBacktestJobAccountCurrency(algorithm, job); //Initialise the algorithm, get the required data: algorithm.Initialize(); // set start and end date if present in the job if (job.PeriodStart.HasValue) { algorithm.SetStartDate(job.PeriodStart.Value); } if (job.PeriodFinish.HasValue) { algorithm.SetEndDate(job.PeriodFinish.Value); } // after we call initialize BaseSetupHandler.LoadBacktestJobCashAmount(algorithm, job); // finalize initialization algorithm.PostInitialize(); } catch (Exception err) { Errors.Add(new AlgorithmSetupException("During the algorithm initialization, the following exception has occurred: ", err)); } }, controls.RamAllocation, sleepIntervalMillis: 100, // entire system is waiting on this, so be as fast as possible workerThread: WorkerThread); if (Errors.Count > 0) { // if we already got an error just exit right away return false; } //Before continuing, detect if this is ready: if (!initializeComplete) return false; MaximumRuntime = TimeSpan.FromMinutes(job.Controls.MaximumRuntimeMinutes); BaseSetupHandler.SetupCurrencyConversions(algorithm, parameters.UniverseSelection); StartingPortfolioValue = algorithm.Portfolio.Cash; // we set the free portfolio value based on the initial total value and the free percentage value algorithm.Settings.FreePortfolioValue = algorithm.Portfolio.TotalPortfolioValue * algorithm.Settings.FreePortfolioValuePercentage; // Get and set maximum orders for this job MaxOrders = job.Controls.BacktestingMaxOrders; algorithm.SetMaximumOrders(MaxOrders); //Starting date of the algorithm: StartingDate = algorithm.StartDate; //Put into log for debugging: Log.Trace("SetUp Backtesting: User: " + job.UserId + " ProjectId: " + job.ProjectId + " AlgoId: " + job.AlgorithmId); Log.Trace($"Dates: Start: {algorithm.StartDate.ToStringInvariant("d")} " + $"End: {algorithm.EndDate.ToStringInvariant("d")} " + $"Cash: {StartingPortfolioValue.ToStringInvariant("C")} " + $"MaximumRuntime: {MaximumRuntime} " + $"MaxOrders: {MaxOrders}"); return initializeComplete; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <filterpriority>2</filterpriority> public void Dispose() { } } // End Result Handler Thread: } // End Namespace
using UnityEngine; using UnityEditor; using System; using System.IO; using System.Xml; using System.Collections; using System.Collections.Generic; using TeamUtility.IO; namespace TeamUtility.Editor.IO.InputManager { public class MappingImportWindow : EditorWindow { [SerializeField] private List<JoystickMapping> _mappings; [SerializeField] private AdvancedInputEditor _configurator; [SerializeField] private Texture2D _highlightTexture; [SerializeField] private Vector2 _mappingListScrollPos = Vector2.zero; [SerializeField] private string _searchString = string.Empty; private const int SELECTION_EMPTY = -1; private List<int> _searchResults; private GUIStyle _whiteLabel; private float _toolbarHeight = 18.0f; private float _searchFieldWidth = 150.0f; private int _selection = SELECTION_EMPTY; private void OnEnable() { if(_mappings == null) { _mappings = new List<JoystickMapping>(); LoadMappings(); } if(_highlightTexture == null) { CreateHighlightTexture(); } if(_searchResults == null) { _searchResults = new List<int>(); } if(_whiteLabel == null) { _whiteLabel = new GUIStyle(EditorStyles.label); _whiteLabel.normal.textColor = Color.white; } } private void LoadMappings() { if(_mappings.Count > 0) _mappings.Clear(); LoadBuiltInMappings(); LoadExternalMappings(); } private void LoadBuiltInMappings() { TextAsset textAsset = Resources.Load<TextAsset>("joystick_mapping_index"); if(textAsset == null) { Debug.LogError("Failed to load built-in joystick mappings. Index file is missing or corrupted."); return; } try { XmlDocument doc = new XmlDocument(); doc.LoadXml(textAsset.text); foreach(XmlNode item in doc.DocumentElement) { JoystickMapping mapping = new JoystickMapping(); mapping.LoadFromResources(item.Attributes["path"].InnerText); if(mapping.AxisCount > 0) { _mappings.Add(mapping); } else { Debug.LogError("Failed to load mapping from Resources folder at path: " + item.Attributes["path"].InnerText); } } } catch(System.Exception ex) { Debug.LogException(ex); Debug.LogError("Failed to load built-in joystick mappings. File format is invalid."); } Resources.UnloadAsset(textAsset); } private void LoadExternalMappings() { string folder = Application.dataPath.Substring(0, Application.dataPath.Length - 6) + "JoystickMappings/"; if(!Directory.Exists(folder)) return; string[] files = Directory.GetFiles(folder, "*.xml"); foreach(string file in files) { JoystickMapping mapping = new JoystickMapping(); mapping.Load(file); if(mapping.AxisCount > 0) { _mappings.Add(mapping); } else { Debug.LogError("Failed to load mapping from: " + file); } } } private void CreateHighlightTexture() { _highlightTexture = new Texture2D(1, 1); _highlightTexture.SetPixel(0, 0, new Color32(50, 125, 255, 255)); _highlightTexture.Apply(); } private void OnDestroy() { Texture2D.DestroyImmediate(_highlightTexture); _highlightTexture = null; } private void OnGUI() { float importButtonHeight = 24.0f; Rect toolbarPosition = new Rect(0.0f, 0.0f, this.position.width, _toolbarHeight); Rect mappingListPosition = new Rect(0.0f, _toolbarHeight, this.position.width, this.position.height - (_toolbarHeight + importButtonHeight + 10.0f)); Rect importButtonPosition = new Rect(this.position.width / 2 - 100.0f, this.position.height - importButtonHeight - 5.0f, 200.0f, importButtonHeight); DisplayMappingList(mappingListPosition); DisplayToolbar(toolbarPosition); GUI.enabled = _selection != SELECTION_EMPTY; if(GUI.Button(importButtonPosition, "Import")) { ImportSelectedMapping(); Close(); } GUI.enabled = true; } private void DisplayMappingList(Rect screenRect) { GUILayout.BeginArea(screenRect); _mappingListScrollPos = EditorGUILayout.BeginScrollView(_mappingListScrollPos); GUILayout.Space(5.0f); if(_searchString.Length > 0) { for(int i = 0; i < _searchResults.Count; i++) { DisplayMapping(screenRect, _searchResults[i]); } } else { for(int i = 0; i < _mappings.Count; i++) { DisplayMapping(screenRect, i); } } GUILayout.Space(5.0f); EditorGUILayout.EndScrollView(); GUILayout.EndArea(); } private void DisplayMapping(Rect screenRect, int index) { Rect configPos = GUILayoutUtility.GetRect(new GUIContent(name), EditorStyles.label, GUILayout.Height(15.0f)); if(Event.current.type == EventType.MouseDown && Event.current.button == 0) { if(configPos.Contains(Event.current.mousePosition)) { _selection = index; Repaint(); } } if(_selection == index) { if(_highlightTexture == null) { CreateHighlightTexture(); } GUI.DrawTexture(configPos, _highlightTexture, ScaleMode.StretchToFill); EditorGUI.LabelField(configPos, _mappings[index].Name, _whiteLabel); } else { EditorGUI.LabelField(configPos, _mappings[index].Name); } } private void DisplayToolbar(Rect screenRect) { Rect searchFieldRect = new Rect(screenRect.width - (_searchFieldWidth + 5.0f), 2.0f, _searchFieldWidth, screenRect.height - 2.0f); int lastSearchStringLength = _searchString.Length; EditorGUI.LabelField(screenRect, "", EditorStyles.toolbarButton); GUILayout.BeginArea(searchFieldRect); _searchString = EditorToolbox.SearchField(_searchString); GUILayout.EndArea(); if(lastSearchStringLength != _searchString.Length) { UpdateSearchResults(); } } private void UpdateSearchResults() { _searchResults.Clear(); for(int i = 0; i < _mappings.Count; i++) { if(_mappings[i].Name.IndexOf(_searchString, System.StringComparison.InvariantCultureIgnoreCase) >= 0) { _searchResults.Add(i); } } _selection = SELECTION_EMPTY; } private void ImportSelectedMapping() { if(_configurator == null) { EditorUtility.DisplayDialog("Error", "Unable to import joystick mapping. Did you close the advanced input editor?", "Close"); return; } InputConfiguration inputConfig = new InputConfiguration(_mappings[_selection].Name.Replace(' ', '_')); foreach(AxisMapping am in _mappings[_selection]) { if(am.ScanType == MappingWizard.ScanType.Button) { AxisConfiguration axisConfig = new AxisConfiguration(am.Name); axisConfig.type = InputType.Button; axisConfig.positive = am.Key; inputConfig.axes.Add(axisConfig); } else { if(am.JoystickAxis < 0 || am.JoystickAxis >= AxisConfiguration.MaxJoystickAxes) { Debug.LogError("Joystick axis is out of range. Cannot import axis configuration: " + am.Name); continue; } AxisConfiguration axisConfig = new AxisConfiguration(am.Name); axisConfig.type = InputType.AnalogAxis; axisConfig.axis = am.JoystickAxis; axisConfig.joystick = 0; axisConfig.deadZone = 0.0f; axisConfig.sensitivity = 1.0f; inputConfig.axes.Add(axisConfig); } } _configurator.AddInputConfiguration(inputConfig); } public static void Open(AdvancedInputEditor configurator) { var window = EditorWindow.GetWindow<MappingImportWindow>("Mapping Importer"); window._configurator = configurator; window.minSize = new Vector2(300.0f, 150.0f); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // OrderPreservingPipeliningSpoolingTask.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Parallel; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace System.Linq.Parallel { class OrderPreservingPipeliningSpoolingTask<TOutput, TKey> : SpoolingTaskBase { private readonly QueryTaskGroupState _taskGroupState; // State shared among tasks. private readonly TaskScheduler _taskScheduler; // The task manager to execute the query. private readonly QueryOperatorEnumerator<TOutput, TKey> _partition; // The source partition. private readonly bool[] _consumerWaiting; // Whether a consumer is waiting on a particular producer private readonly bool[] _producerWaiting; // Whether a particular producer is waiting on the consumer private readonly bool[] _producerDone; // Whether each producer is done private readonly int _partitionIndex; // Index of the partition owned by this task. private readonly Queue<Pair<TKey, TOutput>>[] _buffers; // The buffer for the results private readonly object _bufferLock; // A lock for the buffer /// <summary> /// Whether the producer is allowed to buffer up elements before handing a chunk to the consumer. /// If false, the producer will make each result available to the consumer immediately after it is /// produced. /// </summary> private readonly bool _autoBuffered; /// <summary> /// The number of elements to accumulate on the producer before copying the elements to the /// producer-consumer buffer. This constant is only used in the AutoBuffered mode. /// /// Experimentally, 16 appears to be sufficient buffer size to compensate for the synchronization /// cost. /// </summary> private const int PRODUCER_BUFFER_AUTO_SIZE = 16; /// <summary> /// Constructor /// </summary> internal OrderPreservingPipeliningSpoolingTask( QueryOperatorEnumerator<TOutput, TKey> partition, QueryTaskGroupState taskGroupState, bool[] consumerWaiting, bool[] producerWaiting, bool[] producerDone, int partitionIndex, Queue<Pair<TKey, TOutput>>[] buffers, object bufferLock, TaskScheduler taskScheduler, bool autoBuffered) : base(partitionIndex, taskGroupState) { Debug.Assert(partition != null); Debug.Assert(taskGroupState != null); Debug.Assert(consumerWaiting != null); Debug.Assert(producerWaiting != null && producerWaiting.Length == consumerWaiting.Length); Debug.Assert(producerDone != null && producerDone.Length == consumerWaiting.Length); Debug.Assert(buffers != null && buffers.Length == consumerWaiting.Length); Debug.Assert(partitionIndex >= 0 && partitionIndex < consumerWaiting.Length); _partition = partition; _taskGroupState = taskGroupState; _producerDone = producerDone; _consumerWaiting = consumerWaiting; _producerWaiting = producerWaiting; _partitionIndex = partitionIndex; _buffers = buffers; _bufferLock = bufferLock; _taskScheduler = taskScheduler; _autoBuffered = autoBuffered; } /// <summary> /// This method is responsible for enumerating results and enqueueing them to /// the output buffer as appropriate. Each base class implements its own. /// </summary> protected override void SpoolingWork() { TOutput element = default(TOutput); TKey key = default(TKey); int chunkSize = _autoBuffered ? PRODUCER_BUFFER_AUTO_SIZE : 1; Pair<TKey, TOutput>[] chunk = new Pair<TKey, TOutput>[chunkSize]; var partition = _partition; CancellationToken cancelToken = _taskGroupState.CancellationState.MergedCancellationToken; int lastChunkSize; do { lastChunkSize = 0; while (lastChunkSize < chunkSize && partition.MoveNext(ref element, ref key)) { chunk[lastChunkSize] = new Pair<TKey, TOutput>(key, element); lastChunkSize++; } if (lastChunkSize == 0) break; lock (_bufferLock) { // Check if the query has been cancelled. if (cancelToken.IsCancellationRequested) { break; } for (int i = 0; i < lastChunkSize; i++) { _buffers[_partitionIndex].Enqueue(chunk[i]); } if (_consumerWaiting[_partitionIndex]) { Monitor.Pulse(_bufferLock); _consumerWaiting[_partitionIndex] = false; } // If the producer buffer is too large, wait. // Note: we already checked for cancellation after acquiring the lock on this producer. // That guarantees that the consumer will eventually wake up the producer. if (_buffers[_partitionIndex].Count >= OrderPreservingPipeliningMergeHelper<TOutput, TKey>.MAX_BUFFER_SIZE) { _producerWaiting[_partitionIndex] = true; Monitor.Wait(_bufferLock); } } } while (lastChunkSize == chunkSize); } /// <summary> /// Creates and begins execution of a new set of spooling tasks. /// </summary> public static void Spool( QueryTaskGroupState groupState, PartitionedStream<TOutput, TKey> partitions, bool[] consumerWaiting, bool[] producerWaiting, bool[] producerDone, Queue<Pair<TKey, TOutput>>[] buffers, object[] bufferLocks, TaskScheduler taskScheduler, bool autoBuffered) { Debug.Assert(groupState != null); Debug.Assert(partitions != null); Debug.Assert(producerDone != null && producerDone.Length == partitions.PartitionCount); Debug.Assert(buffers != null && buffers.Length == partitions.PartitionCount); Debug.Assert(bufferLocks != null); int degreeOfParallelism = partitions.PartitionCount; // Initialize the buffers and buffer locks. for (int i = 0; i < degreeOfParallelism; i++) { buffers[i] = new Queue<Pair<TKey, TOutput>>(OrderPreservingPipeliningMergeHelper<TOutput, TKey>.INITIAL_BUFFER_SIZE); bufferLocks[i] = new object(); } // Ensure all tasks in this query are parented under a common root. Because this // is a pipelined query, we detach it from the parent (to avoid blocking the calling // thread), and run the query on a separate thread. Task rootTask = new Task( () => { for (int i = 0; i < degreeOfParallelism; i++) { QueryTask asyncTask = new OrderPreservingPipeliningSpoolingTask<TOutput, TKey>( partitions[i], groupState, consumerWaiting, producerWaiting, producerDone, i, buffers, bufferLocks[i], taskScheduler, autoBuffered); asyncTask.RunAsynchronously(taskScheduler); } }); // Begin the query on the calling thread. groupState.QueryBegin(rootTask); // And schedule it for execution. This is done after beginning to ensure no thread tries to // end the query before its root task has been recorded properly. rootTask.Start(taskScheduler); // We don't call QueryEnd here; when we return, the query is still executing, and the // last enumerator to be disposed of will call QueryEnd for us. } /// <summary> /// Dispose the underlying enumerator and wake up the consumer if necessary. /// </summary> protected override void SpoolingFinally() { // Let the consumer know that this producer is done. lock (_bufferLock) { _producerDone[_partitionIndex] = true; if (_consumerWaiting[_partitionIndex]) { Monitor.Pulse(_bufferLock); _consumerWaiting[_partitionIndex] = false; } } // Call the base implementation. base.SpoolingFinally(); // Dispose of the source enumerator *after* signaling that the task is done. // We call Dispose() last to ensure that if it throws an exception, we will not cause a deadlock. _partition.Dispose(); } } }
using System; using System.Collections; using Axiom.Graphics; using Tao.OpenGl; namespace Axiom.RenderSystems.OpenGL.GLSL { /// <summary> /// Specialisation of HighLevelGpuProgram to provide support for OpenGL /// Shader Language (GLSL). /// </summary> /// <remarks> /// GLSL has no target assembler or entry point specification like DirectX 9 HLSL. /// Vertex and Fragment shaders only have one entry point called "main". /// When a shader is compiled, microcode is generated but can not be accessed by /// the application. /// GLSL also does not provide assembler low level output after compiling. The GL Render /// system assumes that the Gpu program is a GL Gpu program so GLSLProgram will create a /// GLSLGpuProgram that is subclassed from GLGpuProgram for the low level implementation. /// The GLSLProgram class will create a shader object and compile the source but will /// not create a program object. It's up to GLSLGpuProgram class to request a program object /// to link the shader object to. /// <p/> /// GLSL supports multiple modular shader objects that can be attached to one program /// object to form a single shader. This is supported through the "attach" material script /// command. All the modules to be attached are listed on the same line as the attach command /// seperated by white space. /// </remarks> public class GLSLProgram : HighLevelGpuProgram { #region Fields /// <summary> /// The GL id for the program object. /// </summary> protected int glHandle; /// <summary> /// Flag indicating if shader object successfully compiled. /// </summary> protected bool isCompiled; /// <summary> /// Names of shaders attached to this program. /// </summary> protected string attachedShaderNames; /// <summary> /// Holds programs attached to this object. /// </summary> protected ArrayList attachedGLSLPrograms = new ArrayList(); #endregion Fields #region Constructor /// <summary> /// Constructor. /// </summary> public GLSLProgram(string name, GpuProgramType type, string language) : base(name, type, language) { // want scenemanager to pass on surface and light states to the rendersystem // these can be accessed in GLSL passSurfaceAndLightStates = true; // only create a shader object if glsl is supported if(IsSupported) { GLSLHelper.CheckForGLSLError("GL Errors before creating shader object.", 0); // create shader object glHandle = Gl.glCreateShaderObjectARB(type == GpuProgramType.Vertex ? Gl.GL_VERTEX_SHADER_ARB : Gl.GL_FRAGMENT_SHADER_ARB); GLSLHelper.CheckForGLSLError("GL Errors creating shader object.", 0); } } #endregion Constructor #region Properties /// <summary> /// Gets the GL id for the program object. /// </summary> public int GLHandle { get { return glHandle; } } public override int SamplerCount { get { // XXX - hack for now. If we ever use GL, someone will have to fix this. return 8; } } #endregion Properties #region Methods /// <summary> /// Attach another GLSL Shader to this one. /// </summary> /// <param name="name"></param> public void AttachChildShader(string name) { // is the name valid and already loaded? // check with the high level program manager to see if it was loaded HighLevelGpuProgram hlProgram = HighLevelGpuProgramManager.Instance.GetByName(name); if(hlProgram != null) { if(hlProgram.SyntaxCode == "glsl") { // make sure attached program source gets loaded and compiled // don't need a low level implementation for attached shader objects // loadHighLevelImpl will only load the source and compile once // so don't worry about calling it several times GLSLProgram childShader = (GLSLProgram)hlProgram; // load the source and attach the child shader only if supported if(IsSupported) { childShader.LoadHighLevelImpl(); // add to the constainer attachedGLSLPrograms.Add(childShader); attachedShaderNames += name + " "; } } } } /// <summary> /// /// </summary> /// <param name="programObject"></param> public void AttachToProgramObject(int programObject) { Gl.glAttachObjectARB(programObject, glHandle); GLSLHelper.CheckForGLSLError("Error attaching " + this.name + " shader object to GLSL Program Object.", programObject); // atach child objects for(int i = 0; i < attachedGLSLPrograms.Count; i++) { GLSLProgram childShader = (GLSLProgram)attachedGLSLPrograms[i]; // bug in ATI GLSL linker : modules without main function must be recompiled each time // they are linked to a different program object // don't check for compile errors since there won't be any // *** minor inconvenience until ATI fixes there driver childShader.Compile(false); childShader.AttachToProgramObject(programObject); } } /// <summary> /// /// </summary> protected bool Compile() { return Compile(true); } /// <summary> /// /// </summary> /// <param name="checkErrors"></param> protected bool Compile(bool checkErrors) { Gl.glCompileShaderARB(glHandle); int compiled; // check for compile errors Gl.glGetObjectParameterivARB(glHandle, Gl.GL_OBJECT_COMPILE_STATUS_ARB, out compiled); isCompiled = (compiled != 0); // force exception if not compiled if(checkErrors) { GLSLHelper.CheckForGLSLError("Cannot compile GLSL high-level shader: " + name + " ", glHandle, !isCompiled, !isCompiled); if(isCompiled) { GLSLHelper.LogObjectInfo(name + " : GLGL compiled ", glHandle); } } return isCompiled; } #endregion Methods #region HighLevelGpuProgram Implementation protected override void CreateLowLevelImpl() { assemblerProgram = new GLSLGpuProgram(this); } /// <summary> /// /// </summary> protected override void LoadFromSource() { Gl.glShaderSourceARB(glHandle, 1, ref source, null); // check for load errors GLSLHelper.CheckForGLSLError("Cannot load GLGL high-level shader source " + name, 0); Compile(); } /// <summary> /// /// </summary> /// <param name="parms"></param> protected override void PopulateParameterNames(GpuProgramParameters parms) { // can't populate parameter names in GLSL until link time // allow for names read from a material script to be added automatically to the list parms.AutoAddParamName = true; } /// <summary> /// Set a custom param for this high level gpu program. /// </summary> /// <param name="name"></param> /// <param name="val"></param> /// <returns></returns> // TODO: Refactor to command pattern public override bool SetParam(string name, string val) { if(name == "attach") { //get all the shader program names: there could be more than one string[] shaderNames = val.Split(new char[] {' ', '\t'}); // attach the specified shaders to this program for(int i = 0; i < shaderNames.Length; i++) { AttachChildShader(shaderNames[i]); } return true; } return false; } /// <summary> /// /// </summary> protected override void UnloadImpl() { if(IsSupported) { // only delete it if it was supported to being with, else it won't exist Gl.glDeleteObjectARB(glHandle); } // just clearing the reference here assemblerProgram = null; } #endregion HighLevelGpuProgram Implementation } }
// Tree.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2009-October-28 13:29:50> // // ------------------------------------------------------------------ // // This module defines classes for zlib compression and // decompression. This code is derived from the jzlib implementation of // zlib. In keeping with the license for jzlib, the copyright to that // code is below. // // ------------------------------------------------------------------ // // Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the distribution. // // 3. The names of the authors may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, // INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // ----------------------------------------------------------------------- // // This program is based on zlib-1.1.3; credit to authors // Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) // and contributors of zlib. // // ----------------------------------------------------------------------- using System; namespace Ionic2.Zlib { sealed class Tree { private static readonly int HEAP_SIZE = (2 * InternalConstants.L_CODES + 1); // extra bits for each length code internal static readonly int[] ExtraLengthBits = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; // extra bits for each distance code internal static readonly int[] ExtraDistanceBits = new int[] { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; // extra bits for each bit length code internal static readonly int[] extra_blbits = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7}; internal static readonly sbyte[] bl_order = new sbyte[]{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; // The lengths of the bit length codes are sent in order of decreasing // probability, to avoid transmitting the lengths for unused bit // length codes. internal const int Buf_size = 8 * 2; // see definition of array dist_code below //internal const int DIST_CODE_LEN = 512; private static readonly sbyte[] _dist_code = new sbyte[] { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 }; internal static readonly sbyte[] LengthCode = new sbyte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 }; internal static readonly int[] LengthBase = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0 }; internal static readonly int[] DistanceBase = new int[] { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 }; /// <summary> /// Map from a distance to a distance code. /// </summary> /// <remarks> /// No side effects. _dist_code[256] and _dist_code[257] are never used. /// </remarks> internal static int DistanceCode(int dist) { return (dist < 256) ? _dist_code[dist] : _dist_code[256 + SharedUtils.URShift(dist, 7)]; } internal short[] dyn_tree; // the dynamic tree internal int max_code; // largest code with non zero frequency internal StaticTree staticTree; // the corresponding static tree // Compute the optimal bit lengths for a tree and update the total bit length // for the current block. // IN assertion: the fields freq and dad are set, heap[heap_max] and // above are the tree nodes sorted by increasing frequency. // OUT assertions: the field len is set to the optimal bit length, the // array bl_count contains the frequencies for each bit length. // The length opt_len is updated; static_len is also updated if stree is // not null. internal void gen_bitlen(DeflateManager s) { short[] tree = dyn_tree; short[] stree = staticTree.treeCodes; int[] extra = staticTree.extraBits; int base_Renamed = staticTree.extraBase; int max_length = staticTree.maxLength; int h; // heap index int n, m; // iterate over the tree elements int bits; // bit length int xbits; // extra bits short f; // frequency int overflow = 0; // number of elements with bit length too large for (bits = 0; bits <= InternalConstants.MAX_BITS; bits++) s.bl_count[bits] = 0; // In a first pass, compute the optimal bit lengths (which may // overflow in the case of the bit length tree). tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n * 2 + 1] * 2 + 1] + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n * 2 + 1] = (short) bits; // We overwrite tree[n*2+1] which is no longer needed if (n > max_code) continue; // not a leaf node s.bl_count[bits]++; xbits = 0; if (n >= base_Renamed) xbits = extra[n - base_Renamed]; f = tree[n * 2]; s.opt_len += f * (bits + xbits); if (stree != null) s.static_len += f * (stree[n * 2 + 1] + xbits); } if (overflow == 0) return ; // This happens for example on obj2 and pic of the Calgary corpus // Find the first bit length which could increase: do { bits = max_length - 1; while (s.bl_count[bits] == 0) bits--; s.bl_count[bits]--; // move one leaf down the tree s.bl_count[bits + 1] = (short) (s.bl_count[bits + 1] + 2); // move one overflow item as its brother s.bl_count[max_length]--; // The brother of the overflow item also moves one step up, // but this does not affect bl_count[max_length] overflow -= 2; } while (overflow > 0); for (bits = max_length; bits != 0; bits--) { n = s.bl_count[bits]; while (n != 0) { m = s.heap[--h]; if (m > max_code) continue; if (tree[m * 2 + 1] != bits) { s.opt_len = (int) (s.opt_len + ((long) bits - (long) tree[m * 2 + 1]) * (long) tree[m * 2]); tree[m * 2 + 1] = (short) bits; } n--; } } } // Construct one Huffman tree and assigns the code bit strings and lengths. // Update the total bit length for the current block. // IN assertion: the field freq is set for all tree elements. // OUT assertions: the fields len and code are set to the optimal bit length // and corresponding code. The length opt_len is updated; static_len is // also updated if stree is not null. The field max_code is set. internal void build_tree(DeflateManager s) { short[] tree = dyn_tree; short[] stree = staticTree.treeCodes; int elems = staticTree.elems; int n, m; // iterate over heap elements int max_code = -1; // largest code with non zero frequency int node; // new node being created // Construct the initial heap, with least frequent element in // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. // heap[0] is not used. s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2] != 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n * 2 + 1] = 0; } } // The pkzip format requires that at least one distance code exists, // and that at least one bit should be sent even if there is only one // possible code. So to avoid special checks later on we force at least // two codes of non zero frequency. while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2?++max_code:0); tree[node * 2] = 1; s.depth[node] = 0; s.opt_len--; if (stree != null) s.static_len -= stree[node * 2 + 1]; // node is 0 or 1 so it does not have extra bits } this.max_code = max_code; // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, // establish sub-heaps of increasing lengths: for (n = s.heap_len / 2; n >= 1; n--) s.pqdownheap(tree, n); // Construct the Huffman tree by repeatedly combining the least two // frequent nodes. node = elems; // next internal node of the tree do { // n = node of least frequency n = s.heap[1]; s.heap[1] = s.heap[s.heap_len--]; s.pqdownheap(tree, 1); m = s.heap[1]; // m = node of next least frequency s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency s.heap[--s.heap_max] = m; // Create a new node father of n and m tree[node * 2] = unchecked((short) (tree[n * 2] + tree[m * 2])); s.depth[node] = (sbyte) (System.Math.Max((byte) s.depth[n], (byte) s.depth[m]) + 1); tree[n * 2 + 1] = tree[m * 2 + 1] = (short) node; // and insert the new node in the heap s.heap[1] = node++; s.pqdownheap(tree, 1); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1]; // At this point, the fields freq and dad are set. We can now // generate the bit lengths. gen_bitlen(s); // The field len is now set, we can generate the bit codes gen_codes(tree, max_code, s.bl_count); } // Generate the codes for a given tree and bit counts (which need not be // optimal). // IN assertion: the array bl_count contains the bit length statistics for // the given tree and the field len is set for all tree elements. // OUT assertion: the field code is set for all tree elements of non // zero code length. internal static void gen_codes(short[] tree, int max_code, short[] bl_count) { short[] next_code = new short[InternalConstants.MAX_BITS + 1]; // next code value for each bit length short code = 0; // running code value int bits; // bit index int n; // code index // The distribution counts are first used to generate the code values // without bit reversal. for (bits = 1; bits <= InternalConstants.MAX_BITS; bits++) unchecked { next_code[bits] = code = (short) ((code + bl_count[bits - 1]) << 1); } // Check that the bit counts in bl_count are consistent. The last code // must be all ones. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { int len = tree[n * 2 + 1]; if (len == 0) continue; // Now reverse the bits tree[n * 2] = unchecked((short) (bi_reverse(next_code[len]++, len))); } } // Reverse the first len bits of a code, using straightforward code (a faster // method would use a table) // IN assertion: 1 <= len <= 15 internal static int bi_reverse(int code, int len) { int res = 0; do { res |= code & 1; code >>= 1; //SharedUtils.URShift(code, 1); res <<= 1; } while (--len > 0); return res >> 1; } } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; namespace Stream { public class Activity { private const string Field_Id = "id"; private const string Field_Actor = "actor"; private const string Field_Verb = "verb"; private const string Field_Object = "object"; private const string Field_ForeignId = "foreign_id"; private const string Field_To = "to"; private const string Field_Target = "target"; private const string Field_Time = "time"; private const string Field_Activities = "activities"; private const string Field_ActorCount = "actor_count"; private const string Field_IsRead = "is_read"; private const string Field_IsSeen = "is_seen"; private const string Field_CreatedAt = "created_at"; private const string Field_UpdatedAt = "updated_at"; private const string Field_Group = "group"; readonly IDictionary<string, JToken> _data = new Dictionary<string, JToken>(); public string Id { get; set; } public string Actor { get; set; } public string Verb { get; set; } public string Object { get; set; } public string Target { get; set; } public DateTime? Time { get; set; } [JsonProperty("foreign_id")] public string ForeignId { get; set; } public IList<string> To { get; set; } internal static IEnumerable<Activity> GetResults(string json) { JObject obj = JObject.Parse(json); foreach (var prop in obj.Properties()) { if ((prop.Name == "results") || (prop.Name == "activities")) { // get the array var array = prop.Value as JArray; foreach (var val in array) yield return Activity.FromJson((JObject)val); } } } public T GetData<T>(string name) { if (_data.ContainsKey(name)) { var token = _data[name]; // if we are asking for a custom type.. but the JToken is a string if ((!typeof(T).IsBuiltInType()) && (token.Type == JTokenType.String)) { try // to deserialize the string into the object { return JsonConvert.DeserializeObject<T>(token.ToString()); } catch (Exception) { // we'll eat this exception since the next one most likely toss } } return _data[name].ToObject<T>(); } return default(T); } public void SetData<T>(string name, T data) => SetData(name, data, null); public void SetData(IEnumerable<KeyValuePair<string, object>> data) => data.ForEach(x => SetData(x.Key, x.Value, null)); public void SetData<T>(string name, T data, JsonSerializer serializer) { if (serializer != null) _data[name] = JValue.FromObject(data, serializer); else _data[name] = JValue.FromObject(data); } [JsonConstructor] internal Activity() { } public Activity(string actor, string verb, string @object) { Actor = actor; Verb = verb; Object = @object; } internal static string ToActivitiesJson(IEnumerable<Activity> activities, StreamClient client) { var acts = new JArray(from a in activities select a.ToJObject(client)); var obj = new JObject(new JProperty("activities", acts)); return obj.ToString(); } internal string ToJson(StreamClient client) { return ToJObject(client).ToString(); } internal JObject ToJObject(StreamClient client) { JObject obj = new JObject( new JProperty(Field_Actor, this.Actor), new JProperty(Field_Verb, this.Verb), new JProperty(Field_Object, this.Object)); if (Time.HasValue) obj.Add(new JProperty(Field_Time, this.Time.Value.ToString("s", System.Globalization.CultureInfo.InvariantCulture))); if (!string.IsNullOrWhiteSpace(ForeignId)) obj.Add(new JProperty(Field_ForeignId, this.ForeignId)); if (!string.IsNullOrWhiteSpace(Target)) obj.Add(new JProperty(Field_Target, this.Target)); if (To.SafeCount() > 0) { JArray toArray = new JArray(); To.ForEach((st) => { toArray.Add(st); }); obj.Add(new JProperty(Field_To, toArray)); } if (_data.SafeCount() > 0) { _data.Keys.ForEach((k) => { obj.Add(new JProperty(k, _data[k])); }); } return obj; } internal static Activity FromJson(string json) { return FromJson(JObject.Parse(json)); } internal static Activity FromJson(JObject obj) { Activity activity = new Activity(); AggregateActivity aggregateActivity = null; NotificationActivity notificationActivity = null; if (obj.Properties().Any(p => p.Name == Field_Activities)) { if ((obj.Properties().Any(p => p.Name == Field_IsRead)) || (obj.Properties().Any(p => p.Name == Field_IsSeen))) { activity = aggregateActivity = notificationActivity = new NotificationActivity(); } else { activity = aggregateActivity = new AggregateActivity(); } } obj.Properties().ForEach((prop) => { switch (prop.Name) { case Field_Id: activity.Id = prop.Value.Value<string>(); break; case Field_Actor: activity.Actor = prop.Value.Value<string>(); break; case Field_Verb: activity.Verb = prop.Value.Value<string>(); break; case Field_Object: activity.Object = prop.Value.Value<string>(); break; case Field_Target: activity.Target = prop.Value.Value<string>(); break; case Field_ForeignId: activity.ForeignId = prop.Value.Value<string>(); break; case Field_Time: activity.Time = prop.Value.Value<DateTime>(); break; case Field_To: { JArray array = prop.Value as JArray; if ((array != null) && (array.SafeCount() > 0)) { if (array.First.Type == JTokenType.Array) { // need to take the first from each array List<string> tos = new List<string>(); foreach (var child in array) { var str = child.ToObject<string[]>(); tos.Add(str[0]); } activity.To = tos; } else { activity.To = prop.Value.ToObject<string[]>().ToList(); } } else { activity.To = new List<string>(); } break; } case Field_Activities: { var activities = new List<Activity>(); JArray array = prop.Value as JArray; if ((array != null) && (array.SafeCount() > 0)) { foreach (var child in array) { var childJO = child as JObject; if (childJO != null) activities.Add(FromJson(childJO)); } } if (aggregateActivity != null) aggregateActivity.Activities = activities; break; } case Field_ActorCount: { if (aggregateActivity != null) aggregateActivity.ActorCount = prop.Value.Value<int>(); break; } case Field_IsRead: { if (notificationActivity != null) notificationActivity.IsRead = prop.Value.Value<bool>(); break; } case Field_IsSeen: { if (notificationActivity != null) notificationActivity.IsSeen = prop.Value.Value<bool>(); break; } case Field_CreatedAt: { if (aggregateActivity != null) aggregateActivity.CreatedAt = prop.Value.Value<DateTime>(); break; } case Field_UpdatedAt: { if (aggregateActivity != null) aggregateActivity.UpdatedAt = prop.Value.Value<DateTime>(); break; } case Field_Group: { if (aggregateActivity != null) aggregateActivity.Group = prop.Value.Value<string>(); break; } default: { // stash everything else as custom activity._data[prop.Name] = prop.Value; break; }; } }); return activity; } } }
using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Reflection; using bv.common.Core; using System.IO; using System.Linq; using bv.common.Configuration; using System.Windows.Forms; namespace bv.common.Diagnostics { public class Dbg { //private static Regex s_DebugMethodFilterRegexp; //private static bool s_DebugMethodFilterRegexpDefined; private static int m_DefaultDetailLevel; private Dbg() { // NOOP } private static readonly StandardOutput m_StandardOutput = new StandardOutput(); public static DebugFileOutput CreateDebugFileOutput(string fileName) { if (!Utils.IsEmpty(fileName)) { DirectoryInfo dir = Directory.GetParent(Application.CommonAppDataPath); string logfile = dir.FullName + "\\" + fileName; if (IsValidOutputFile(logfile)) return new DebugFileOutput(logfile, false); logfile = Utils.GetExecutingPath() + fileName; if (IsValidOutputFile(logfile)) return new DebugFileOutput(logfile, false); } return null; } private static IDebugOutput CreateDefaultOutputMethod() { // TODO: allow configurable output to log file m_DefaultDetailLevel = BaseSettings.DebugDetailLevel; if (!BaseSettings.DebugOutput) { return null; } if (!Utils.IsEmpty(BaseSettings.DebugLogFile)) { var output = CreateDebugFileOutput(BaseSettings.DebugLogFile); if (output != null) return output; } return m_StandardOutput; } private static bool IsValidOutputFile(string fileName) { try { if (File.Exists(fileName)) { FileAttributes attr = File.GetAttributes(fileName); if ((attr & FileAttributes.ReadOnly) != 0) { attr = attr & (~FileAttributes.ReadOnly); File.SetAttributes(fileName, attr); } FileStream fs = File.OpenWrite(fileName); fs.Close(); } else { FileStream fs = File.Create(fileName); fs.Close(); } return true; } catch (Exception) { return false; } } private static string FormatDataRow(DataRow row) { var @out = (from DataColumn col in row.Table.Columns select string.Format(":{0} <{1}>", col.ColumnName, FormatValue(row[col]))).ToList(); return string.Format("#<DataRow {0}>", Utils.Join(" ", @out)); } public static string FormatValue(object value) { if (value == null) { return "*Nothing*"; } if (value == DBNull.Value) { return "*DBNull*"; } var row = value as DataRow; if (row != null) { return FormatDataRow(row); } var view = value as DataRowView; if (view != null) { return FormatDataRow(view.Row); } return value.ToString(); } private static IDebugOutput m_OutputMethod; public static IDebugOutput OutputMethod { get { if (!Config.IsInitialized) Config.InitSettings(); if (!Config.IsInitialized) return m_StandardOutput; return m_OutputMethod ?? (m_OutputMethod = CreateDefaultOutputMethod()); //Dim result As IDebugOutput = Nothing //If InitSlot() Then // result = CType(Thread.GetData(s_OutputMethodSlot), IDebugOutput) //Else // result = CreateDefaultOutputMethod() // Thread.SetData(s_OutputMethodSlot, result) //End If //Return result } set { m_OutputMethod = value; //InitSlot() //Thread.SetData(s_OutputMethodSlot, value) } } private static void DoDbg(int detailLevel, string fmt, params object[] args) { if (OutputMethod != null) { var trace = new StackTrace(2, true); string methodName = "*UNKNOWN*"; string declaringMethodName = "*UNKNOWN*"; if (trace.GetFrame(0) != null) { MethodBase method = trace.GetFrame(0).GetMethod(); if (method != null) { methodName = method.Name; if (method.DeclaringType != null) declaringMethodName = method.DeclaringType.Name; } } if (ShouldIgnore(detailLevel)) { return; } if (args == null || args.Length == 0) { OutputMethod.WriteLine(string.Format("{0} {1}.{2}(): {3}", DateTime.Now, declaringMethodName, methodName, fmt)); return; } var newArgs = new object[args.Length]; for (int i = 0; i <= args.Length - 1; i++) { newArgs[i] = FormatValue(args[i]); } OutputMethod.WriteLine(string.Format("{0} {1}.{2}(): {3}", DateTime.Now, declaringMethodName, methodName, string.Format(fmt, newArgs))); } } public static void WriteLine(string fmt, params object[] args) { if (OutputMethod != null) { var newArgs = new object[args.Length]; for (int i = 0; i <= args.Length - 1; i++) newArgs[i] = FormatValue(args[i]); OutputMethod.WriteLine(args.Length == 0 ? fmt : string.Format(fmt, newArgs)); } } public static void Debug(string fmt, params object[] args) { DoDbg(0, fmt, args); } public static void ConditionalDebug(int detailLevel, string fmt, params object[] args) { DoDbg(detailLevel, fmt, args); } public static void ConditionalDebug(DebugDetalizationLevel detailLevel, string fmt, params object[] args) { DoDbg((int)detailLevel, fmt, args); } public static void Fail(string fmt, params object[] args) { string message = "Assertion failed: " + string.Format(fmt, args); DoDbg(0, "{0}", message); // TODO: always print failure messages if (Debugger.IsAttached) { Debugger.Break(); } throw (new InternalErrorException(message)); } public static void Assert(bool value, string fmt, params object[] args) { if (!value) { // we duplicate Fail here to make DoDbg work correctly string message = "Assertion failed: " + string.Format(fmt, args); DoDbg(0, "{0}", message); if (Debugger.IsAttached) { Debugger.Break(); } throw (new InternalErrorException(message)); } } public static void DbgAssert(bool value, string fmt, params object[] args) { if (!value) { // we duplicate Fail here to make DoDbg work correctly string message = "Assertion failed: " + string.Format(fmt, args); DoDbg(0, "{0}", message); } } public static void DbgAssert(int detailLevel, bool value, string fmt, params object[] args) { if (!value) { // we duplicate Fail here to make DoDbg work correctly string message = "Assertion failed: " + string.Format(fmt, args); DoDbg(detailLevel, "{0}", message); } } // TODO: probably System.Diagnostics.SymbolStore.* can be used to display extended error information public static void Require(params object[] values) { for (int i = 0; i <= values.Length - 1; i++) { if (values[i] == null) { // we duplicate Fail here to make DoDbg work correctly string message = string.Format("Require: value #{0} (starting from 1) is Nothing", i + 1); DoDbg(0, "{0}", message); if (Debugger.IsAttached) { Debugger.Break(); } throw (new InternalErrorException(message)); } } } private static bool ShouldIgnore(int detailLevel) { return detailLevel > m_DefaultDetailLevel; } public static void Trace(params object[] argValues) { #if TRACE if (OutputMethod == null) { return; } var trace = new StackTrace(1, true); MethodBase method = null; string methodName = "*UNKNOWN*"; string declaringTypeName = "*UNKNOWN*"; if (trace.GetFrame(0) != null) { method = trace.GetFrame(0).GetMethod(); if (method != null) { methodName = method.Name; if (method.DeclaringType != null) declaringTypeName = method.DeclaringType.Name; } } var argStrings = new List<string>(); if (argValues != null && argValues.Length != 0 && method != null) { ParameterInfo[] @params = method.GetParameters(); int numArgs = Math.Min(@params.Length, argValues.Length); for (int i = 0; i <= numArgs - 1; i++) { string valString = FormatValue(argValues[i]); argStrings.Add(string.Format("{0} = <{1}>", @params[i].Name, valString)); } } OutputMethod.WriteLine(string.Format("--> {0}.{1}({2})", declaringTypeName, methodName, Utils.Join(", ", argStrings))); #endif } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using MetroLog; using NUnit.Framework; [TestFixture] public class MetroLogTests { string beforeAssemblyPath; Assembly assembly; public List<string> Errors = new List<string>(); public List<string> Fatals = new List<string>(); public List<string> Debugs = new List<string>(); public List<string> Traces = new List<string>(); public List<string> Information = new List<string>(); public List<string> Warns = new List<string>(); string afterAssemblyPath; public MetroLogTests() { AppDomainAssemblyFinder.Attach(); var configuration = LogManagerFactory.DefaultConfiguration; configuration.IsEnabled = true; beforeAssemblyPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\MetroLogAssemblyToProcess\bin\Debug\MetroLogAssemblyToProcess.dll")); #if (!DEBUG) beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release"); #endif afterAssemblyPath = WeaverHelper.Weave(beforeAssemblyPath); assembly = Assembly.LoadFile(afterAssemblyPath); var target = new ActionTarget { Action = LogEvent }; configuration.AddTarget(LogLevel.Trace, target); configuration.AddTarget(LogLevel.Debug, target); configuration.AddTarget(LogLevel.Warn, target); configuration.AddTarget(LogLevel.Info, target); configuration.AddTarget(LogLevel.Error, target); configuration.AddTarget(LogLevel.Fatal, target); } void LogEvent(LogEventInfo eventInfo) { if (eventInfo.Level == LogLevel.Fatal) { Fatals.Add(eventInfo.Message); return; } if (eventInfo.Level == LogLevel.Error) { Errors.Add(eventInfo.Message); return; } if (eventInfo.Level == LogLevel.Warn) { Warns.Add(eventInfo.Message); return; } if (eventInfo.Level == LogLevel.Info) { Information.Add(eventInfo.Message); return; } if (eventInfo.Level == LogLevel.Debug) { Debugs.Add(eventInfo.Message); return; } if (eventInfo.Level == LogLevel.Trace) { Traces.Add(eventInfo.Message); // ReSharper disable RedundantJumpStatement return; // ReSharper restore RedundantJumpStatement } } [SetUp] public void Setup() { Errors.Clear(); Traces.Clear(); Debugs.Clear(); Information.Clear(); Warns.Clear(); Fatals.Clear(); } [Test] public void ClassWithComplexExpressionInLog() { var type = assembly.GetType("ClassWithComplexExpressionInLog"); var instance = (dynamic) Activator.CreateInstance(type); instance.Method(); Assert.AreEqual(1, Errors.Count); Assert.IsTrue(Errors.First().StartsWith("Method: 'Void Method()'. Line: ~")); } [Test] public void MethodThatReturns() { var type = assembly.GetType("OnException"); var instance = (dynamic) Activator.CreateInstance(type); Assert.AreEqual("a", instance.MethodThatReturns("x", 6)); } [Test] public void Generic() { var type = assembly.GetType("GenericClass`1"); var constructedType = type.MakeGenericType(typeof(string)); var instance = (dynamic) Activator.CreateInstance(constructedType); instance.Debug(); var message = Debugs.First(); Assert.IsTrue(message.StartsWith("Method: 'Void Debug()'. Line: ~")); } [Test] public void ClassWithExistingField() { var type = assembly.GetType("ClassWithExistingField"); Assert.AreEqual(1, type.GetFields(BindingFlags.NonPublic | BindingFlags.Static).Length); var instance = (dynamic) Activator.CreateInstance(type); instance.Debug(); Assert.AreEqual(1, Debugs.Count); Assert.IsTrue(Debugs.First().StartsWith("Method: 'Void Debug()'. Line: ~")); } // ReSharper disable once UnusedParameter.Local void CheckException(Action<object> action, List<string> list, string expected) { Exception exception = null; var type = assembly.GetType("OnException"); var instance = (dynamic) Activator.CreateInstance(type); try { action(instance); } catch (Exception e) { exception = e; } Assert.IsNotNull(exception); Assert.AreEqual(1, list.Count); var first = list.First(); Assert.IsTrue(first.StartsWith(expected), first); } [Test] public void OnExceptionToTrace() { var expected = "Exception occurred in 'Void ToTrace(String, Int32)'. param1 'x' param2 '6'"; Action<dynamic> action = o => o.ToTrace("x", 6); CheckException(action, Traces, expected); } [Test] public void OnExceptionToTraceWithReturn() { var expected = "Exception occurred in 'Object ToTraceWithReturn(String, Int32)'. param1 'x' param2 '6'"; Action<dynamic> action = o => o.ToTraceWithReturn("x", 6); CheckException(action, Traces, expected); } [Test] public void OnExceptionToDebug() { var expected = "Exception occurred in 'Void ToDebug(String, Int32)'. param1 'x' param2 '6'"; Action<dynamic> action = o => o.ToDebug("x", 6); CheckException(action, Debugs, expected); } [Test] public void OnExceptionToDebugWithReturn() { var expected = "Exception occurred in 'Object ToDebugWithReturn(String, Int32)'. param1 'x' param2 '6'"; Action<dynamic> action = o => o.ToDebugWithReturn("x", 6); CheckException(action, Debugs, expected); } [Test] public void OnExceptionToInfo() { var expected = "Exception occurred in 'Void ToInfo(String, Int32)'. param1 'x' param2 '6'"; Action<dynamic> action = o => o.ToInfo("x", 6); CheckException(action, Information, expected); } [Test] public void OnExceptionToInfoWithReturn() { var expected = "Exception occurred in 'Object ToInfoWithReturn(String, Int32)'. param1 'x' param2 '6'"; Action<dynamic> action = o => o.ToInfoWithReturn("x", 6); CheckException(action, Information, expected); } [Test] public void OnExceptionToWarn() { var expected = "Exception occurred in 'Void ToWarn(String, Int32)'. param1 'x' param2 '6'"; Action<dynamic> action = o => o.ToWarn("x", 6); CheckException(action, Warns, expected); } [Test] public void OnExceptionToWarnWithReturn() { var expected = "Exception occurred in 'Object ToWarnWithReturn(String, Int32)'. param1 'x' param2 '6'"; Action<dynamic> action = o => o.ToWarnWithReturn("x", 6); CheckException(action, Warns, expected); } [Test] public void OnExceptionToError() { var expected = "Exception occurred in 'Void ToError(String, Int32)'. param1 'x' param2 '6'"; Action<dynamic> action = o => o.ToError("x", 6); CheckException(action, Errors, expected); } [Test] public void OnExceptionToErrorWithReturn() { var expected = "Exception occurred in 'Object ToErrorWithReturn(String, Int32)'. param1 'x' param2 '6'"; Action<dynamic> action = o => o.ToErrorWithReturn("x", 6); CheckException(action, Errors, expected); } [Test] public void OnExceptionToFatal() { var expected = "Exception occurred in 'Void ToFatal(String, Int32)'. param1 'x' param2 '6'"; Action<dynamic> action = o => o.ToFatal("x", 6); CheckException(action, Fatals, expected); } [Test] public void OnExceptionToFatalWithReturn() { var expected = "Exception occurred in 'Object ToFatalWithReturn(String, Int32)'. param1 'x' param2 '6'"; Action<dynamic> action = o => o.ToFatalWithReturn("x", 6); CheckException(action, Fatals, expected); } [Test] public void IsTraceEnabled() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); Assert.IsTrue(instance.IsTraceEnabled()); } [Test] public void Trace() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.Trace(); Assert.AreEqual(1, Traces.Count); Assert.IsTrue(Traces.First().StartsWith("Method: 'Void Trace()'. Line: ~")); } [Test] public void TraceString() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.TraceString(); Assert.AreEqual(1, Traces.Count); Assert.IsTrue(Traces.First().StartsWith("Method: 'Void TraceString()'. Line: ~")); } [Test] public void TraceStringFunc() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.TraceStringFunc(); Assert.AreEqual(1, Traces.Count); Assert.IsTrue(Traces.First().StartsWith("Method: 'Void TraceStringFunc()'. Line: ~")); } [Test] public void TraceStringParams() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.TraceStringParams(); Assert.AreEqual(1, Traces.Count); Assert.IsTrue(Traces.First().StartsWith("Method: 'Void TraceStringParams()'. Line: ~")); } [Test] public void TraceStringException() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.TraceStringException(); Assert.AreEqual(1, Traces.Count); Assert.IsTrue(Traces.First().StartsWith("Method: 'Void TraceStringException()'. Line: ~")); } [Test] public void TraceStringExceptionFunc() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.TraceStringExceptionFunc(); Assert.AreEqual(1, Traces.Count); Assert.IsTrue(Traces.First().StartsWith("Method: 'Void TraceStringExceptionFunc()'. Line: ~")); } [Test] public void IsDebugEnabled() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); Assert.IsTrue(instance.IsDebugEnabled()); } [Test] public void Debug() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.Debug(); Assert.AreEqual(1, Debugs.Count); Assert.IsTrue(Debugs.First().StartsWith("Method: 'Void Debug()'. Line: ~")); } [Test] public void DebugString() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.DebugString(); Assert.AreEqual(1, Debugs.Count); Assert.IsTrue(Debugs.First().StartsWith("Method: 'Void DebugString()'. Line: ~")); } [Test] public void DebugStringFunc() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.DebugStringFunc(); Assert.AreEqual(1, Debugs.Count); Assert.IsTrue(Debugs.First().StartsWith("Method: 'Void DebugStringFunc()'. Line: ~")); } [Test] public void DebugStringParams() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.DebugStringParams(); Assert.AreEqual(1, Debugs.Count); Assert.IsTrue(Debugs.First().StartsWith("Method: 'Void DebugStringParams()'. Line: ~")); } [Test] public void DebugStringException() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.DebugStringException(); Assert.AreEqual(1, Debugs.Count); Assert.IsTrue(Debugs.First().StartsWith("Method: 'Void DebugStringException()'. Line: ~")); } [Test] public void DebugStringExceptionFunc() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.DebugStringExceptionFunc(); Assert.AreEqual(1, Debugs.Count); Assert.IsTrue(Debugs.First().StartsWith("Method: 'Void DebugStringExceptionFunc()'. Line: ~")); } [Test] public void IsInfoEnabled() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); Assert.IsTrue(instance.IsInfoEnabled()); } [Test] public void Info() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.Info(); Assert.AreEqual(1, Information.Count); Assert.IsTrue(Information.First().StartsWith("Method: 'Void Info()'. Line: ~")); } [Test] public void InfoString() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.InfoString(); Assert.AreEqual(1, Information.Count); Assert.IsTrue(Information.First().StartsWith("Method: 'Void InfoString()'. Line: ~")); } [Test] public void InfoStringFunc() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.InfoStringFunc(); Assert.AreEqual(1, Information.Count); Assert.IsTrue(Information.First().StartsWith("Method: 'Void InfoStringFunc()'. Line: ~")); } [Test] public void InfoStringParams() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.InfoStringParams(); Assert.AreEqual(1, Information.Count); Assert.IsTrue(Information.First().StartsWith("Method: 'Void InfoStringParams()'. Line: ~")); } [Test] public void InfoStringException() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.InfoStringException(); Assert.AreEqual(1, Information.Count); Assert.IsTrue(Information.First().StartsWith("Method: 'Void InfoStringException()'. Line: ~")); } [Test] public void InfoStringExceptionFunc() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.InfoStringExceptionFunc(); Assert.AreEqual(1, Information.Count); Assert.IsTrue(Information.First().StartsWith("Method: 'Void InfoStringExceptionFunc()'. Line: ~")); } [Test] public void IsWarnEnabled() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); Assert.IsTrue(instance.IsWarnEnabled()); } [Test] public void Warn() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.Warn(); Assert.AreEqual(1, Warns.Count); Assert.IsTrue(Warns.First().StartsWith("Method: 'Void Warn()'. Line: ~")); } [Test] public void WarnString() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.WarnString(); Assert.AreEqual(1, Warns.Count); Assert.IsTrue(Warns.First().StartsWith("Method: 'Void WarnString()'. Line: ~")); } [Test] public void WarnStringFunc() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.WarnStringFunc(); Assert.AreEqual(1, Warns.Count); Assert.IsTrue(Warns.First().StartsWith("Method: 'Void WarnStringFunc()'. Line: ~")); } [Test] public void WarnStringParams() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.WarnStringParams(); Assert.AreEqual(1, Warns.Count); Assert.IsTrue(Warns.First().StartsWith("Method: 'Void WarnStringParams()'. Line: ~")); } [Test] public void WarnStringException() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.WarnStringException(); Assert.AreEqual(1, Warns.Count); Assert.IsTrue(Warns.First().StartsWith("Method: 'Void WarnStringException()'. Line: ~")); } [Test] public void WarnStringExceptionFunc() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.WarnStringExceptionFunc(); Assert.AreEqual(1, Warns.Count); Assert.IsTrue(Warns.First().StartsWith("Method: 'Void WarnStringExceptionFunc()'. Line: ~")); } [Test] public void IsErrorEnabled() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); Assert.IsTrue(instance.IsErrorEnabled()); } [Test] public void Error() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.Error(); Assert.AreEqual(1, Errors.Count); Assert.IsTrue(Errors.First().StartsWith("Method: 'Void Error()'. Line: ~")); } [Test] public void ErrorString() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.ErrorString(); Assert.AreEqual(1, Errors.Count); Assert.IsTrue(Errors.First().StartsWith("Method: 'Void ErrorString()'. Line: ~")); } [Test] public void ErrorStringFunc() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.ErrorStringFunc(); Assert.AreEqual(1, Errors.Count); Assert.IsTrue(Errors.First().StartsWith("Method: 'Void ErrorStringFunc()'. Line: ~")); } [Test] public void ErrorStringParams() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.ErrorStringParams(); Assert.AreEqual(1, Errors.Count); Assert.IsTrue(Errors.First().StartsWith("Method: 'Void ErrorStringParams()'. Line: ~")); } [Test] public void ErrorStringException() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.ErrorStringException(); Assert.AreEqual(1, Errors.Count); Assert.IsTrue(Errors.First().StartsWith("Method: 'Void ErrorStringException()'. Line: ~")); } [Test] public void ErrorStringExceptionFunc() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.ErrorStringExceptionFunc(); Assert.AreEqual(1, Errors.Count); Assert.IsTrue(Errors.First().StartsWith("Method: 'Void ErrorStringExceptionFunc()'. Line: ~")); } [Test] public void IsFatalEnabled() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); Assert.IsTrue(instance.IsFatalEnabled()); } [Test] public void Fatal() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.Fatal(); Assert.AreEqual(1, Fatals.Count); Assert.IsTrue(Fatals.First().StartsWith("Method: 'Void Fatal()'. Line: ~")); } [Test] public void FatalString() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.FatalString(); Assert.AreEqual(1, Fatals.Count); Assert.IsTrue(Fatals.First().StartsWith("Method: 'Void FatalString()'. Line: ~")); } [Test] public void FatalStringFunc() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.FatalStringFunc(); Assert.AreEqual(1, Fatals.Count); Assert.IsTrue(Fatals.First().StartsWith("Method: 'Void FatalStringFunc()'. Line: ~")); } [Test] public void FatalStringParams() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.FatalStringParams(); Assert.AreEqual(1, Fatals.Count); Assert.IsTrue(Fatals.First().StartsWith("Method: 'Void FatalStringParams()'. Line: ~")); } [Test] public void FatalStringException() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.FatalStringException(); Assert.AreEqual(1, Fatals.Count); Assert.IsTrue(Fatals.First().StartsWith("Method: 'Void FatalStringException()'. Line: ~")); } [Test] public void FatalStringExceptionFunc() { var type = assembly.GetType("ClassWithLogging"); var instance = (dynamic) Activator.CreateInstance(type); instance.FatalStringExceptionFunc(); Assert.AreEqual(1, Fatals.Count); Assert.IsTrue(Fatals.First().StartsWith("Method: 'Void FatalStringExceptionFunc()'. Line: ~")); } [Test] public void PeVerify() { Verifier.Verify(beforeAssemblyPath, afterAssemblyPath); } [Test] public void AsyncMethod() { var type = assembly.GetType("ClassWithCompilerGeneratedClasses"); var instance = (dynamic) Activator.CreateInstance(type); instance.AsyncMethod(); Assert.AreEqual(1, Debugs.Count); Assert.IsTrue(Debugs.First().StartsWith("Method: 'Void AsyncMethod()'. Line: ~")); } [Test] public void EnumeratorMethod() { var type = assembly.GetType("ClassWithCompilerGeneratedClasses"); var instance = (dynamic) Activator.CreateInstance(type); ((IEnumerable<int>) instance.EnumeratorMethod()).ToList(); Assert.AreEqual(1, Debugs.Count); Assert.IsTrue(Debugs.First().StartsWith("Method: 'IEnumerable<Int32> EnumeratorMethod()'. Line: ~"), Debugs.First()); } [Test] public void DelegateMethod() { var type = assembly.GetType("ClassWithCompilerGeneratedClasses"); var instance = (dynamic) Activator.CreateInstance(type); instance.DelegateMethod(); Assert.AreEqual(1, Debugs.Count); Assert.IsTrue(Debugs.First().StartsWith("Method: 'Void DelegateMethod()'. Line: ~"), Debugs.First()); } [Test] public void AsyncDelegateMethod() { var type = assembly.GetType("ClassWithCompilerGeneratedClasses"); var instance = (dynamic) Activator.CreateInstance(type); instance.AsyncDelegateMethod(); Assert.AreEqual(1, Debugs.Count); Assert.IsTrue(Debugs.First().StartsWith("Method: 'Void AsyncDelegateMethod()'. Line: ~"), Debugs.First()); } [Test] public void LambdaMethod() { var type = assembly.GetType("ClassWithCompilerGeneratedClasses"); var instance = (dynamic) Activator.CreateInstance(type); instance.LambdaMethod(); Assert.AreEqual(1, Debugs.Count); Assert.IsTrue(Debugs.First().StartsWith("Method: 'Void LambdaMethod()'. Line: ~"), Debugs.First()); } [Test] [Explicit("need to fix ref")] public void Issue33() { // We need to load a custom assembly because the C# compiler won't generate the IL // that caused the issue, but NullGuard does. var afterIssue33Path = WeaverHelper.Weave(Path.GetFullPath("NullGuardAnotarBug.dll")); var issue33Assembly = Assembly.LoadFile(afterIssue33Path); var type = issue33Assembly.GetType("NullGuardAnotarBug"); var instance = (dynamic) Activator.CreateInstance(type); Assert.NotNull(instance.DoIt()); } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders { public class LLRAW : ITerrainLoader { public struct HeightmapLookupValue : IComparable<HeightmapLookupValue> { public ushort Index; public float Value; public HeightmapLookupValue(ushort index, float value) { Index = index; Value = value; } public int CompareTo(HeightmapLookupValue val) { return Value.CompareTo(val.Value); } } /// <summary>Lookup table to speed up terrain exports</summary> HeightmapLookupValue[] LookupHeightTable; public LLRAW() { LookupHeightTable = new HeightmapLookupValue[256 * 256]; for (int i = 0; i < 256; i++) { for (int j = 0; j < 256; j++) { LookupHeightTable[i + (j * 256)] = new HeightmapLookupValue((ushort)(i + (j * 256)), (float)((double)i * ((double)j / 128.0d))); } } Array.Sort<HeightmapLookupValue>(LookupHeightTable); } #region ITerrainLoader Members public ITerrainChannel LoadFile(string filename) { FileInfo file = new FileInfo(filename); FileStream s = file.Open(FileMode.Open, FileAccess.Read); ITerrainChannel retval = LoadStream(s); s.Close(); return retval; } public ITerrainChannel LoadFile(string filename, int offsetX, int offsetY, int fileWidth, int fileHeight, int sectionWidth, int sectionHeight) { TerrainChannel retval = new TerrainChannel(sectionWidth, sectionHeight); FileInfo file = new FileInfo(filename); FileStream s = file.Open(FileMode.Open, FileAccess.Read); BinaryReader bs = new BinaryReader(s); int currFileYOffset = fileHeight - 1; // if our region isn't on the first Y section of the areas to be landscaped, then // advance to our section of the file while (currFileYOffset > offsetY) { // read a whole strip of regions int heightsToRead = sectionHeight * (fileWidth * sectionWidth); bs.ReadBytes(heightsToRead * 13); // because there are 13 fun channels currFileYOffset--; } // got to the Y start offset within the file of our region // so read the file bits associated with our region int y; // for each Y within our Y offset for (y = sectionHeight - 1; y >= 0; y--) { int currFileXOffset = 0; // if our region isn't the first X section of the areas to be landscaped, then // advance the stream to the X start pos of our section in the file // i.e. eat X upto where we start while (currFileXOffset < offsetX) { bs.ReadBytes(sectionWidth * 13); currFileXOffset++; } // got to our X offset, so write our regions X line int x; for (x = 0; x < sectionWidth; x++) { // Read a strip and continue retval[x, y] = bs.ReadByte() * (bs.ReadByte() / 128.0); bs.ReadBytes(11); } // record that we wrote it currFileXOffset++; // if our region isn't the last X section of the areas to be landscaped, then // advance the stream to the end of this Y column while (currFileXOffset < fileWidth) { // eat the next regions x line bs.ReadBytes(sectionWidth * 13); //The 13 channels again currFileXOffset++; } } bs.Close(); s.Close(); return retval; } public ITerrainChannel LoadStream(Stream s) { TerrainChannel retval = new TerrainChannel(); BinaryReader bs = new BinaryReader(s); int y; for (y = 0; y < retval.Height; y++) { int x; for (x = 0; x < retval.Width; x++) { retval[x, (retval.Height - 1) - y] = bs.ReadByte() * (bs.ReadByte() / 128.0); bs.ReadBytes(11); // Advance the stream to next bytes. } } bs.Close(); return retval; } public void SaveFile(string filename, ITerrainChannel map) { FileInfo file = new FileInfo(filename); FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write); SaveStream(s, map); s.Close(); } public void SaveStream(Stream s, ITerrainChannel map) { BinaryWriter binStream = new BinaryWriter(s); // Output the calculated raw for (int y = 0; y < map.Height; y++) { for (int x = 0; x < map.Width; x++) { double t = map[x, (map.Height - 1) - y]; //if height is less than 0, set it to 0 as //can't save -ve values in a LLRAW file if (t < 0d) { t = 0d; } int index = 0; // The lookup table is pre-sorted, so we either find an exact match or // the next closest (smaller) match with a binary search index = Array.BinarySearch<HeightmapLookupValue>(LookupHeightTable, new HeightmapLookupValue(0, (float)t)); if (index < 0) index = ~index - 1; index = LookupHeightTable[index].Index; byte red = (byte) (index & 0xFF); byte green = (byte) ((index >> 8) & 0xFF); const byte blue = 20; const byte alpha1 = 0; const byte alpha2 = 0; const byte alpha3 = 0; const byte alpha4 = 0; const byte alpha5 = 255; const byte alpha6 = 255; const byte alpha7 = 255; const byte alpha8 = 255; byte alpha9 = red; byte alpha10 = green; binStream.Write(red); binStream.Write(green); binStream.Write(blue); binStream.Write(alpha1); binStream.Write(alpha2); binStream.Write(alpha3); binStream.Write(alpha4); binStream.Write(alpha5); binStream.Write(alpha6); binStream.Write(alpha7); binStream.Write(alpha8); binStream.Write(alpha9); binStream.Write(alpha10); } } binStream.Close(); } public string FileExtension { get { return ".raw"; } } public virtual void SaveFile(ITerrainChannel m_channel, string filename, int offsetX, int offsetY, int fileWidth, int fileHeight, int regionSizeX, int regionSizeY) { throw new System.Exception("Not Implemented"); } #endregion public override string ToString() { return "LL/SL RAW"; } //Returns true if this extension is supported for terrain save-tile public bool SupportsTileSave() { return false; } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.ComponentModel; // need this for the properties metadata using System.Drawing.Design; using System.Xml; using System.Globalization; using System.Windows.Forms; using System.Windows.Forms.Design; namespace fyiReporting.RdlDesign { /// <summary> /// PropertyAction - /// </summary> [TypeConverter(typeof(PropertyBackgroundConverter)), Editor(typeof(PropertyBackgroundUIEditor), typeof(System.Drawing.Design.UITypeEditor))] internal class PropertyBackground : IReportItem { PropertyReportItem pri; string[] _names; string[] _subitems; internal PropertyBackground(PropertyReportItem ri) { pri = ri; _names = null; _subitems = new string[] { "Style", "" }; } internal PropertyBackground(PropertyReportItem ri, params string[] names) { pri = ri; _names = names; // now build the array used to get/set values _subitems = new string[names.Length + 2]; int i = 0; foreach (string s in names) _subitems[i++] = s; _subitems[i++] = "Style"; } internal PropertyReportItem RI { get { return pri; } } internal string[] Names { get { return _names; } } [RefreshProperties(RefreshProperties.Repaint), TypeConverter(typeof(ColorConverter)), DescriptionAttribute("Background color.")] public string Color { get { return GetStyleValue("BackgroundColor", ""); } set { SetStyleValue("BackgroundColor", value); } } [RefreshProperties(RefreshProperties.Repaint), TypeConverter(typeof(ColorConverter)), DescriptionAttribute("End color when gradient type is not None.")] public string EndColor { get { return GetStyleValue("BackgroundGradientEndColor", ""); } set { SetStyleValue("BackgroundGradientEndColor", value); } } [RefreshProperties(RefreshProperties.Repaint), TypeConverter(typeof(GradientTypeConverter)), DescriptionAttribute("Type of background gradient.")] public string GradientType { get { return GetStyleValue("BackgroundGradientType", "None"); } set { SetStyleValue("BackgroundGradientType", value); } } [DescriptionAttribute("Image to place in the background of the report item")] public PropertyBackgroundImage Image { get { return new PropertyBackgroundImage(pri, _names); } } private string GetStyleValue(string l1, string def) { _subitems[_subitems.Length - 1] = l1; return pri.GetWithList(def, _subitems); } private void SetStyleValue(string l1, string val) { _subitems[_subitems.Length - 1] = l1; pri.SetWithList(val, _subitems); } public override string ToString() { return GetStyleValue("BackgroundColor", ""); } #region IReportItem Members public PropertyReportItem GetPRI() { return pri; } #endregion } internal class PropertyBackgroundConverter : ExpandableObjectConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(PropertyBackground)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is PropertyBackground) { PropertyBackground pf = value as PropertyBackground; return pf.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } internal class PropertyBackgroundUIEditor : UITypeEditor { internal PropertyBackgroundUIEditor() { } public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if ((context == null) || (provider == null)) return base.EditValue(context, provider, value); // Access the Property Browser's UI display service IWindowsFormsEditorService editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (editorService == null) return base.EditValue(context, provider, value); // Create an instance of the UI editor form IReportItem iri = context.Instance as IReportItem; if (iri == null) return base.EditValue(context, provider, value); PropertyReportItem pre = iri.GetPRI(); string[] names; PropertyBackground pb = value as PropertyBackground; if (pb != null) names = pb.Names; else { PropertyBackgroundImage pbi = value as PropertyBackgroundImage; if (pbi == null) return base.EditValue(context, provider, value); names = pbi.Names; } using (SingleCtlDialog scd = new SingleCtlDialog(pre.DesignCtl, pre.Draw, pre.Nodes, SingleCtlTypeEnum.BackgroundCtl, names)) { // Display the UI editor dialog if (editorService.ShowDialog(scd) == DialogResult.OK) { // Return the new property value from the UI editor form return new PropertyBackground(pre); } return base.EditValue(context, provider, value); } } } #region GradientType internal class GradientTypeConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(StaticLists.GradientList); } } #endregion [TypeConverter(typeof(PropertyBackgroundImageConverter)), Editor(typeof(PropertyBackgroundUIEditor), typeof(System.Drawing.Design.UITypeEditor))] internal class PropertyBackgroundImage : IReportItem { PropertyReportItem pri; string[] _names; string[] _subitems; internal PropertyBackgroundImage(PropertyReportItem ri, string[] names) { pri = ri; _names = names; if (names == null) { _subitems = new string[] { "Style", "BackgroundImage", "" }; } else { // now build the array used to get/set values _subitems = new string[names.Length + 3]; int i = 0; foreach (string s in names) _subitems[i++] = s; _subitems[i++] = "Style"; _subitems[i++] = "BackgroundImage"; } } internal string[] Names { get { return _names; } } public override string ToString() { string s = this.Source; string v = ""; if (s.ToLower().Trim() != "none") v = this.Value.Expression; return string.Format("{0} {1}", s, v); } [RefreshProperties(RefreshProperties.Repaint), TypeConverter(typeof(ImageSourceConverter)), DescriptionAttribute("Background Image Source: None, External, Embedded, Database.")] public string Source { get { _subitems[_subitems.Length-1] = "Source"; return pri.GetWithList("None", _subitems); } set { if (value.ToLower().Trim() == "none") { List<string> l = new List<string>(_subitems); l.RemoveAt(l.Count - 1); pri.RemoveWithList(l.ToArray()); } else { _subitems[_subitems.Length - 1] = "Source"; pri.SetWithList(value, _subitems); } } } [RefreshProperties(RefreshProperties.Repaint), DescriptionAttribute("Value depends upon the source of the image.")] public PropertyExpr Value { get { _subitems[_subitems.Length - 1] = "Value"; return new PropertyExpr(pri.GetWithList("", _subitems)); } set { if (this.Source.ToLower().Trim() == "none") throw new ArgumentException("Value isn't relevent when Source=None."); _subitems[_subitems.Length - 1] = "Value"; pri.SetWithList(value.Expression, _subitems); } } [RefreshProperties(RefreshProperties.Repaint), TypeConverter(typeof(ImageMIMETypeConverter)), DescriptionAttribute("When Source is Database MIMEType describes the type of image.")] public string MIMEType { get { _subitems[_subitems.Length - 1] = "MIMEType"; return pri.GetWithList("", _subitems); } set { if (this.Source.ToLower().Trim() != "database") throw new ArgumentException("MIMEType isn't relevent when Source isn't Database."); _subitems[_subitems.Length - 1] = "MIMEType"; pri.SetWithList(value, _subitems); } } [RefreshProperties(RefreshProperties.Repaint), TypeConverter(typeof(ImageRepeatConverter)), DescriptionAttribute("Controls repeating of the background image to fill space.")] public string Repeat { get { _subitems[_subitems.Length - 1] = "BackgroundRepeat"; return pri.GetWithList("Repeat", _subitems); } set { if (this.Source.ToLower().Trim() == "none") throw new ArgumentException("Repeat isn't relevent when Source=None."); _subitems[_subitems.Length - 1] = "BackgroundRepeat"; pri.SetWithList(value, _subitems); } } #region IReportItem Members public PropertyReportItem GetPRI() { return pri; } #endregion } internal class PropertyBackgroundImageConverter : ExpandableObjectConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(PropertyBackgroundImage)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is PropertyBackgroundImage) { PropertyBackgroundImage pf = value as PropertyBackgroundImage; return pf.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } #region ImageSource internal class ImageSourceConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { if (context.Instance is PropertyImageI) return new StandardValuesCollection(new string[] { "External", "Embedded", "Database"}); else return new StandardValuesCollection(new string[] { "None", "External", "Embedded", "Database"}); } } #endregion #region ImageMIMEType internal class ImageMIMETypeConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(new string[] { "image/bmp", "image/jpeg", "image/gif", "image/png","image/x-png"}); } } #endregion #region ImageRepeat internal class ImageRepeatConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(new string[] { "Repeat", "NoRepeat", "RepeatX", "RepeatY"}); } } #endregion }
using System; using System.IO; using Microsoft.DirectX; using D3D = Microsoft.DirectX.Direct3D; namespace Voyage.Terraingine.DXViewport { /// <summary> /// A class to handle creation and usage of DirectX Effects. /// </summary> public class Effect { #region Enumerations /// <summary> /// Enumeration for the allowed effect creation types. /// </summary> public enum CreationType { /// <summary> /// Type for creating an effect file. /// </summary> File, /// <summary> /// Type for creating an effect stream. /// </summary> Stream, /// <summary> /// Type for creating an effect string. /// </summary> String } #endregion #region Data Members private Effect.CreationType _createType; private D3D.Effect _effect; private string _filename; private Stream _stream; private string _sourceData; private D3D.Macro[] _preprocessorDefines; private D3D.Include _includeFile; private D3D.ShaderFlags _flags; private D3D.EffectPool _pool; private string _errors; #endregion #region Properties /// <summary> /// Gets or sets the creation type for the Effect. /// </summary> public Effect.CreationType CreationMethod { get { return _createType; } set { _createType = value; } } /// <summary> /// Gets or sets the DirectX effect. /// </summary> public D3D.Effect DXEffect { get { return _effect; } set { _effect = value; } } /// <summary> /// Gets or sets the name of the Effect file. /// </summary> public string FileName { get { return _filename; } set { _filename = value; } } /// <summary> /// Gets or sets the stream data used for the Effect. /// </summary> public Stream Stream { get { return _stream; } set { _stream = value; } } /// <summary> /// Gets or sets the source data for the Effect. /// </summary> public string SourceData { get { return _sourceData; } set { _sourceData = value; } } /// <summary> /// Gets or sets the array of preprocessor macro definitions used during Effect creation. /// </summary> public D3D.Macro[] PreProcessorDefines { get { return _preprocessorDefines; } set { _preprocessorDefines = value; } } /// <summary> /// Gets or sets the Include object to use for handling #include directives during Effect creation. /// </summary> public D3D.Include IncludeFile { get { return _includeFile; } set { _includeFile = value; } } /// <summary> /// Gets or sets the shader compilation flags used during Effect creation. /// </summary> public D3D.ShaderFlags Flags { get { return _flags; } set { _flags = value; } } /// <summary> /// Gets or sets the EffectPool object to use for shared parameters. /// </summary> public D3D.EffectPool Pool { get { return _pool; } set { _pool = value; } } /// <summary> /// Gets the compilation errors returned during Effect creation. /// </summary> public string Errors { get { return _errors; } } #endregion #region Methods /// <summary> /// Creates the Effect object. /// </summary> public Effect() { _effect = null; Dispose(); } /// <summary> /// Creates a DirectX Effect. /// </summary> /// <param name="device">The DirectX device that creates the effect.</param> /// <returns>Whether the Effect was created.</returns> public bool CreateEffect( D3D.Device device ) { bool result = false; switch ( _createType ) { case Effect.CreationType.File: result = CreateEffectFromFile( device ); break; case Effect.CreationType.Stream: result = CreateEffectFromStream( device ); break; case Effect.CreationType.String: result = CreateEffectFromString( device ); break; } return result; } /// <summary> /// Creates a DirectX Effect from a file. /// </summary> /// <param name="device">The DirectX device that creates the effect.</param> /// <returns>Whether the Effect was created.</returns> public bool CreateEffectFromFile( D3D.Device device ) { bool result = false; if ( _filename != null ) { _effect = D3D.Effect.FromFile( device, _filename, _preprocessorDefines, _includeFile, _flags, _pool, out _errors ); if ( _effect != null ) result = true; } return result; } /// <summary> /// Creates a DirectX Effect from a data stream. /// </summary> /// <param name="device">The DirectX device that creates the effect.</param> /// <returns>Whether the Effect was created.</returns> public bool CreateEffectFromStream( D3D.Device device ) { bool result = false; if ( _stream != null ) { _effect = D3D.Effect.FromStream( device, _stream, _preprocessorDefines, _includeFile, _flags, _pool, out _errors ); if ( _effect != null ) result = true; } return result; } /// <summary> /// Creates a DirectX Effect from a string of source data. /// </summary> /// <param name="device">The DirectX device that creates the effect.</param> /// <returns>Whether the Effect was created.</returns> public bool CreateEffectFromString( D3D.Device device ) { bool result = false; if ( _sourceData != null ) { _effect = D3D.Effect.FromString( device, _sourceData, _preprocessorDefines, _includeFile, _flags, _pool, out _errors ); if ( _effect != null ) result = true; } return result; } /// <summary> /// Checks if the specified technique in the effect is valid. /// </summary> /// <param name="name">The name of the technique to validate.</param> /// <returns>Whether the technique is valid.</returns> public bool ValidateTechnique( string name ) { bool result = false; D3D.EffectHandle technique = _effect.GetTechnique( name ); if ( technique != null ) result = _effect.IsTechniqueValid( technique ); return result; } /// <summary> /// Disposes of the Effect object. /// </summary> public void Dispose() { if ( _effect != null ) { _effect.Dispose(); _effect = null; } _createType = Effect.CreationType.File; _filename = null; _stream = null; _sourceData = null; _preprocessorDefines = null; _includeFile = null; _flags = D3D.ShaderFlags.None; _pool = null; _errors = null; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; using System.Numerics; [assembly: PythonModule("math", typeof(IronPython.Modules.PythonMath))] namespace IronPython.Modules { public static partial class PythonMath { public const string __doc__ = "Provides common mathematical functions."; public const double pi = Math.PI; public const double e = Math.E; private const double degreesToRadians = Math.PI / 180.0; private const int Bias = 0x3FE; public static double degrees(double radians) { return Check(radians, radians / degreesToRadians); } public static double radians(double degrees) { return Check(degrees, degrees * degreesToRadians); } public static double fmod(double v, double w) { return Check(v, w, v % w); } private static double sum(List<double> partials) { // sum the partials the same was as CPython does var n = partials.Count; var hi = 0.0; if (n == 0) return hi; var lo = 0.0; // sum exact while (n > 0) { var x = hi; var y = partials[--n]; hi = x + y; lo = y - (hi - x); if (lo != 0.0) break; } if (n == 0) return hi; // half-even rounding if (lo < 0.0 && partials[n - 1] < 0.0 || lo > 0.0 && partials[n - 1] > 0.0) { var y = lo * 2.0; var x = hi + y; var yr = x - hi; if (y == yr) hi = x; } return hi; } public static double fsum(IEnumerable e) { // msum from https://code.activestate.com/recipes/393090/ var partials = new List<double>(); foreach (var v in e.Cast<object>().Select(o => Converter.ConvertToDouble(o))) { var x = v; var i = 0; for (var j = 0; j < partials.Count; j++) { var y = partials[j]; if (Math.Abs(x) < Math.Abs(y)) { var t = x; x = y; y = t; } var hi = x + y; var lo = y - (hi - x); if (lo != 0) { partials[i++] = lo; } x = hi; } partials.RemoveRange(i, partials.Count - i); partials.Add(x); } return sum(partials); } public static PythonTuple frexp(double v) { if (Double.IsInfinity(v) || Double.IsNaN(v)) { return PythonTuple.MakeTuple(v, 0.0); } int exponent = 0; double mantissa = 0; if (v == 0) { mantissa = 0; exponent = 0; } else { byte[] vb = BitConverter.GetBytes(v); if (BitConverter.IsLittleEndian) { DecomposeLe(vb, out mantissa, out exponent); } else { throw new NotImplementedException(); } } return PythonTuple.MakeTuple(mantissa, exponent); } public static PythonTuple modf(double v) { if (double.IsInfinity(v)) { return PythonTuple.MakeTuple(0.0, v); } double w = v % 1.0; v -= w; return PythonTuple.MakeTuple(w, v); } public static double ldexp(double v, BigInteger w) { if (v == 0.0 || double.IsInfinity(v)) { return v; } return Check(v, v * Math.Pow(2.0, (double)w)); } public static double hypot(double v, double w) { if (double.IsInfinity(v) || double.IsInfinity(w)) { return double.PositiveInfinity; } return Check(v, w, MathUtils.Hypot(v, w)); } public static double pow(double v, double exp) { if (v == 1.0 || exp == 0.0) { return 1.0; } else if (double.IsNaN(v) || double.IsNaN(exp)) { return double.NaN; } else if (v == 0.0) { if (exp > 0.0) { return 0.0; } throw PythonOps.ValueError("math domain error"); } else if (double.IsPositiveInfinity(exp)) { if (v > 1.0 || v < -1.0) { return double.PositiveInfinity; } else if (v == -1.0) { return 1.0; } else { return 0.0; } } else if (double.IsNegativeInfinity(exp)) { if (v > 1.0 || v < -1.0) { return 0.0; } else if (v == -1.0) { return 1.0; } else { return double.PositiveInfinity; } } return Check(v, exp, Math.Pow(v, exp)); } public static double log(double v0) { if (v0 <= 0.0) { throw PythonOps.ValueError("math domain error"); } return Check(v0, Math.Log(v0)); } public static double log(double v0, double v1) { if (v0 <= 0.0 || v1 == 0.0) { throw PythonOps.ValueError("math domain error"); } else if (v1 == 1.0) { throw PythonOps.ZeroDivisionError("float division"); } else if (v1 == Double.PositiveInfinity) { return 0.0; } return Check(Math.Log(v0, v1)); } public static double log(BigInteger value) { if (value.Sign <= 0) { throw PythonOps.ValueError("math domain error"); } return value.Log(); } public static double log(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return log(val); } else { return log(Converter.ConvertToBigInteger(value)); } } public static double log(BigInteger value, double newBase) { if (newBase <= 0.0 || value <= 0) { throw PythonOps.ValueError("math domain error"); } else if (newBase == 1.0) { throw PythonOps.ZeroDivisionError("float division"); } else if (newBase == Double.PositiveInfinity) { return 0.0; } return Check(value.Log(newBase)); } public static double log(object value, double newBase) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return log(val, newBase); } else { return log(Converter.ConvertToBigInteger(value), newBase); } } public static double log10(double v0) { if (v0 <= 0.0) { throw PythonOps.ValueError("math domain error"); } return Check(v0, Math.Log10(v0)); } public static double log10(BigInteger value) { if (value.Sign <= 0) { throw PythonOps.ValueError("math domain error"); } return value.Log10(); } public static double log10(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return log10(val); } else { return log10(Converter.ConvertToBigInteger(value)); } } public static double log1p(double v0) { // Calculate log(1.0 + v0) using William Kahan's algorithm for numerical precision if (double.IsPositiveInfinity(v0)) { return double.PositiveInfinity; } double v1 = v0 + 1.0; // Linear approximation for very small v0 if (v1 == 1.0) { return v0; } // Apply correction factor return log(v1) * v0 / (v1 - 1.0); } public static double log1p(BigInteger value) { return log(value + BigInteger.One); } public static double log1p(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return log1p(val); } else { return log1p(Converter.ConvertToBigInteger(value)); } } public static double expm1(double v0) { return Check(v0, Math.Tanh(v0 / 2.0) * (Math.Exp(v0) + 1.0)); } public static double asinh(double v0) { if (v0 == 0.0 || double.IsInfinity(v0)) { return v0; } // rewrote ln(v0 + sqrt(v0**2 + 1)) for precision if (Math.Abs(v0) > 1.0) { return Math.Sign(v0)*(Math.Log(Math.Abs(v0)) + Math.Log(1.0 + MathUtils.Hypot(1.0, 1.0 / v0))); } else { return Math.Log(v0 + MathUtils.Hypot(1.0, v0)); } } public static double asinh(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return asinh(val); } else { return asinh(Converter.ConvertToBigInteger(value)); } } public static double acosh(double v0) { if (v0 < 1.0) { throw PythonOps.ValueError("math domain error"); } else if (double.IsPositiveInfinity(v0)) { return double.PositiveInfinity; } // rewrote ln(v0 + sqrt(v0**2 - 1)) for precision double c = Math.Sqrt(v0 + 1.0); return Math.Log(c) + Math.Log(v0 / c + Math.Sqrt(v0 - 1.0)); } public static double acosh(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return acosh(val); } else { return acosh(Converter.ConvertToBigInteger(value)); } } public static double atanh(double v0) { if (v0 >= 1.0 || v0 <= -1.0) { throw PythonOps.ValueError("math domain error"); } else if (v0 == 0.0) { // preserve +/-0.0 return v0; } return Math.Log((1.0 + v0) / (1.0 - v0)) * 0.5; } public static double atanh(BigInteger value) { if (value == 0) { return 0; } else { throw PythonOps.ValueError("math domain error"); } } public static double atanh(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return atanh(val); } else { return atanh(Converter.ConvertToBigInteger(value)); } } public static double atan2(double v0, double v1) { if (double.IsNaN(v0) || double.IsNaN(v1)) { return double.NaN; } else if (double.IsInfinity(v0)) { if (double.IsPositiveInfinity(v1)) { return pi * 0.25 * Math.Sign(v0); } else if (double.IsNegativeInfinity(v1)) { return pi * 0.75 * Math.Sign(v0); } else { return pi * 0.5 * Math.Sign(v0); } } else if (double.IsInfinity(v1)) { return v1 > 0.0 ? 0.0 : pi * DoubleOps.Sign(v0); } return Math.Atan2(v0, v1); } /// <summary> /// Error function on real values /// </summary> public static double erf(double v0) { return MathUtils.Erf(v0); } /// <summary> /// Complementary error function on real values: erfc(x) = 1 - erf(x) /// </summary> public static double erfc(double v0) { return MathUtils.ErfComplement(v0); } public static object factorial(double v0) { if (v0 % 1.0 != 0.0) { throw PythonOps.ValueError("factorial() only accepts integral values"); } if (v0 < 0.0) { throw PythonOps.ValueError("factorial() not defined for negative values"); } BigInteger val = 1; for (BigInteger mul = (BigInteger)v0; mul > BigInteger.One; mul -= BigInteger.One) { val *= mul; } if (val > SysModule.maxint) { return val; } return (int)val; } public static object factorial(BigInteger value) { if (value < 0) { throw PythonOps.ValueError("factorial() not defined for negative values"); } BigInteger val = 1; for (BigInteger mul = value; mul > BigInteger.One; mul -= BigInteger.One) { val *= mul; } if (val > SysModule.maxint) { return val; } return (int)val; } public static object factorial(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return factorial(val); } else { return factorial(Converter.ConvertToBigInteger(value)); } } /// <summary> /// Gamma function on real values /// </summary> public static double gamma(double v0) { return Check(v0, MathUtils.Gamma(v0)); } /// <summary> /// Natural log of absolute value of Gamma function /// </summary> public static double lgamma(double v0) { return Check(v0, MathUtils.LogGamma(v0)); } public static object trunc(CodeContext/*!*/ context, object value) { object func; if (PythonOps.TryGetBoundAttr(value, "__trunc__", out func)) { return PythonOps.CallWithContext(context, func); } else { throw PythonOps.AttributeError("__trunc__"); } } public static bool isinf(double v0) { return double.IsInfinity(v0); } public static bool isinf(BigInteger value) { return false; } public static bool isinf(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return isinf(val); } return false; } public static bool isnan(double v0) { return double.IsNaN(v0); } public static bool isnan(BigInteger value) { return false; } public static bool isnan(object value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; if (Converter.TryConvertToDouble(value, out val)) { return isnan(val); } return false; } public static double copysign(double x, double y) { return DoubleOps.CopySign(x, y); } public static double copysign(object x, object y) { double val, sign; if (!Converter.TryConvertToDouble(x, out val) || !Converter.TryConvertToDouble(y, out sign)) { throw PythonOps.TypeError("TypeError: a float is required"); } return DoubleOps.CopySign(val, sign); } #region Private Implementation Details private static void SetExponentLe(byte[] v, int exp) { exp += Bias; ushort oldExp = LdExponentLe(v); ushort newExp = (ushort)(oldExp & 0x800f | (exp << 4)); StExponentLe(v, newExp); } private static int IntExponentLe(byte[] v) { ushort exp = LdExponentLe(v); return ((int)((exp & 0x7FF0) >> 4) - Bias); } private static ushort LdExponentLe(byte[] v) { return (ushort)(v[6] | ((ushort)v[7] << 8)); } private static long LdMantissaLe(byte[] v) { int i1 = (v[0] | (v[1] << 8) | (v[2] << 16) | (v[3] << 24)); int i2 = (v[4] | (v[5] << 8) | ((v[6] & 0xF) << 16)); return i1 | (i2 << 32); } private static void StExponentLe(byte[] v, ushort e) { v[6] = (byte)e; v[7] = (byte)(e >> 8); } private static bool IsDenormalizedLe(byte[] v) { ushort exp = LdExponentLe(v); long man = LdMantissaLe(v); return ((exp & 0x7FF0) == 0 && (man != 0)); } private static void DecomposeLe(byte[] v, out double m, out int e) { if (IsDenormalizedLe(v)) { m = BitConverter.ToDouble(v, 0); m *= Math.Pow(2.0, 1022); v = BitConverter.GetBytes(m); e = IntExponentLe(v) - 1022; } else { e = IntExponentLe(v); } SetExponentLe(v, 0); m = BitConverter.ToDouble(v, 0); } private static double Check(double v) { return PythonOps.CheckMath(v); } private static double Check(double input, double output) { return PythonOps.CheckMath(input, output); } private static double Check(double in0, double in1, double output) { return PythonOps.CheckMath(in0, in1, output); } #endregion } }
namespace Nancy.Testing.Tests { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Collections.ObjectModel; using System.Threading.Tasks; using Nancy.Extensions; using Nancy.Helpers; using Nancy.Session; using Nancy.Tests; using Nancy.Authentication.Forms; using Nancy.Configuration; using Nancy.Tests.xUnitExtensions; using Xunit; using FakeItEasy; public class BrowserFixture { private readonly Browser browser; public BrowserFixture() { var bootstrapper = new ConfigurableBootstrapper(config => config.Modules(typeof(EchoModule))); CookieBasedSessions.Enable(bootstrapper); this.browser = new Browser(bootstrapper); } [Fact] public async Task Should_be_able_to_send_string_in_body() { // Given const string thisIsMyRequestBody = "This is my request body"; // When var result = await browser.Post("/", with => { with.HttpRequest(); with.Body(thisIsMyRequestBody); }); // Then result.Body.AsString().ShouldEqual(thisIsMyRequestBody); } [Fact] public async Task Should_be_able_to_set_user_host_address() { // Given const string userHostAddress = "127.0.0.1"; // When var result = await browser.Get("/userHostAddress", with => { with.HttpRequest(); with.UserHostAddress(userHostAddress); }); // Then result.Body.AsString().ShouldEqual(userHostAddress); } [Fact] public async Task Should_be_able_check_is_local_ipV4() { // Given const string userHostAddress = "127.0.0.1"; // When var result = await browser.Get("/isLocal", with => { with.HttpRequest(); with.HostName("localhost"); with.UserHostAddress(userHostAddress); }); // Then result.Body.AsString().ShouldEqual("local"); } [Fact] public async Task Should_be_able_check_is_local_ipV6() { // Given const string userHostAddress = "::1"; // When var result = await browser.Get("/isLocal", with => { with.HttpRequest(); with.HostName("localhost"); with.UserHostAddress(userHostAddress); }); // Then result.Body.AsString().ShouldEqual("local"); } [Fact] public async Task Should_be_able_check_is_not_local() { // Given const string userHostAddress = "84.12.65.72"; // When var result = await browser.Get("/isLocal", with => { with.HttpRequest(); with.HostName("anotherhost"); with.UserHostAddress(userHostAddress); }); // Then result.Body.AsString().ShouldEqual("not-local"); } [Fact] public async Task Should_be_able_to_send_stream_in_body() { // Given const string thisIsMyRequestBody = "This is my request body"; var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write(thisIsMyRequestBody); writer.Flush(); // When var result = await browser.Post("/", with => { with.HttpRequest(); with.Body(stream, "text/plain"); }); // Then result.Body.AsString().ShouldEqual(thisIsMyRequestBody); } [Fact] public async Task Should_be_able_to_send_json_in_body() { // Given var model = new EchoModel { SomeString = "Some String", SomeInt = 29, SomeBoolean = true }; // When var result = await browser.Post("/", with => { with.JsonBody(model); }); // Then var actualModel = result.Body.DeserializeJson<EchoModel>(); actualModel.ShouldNotBeNull(); actualModel.SomeString.ShouldEqual(model.SomeString); actualModel.SomeInt.ShouldEqual(model.SomeInt); actualModel.SomeBoolean.ShouldEqual(model.SomeBoolean); } [Fact] public async Task Should_be_able_to_send_xml_in_body() { // Given var model = new EchoModel { SomeString = "Some String", SomeInt = 29, SomeBoolean = true }; // When var result = await browser.Post("/", with => { with.XMLBody(model); }); // Then var actualModel = result.Body.DeserializeXml<EchoModel>(); actualModel.ShouldNotBeNull(); actualModel.SomeString.ShouldEqual(model.SomeString); actualModel.SomeInt.ShouldEqual(model.SomeInt); actualModel.SomeBoolean.ShouldEqual(model.SomeBoolean); } [Fact] public void Should_add_basic_authentication_credentials_to_the_headers_of_the_request() { // Given var context = new BrowserContext(A.Fake<INancyEnvironment>()); // When context.BasicAuth("username", "password"); // Then IBrowserContextValues values = context; var credentials = string.Format("{0}:{1}", "username", "password"); var encodedCredentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)); values.Headers["Authorization"].ShouldHaveCount(1); values.Headers["Authorization"].First().ShouldEqual("Basic " + encodedCredentials); } [Fact] public void Should_add_cookies_to_the_request() { // Given var context = new BrowserContext(A.Fake<INancyEnvironment>()); var cookies = new Dictionary<string, string> { { "CookieName", "CookieValue" }, { "SomeCookieName", "SomeCookieValue" } }; // When context.Cookie(cookies); // Then IBrowserContextValues values = context; var cookieString = cookies.Aggregate(string.Empty, (current, cookie) => current + string.Format("{0}={1};", HttpUtility.UrlEncode(cookie.Key), HttpUtility.UrlEncode(cookie.Value))); values.Headers["Cookie"].ShouldHaveCount(1); values.Headers["Cookie"].First().ShouldEqual(cookieString); } [Fact] public void Should_add_cookie_to_the_request() { // Given var context = new BrowserContext(A.Fake<INancyEnvironment>()); var cookies = new Dictionary<string, string> { { "CookieName", "CookieValue" }, { "SomeCookieName", "SomeCookieValue" } }; // When foreach (var cookie in cookies) { context.Cookie(cookie.Key, cookie.Value); } // Then IBrowserContextValues values = context; var cookieString = cookies.Aggregate(string.Empty, (current, cookie) => current + string.Format("{0}={1};", HttpUtility.UrlEncode(cookie.Key), HttpUtility.UrlEncode(cookie.Value))); values.Headers["Cookie"].ShouldHaveCount(1); values.Headers["Cookie"].First().ShouldEqual(cookieString); } [Fact] public async Task Should_add_cookies_to_the_request_and_get_cookies_in_response() { // Given var cookies = new Dictionary<string, string> { { "CookieName", "CookieValue" }, { "SomeCookieName", "SomeCookieValue" } }; // When var result = await browser.Get("/cookie", with => { with.Cookie(cookies); }); // Then result.Cookies.Single(x => x.Name == "CookieName").Value.ShouldEqual("CookieValue"); result.Cookies.Single(x => x.Name == "SomeCookieName").Value.ShouldEqual("SomeCookieValue"); } [Fact] public async Task Should_add_a_cookie_to_the_request_and_get_a_cookie_in_response() { // Given, When var result = await browser.Get("/cookie", with => with.Cookie("CookieName", "CookieValue")); // Then result.Cookies.Single(x => x.Name == "CookieName").Value.ShouldEqual("CookieValue"); } [Fact] public async Task Should_be_able_to_continue_with_another_request() { // Given const string FirstRequestBody = "This is my first request body"; const string SecondRequestBody = "This is my second request body"; var firstRequestStream = new MemoryStream(); var firstRequestWriter = new StreamWriter(firstRequestStream); firstRequestWriter.Write(FirstRequestBody); firstRequestWriter.Flush(); var secondRequestStream = new MemoryStream(); var secondRequestWriter = new StreamWriter(secondRequestStream); secondRequestWriter.Write(SecondRequestBody); secondRequestWriter.Flush(); // When await browser.Post("/", with => { with.HttpRequest(); with.Body(firstRequestStream, "text/plain"); }); var result = await browser.Post("/", with => { with.HttpRequest(); with.Body(secondRequestStream, "text/plain"); }); // Then result.Body.AsString().ShouldEqual(SecondRequestBody); } [Fact] public async Task Should_maintain_cookies_when_chaining_requests() { // Given // When await browser.Get("/session", with => with.HttpRequest()); var result = await this.browser.Get( "/session", with => with.HttpRequest()); //Then result.Body.AsString().ShouldEqual("Current session value is: I've created a session!"); } [Fact] public async Task Should_maintain_cookies_even_if_not_set_on_directly_preceding_request() { // Given // When await browser.Get("/session", with => with.HttpRequest()); await browser.Get("/nothing", with => with.HttpRequest()); var result = await browser.Get("/session", with => with.HttpRequest()); //Then result.Body.AsString().ShouldEqual("Current session value is: I've created a session!"); } [Fact] public async Task Should_be_able_to_not_specify_delegate_for_basic_http_request() { //Given, When var result = await browser.Get("/type"); //Then result.Body.AsString().ShouldEqual("http"); } [Fact] public async Task Should_add_ajax_header() { //Given, When var result = await browser.Get("/ajax", with => with.AjaxRequest()); //Then result.Body.AsString().ShouldEqual("ajax"); } [Fact] public async Task Should_throw_an_exception_when_the_cert_couldnt_be_found() { //Given, When var exception = await RecordAsync.Exception(() => { return browser.Get("/ajax", with => with.Certificate( StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint, "aa aa aa")); }); //Then exception.ShouldBeOfType<InvalidOperationException>(); } [Fact] public async Task Should_add_certificate() { //Given, When var result = await browser.Get("/cert", with => with.Certificate()); //Then result.Context.Request.ClientCertificate.ShouldNotBeNull(); } [Fact] public async Task Should_change_scheme_to_https_when_HttpsRequest_is_called_on_the_context() { //Given, When var result = await browser.Get("/", with => with.HttpsRequest()); //Then result.Context.Request.Url.Scheme.ShouldEqual("https"); } [Fact] public async Task Should_add_forms_authentication_cookie_to_the_request() { //Given var userId = A.Dummy<Guid>(); var formsAuthConfig = new FormsAuthenticationConfiguration() { RedirectUrl = "/login", UserMapper = A.Fake<IUserMapper>(), }; var encryptedId = formsAuthConfig.CryptographyConfiguration.EncryptionProvider.Encrypt(userId.ToString()); var hmacBytes = formsAuthConfig.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedId); var hmacString = Convert.ToBase64String(hmacBytes); var cookieContents = String.Format("{1}{0}", encryptedId, hmacString); //When var response = await browser.Get("/cookie", (with) => { with.HttpRequest(); with.FormsAuth(userId, formsAuthConfig); }); var cookie = response.Cookies.Single(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName); var cookieValue = cookie.Value; //Then cookieValue.ShouldEqual(cookieContents); } [Fact] public async Task Should_return_JSON_serialized_form() { // Given var response = await browser.Post("/serializedform", (with) => { with.HttpRequest(); with.Accept("application/json"); with.FormValue("SomeString", "Hi"); with.FormValue("SomeInt", "1"); with.FormValue("SomeBoolean", "true"); }); // When var actualModel = response.Body.DeserializeJson<EchoModel>(); // Then Assert.Equal("Hi", actualModel.SomeString); Assert.Equal(1, actualModel.SomeInt); Assert.Equal(true, actualModel.SomeBoolean); } [Fact] public async Task Should_return_JSON_serialized_querystring() { // Given var response = await browser.Get("/serializedquerystring", (with) => { with.HttpRequest(); with.Accept("application/json"); with.Query("SomeString", "Hi"); with.Query("SomeInt", "1"); with.Query("SomeBoolean", "true"); }); // When var actualModel = response.Body.DeserializeJson<EchoModel>(); // Then Assert.Equal("Hi", actualModel.SomeString); Assert.Equal(1, actualModel.SomeInt); Assert.Equal(true, actualModel.SomeBoolean); } [Fact] public async Task Should_encode_form() { //Given, When var result = await browser.Post("/encoded", with => { with.HttpRequest(); with.FormValue("name", "john++"); }); //Then result.Body.AsString().ShouldEqual("john++"); } [Fact] public async Task Should_encode_querystring() { //Given, When var result = await browser.Post("/encodedquerystring", with => { with.HttpRequest(); with.Query("name", "john++"); }); //Then result.Body.AsString().ShouldEqual("john++"); } [Fact] public async Task Should_add_nancy_testing_browser_header_as_default_user_agent() { // Given const string expectedHeaderValue = "Nancy.Testing.Browser"; // When var result = (await browser.Get("/useragent")).Body.AsString(); // Then result.ShouldEqual(expectedHeaderValue); } [Fact] public async Task Should_override_default_user_agent_when_explicitly_defined() { // Given const string expectedHeaderValue = "Custom.User.Agent"; // When var result = await browser.Get("/useragent", with => { with.Header("User-Agent", expectedHeaderValue); }); var header = result.Body.AsString(); // Then header.ShouldEqual(expectedHeaderValue); } [Theory] [InlineData("application/xml")] public async Task Should_return_error_message_on_cyclical_exception(string accept) { //Given var browser = new Browser(with => { with.Modules(typeof(EchoModule)); with.Configure(env => { env.Tracing( enabled: true, displayErrorTraces: true); }); }); // When var result = await browser.Get("/cyclical", with => with.Accept(accept)); //Then var resultBody = result.Body.AsString(); resultBody.ShouldNotBeEmpty(); } [Theory] [InlineData("application/xml")] public async Task Should_return_no_error_message_on_cyclical_exception_when_disabled_error_trace(string accept) { //Given var browser = new Browser(with => { with.Modules(typeof(EchoModule)); with.Configure(env => { env.Tracing( enabled: true, displayErrorTraces: false); }); }); // When var result = await browser.Get("/cyclical", with => with.Accept(accept)); //Then result.Body.AsString().ShouldBeEmpty(); } public class EchoModel { public string SomeString { get; set; } public int SomeInt { get; set; } public bool SomeBoolean { get; set; } } public class Category { public string Name { get; set; } public ICollection<Product> Products { get; set; } } public class Product { public string Name { get; set; } public Category Category { get; set; } } public class EchoModule : NancyModule { public EchoModule() { Get("/cyclical", args => { var category = new Category(); category.Name = "Electronics"; var product = new Product(); product.Name = "iPad"; product.Category = category; category.Products = new Collection<Product>(new List<Product>(new[] { product })); return product; }); Post("/", args => { var body = new StreamReader(this.Context.Request.Body).ReadToEnd(); return new Response { Contents = stream => { var writer = new StreamWriter(stream); writer.Write(body); writer.Flush(); } }; }); Get("/cookie", args => { var response = (Response)"Cookies"; foreach (var cookie in this.Request.Cookies) { response.WithCookie(cookie.Key, cookie.Value); } return response; }); Get("/nothing", args => string.Empty); Get("/userHostAddress", args => this.Request.UserHostAddress); Get("/isLocal", args => this.Request.IsLocal() ? "local" : "not-local"); Get("/session", args => { var value = Session["moo"] ?? ""; var output = "Current session value is: " + value; if (string.IsNullOrEmpty(value.ToString())) { Session["moo"] = "I've created a session!"; } var response = (Response)output; return response; }); Get("/useragent", args => this.Request.Headers.UserAgent); Get("/type", args => this.Request.Url.Scheme.ToLower()); Get("/ajax", args => this.Request.IsAjaxRequest() ? "ajax" : "not-ajax"); Post("/encoded", args => (string)this.Request.Form.name); Post("/encodedquerystring", args => (string)this.Request.Query.name); Post("/serializedform", args => { IDictionary<string, object> data = Request.Form.ToDictionary(); return data; }); Get("/serializedquerystring", args => { IDictionary<string, object> data = Request.Query.ToDictionary(); return data; }); } } } }
// This file was generated by the Gtk# code generator. // Any changes made will be lost if regenerated. namespace Gtk { using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; #region Autogenerated code public partial class Popover : Gtk.Bin { public Popover (IntPtr raw) : base(raw) {} [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr gtk_popover_new(IntPtr relative_to); public Popover (Gtk.Widget relative_to) : base (IntPtr.Zero) { if (GetType () != typeof (Popover)) { throw new InvalidOperationException ("Can't override this constructor."); } Raw = gtk_popover_new(relative_to == null ? IntPtr.Zero : relative_to.Handle); } [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr gtk_popover_new_from_model(IntPtr relative_to, IntPtr model); public Popover (Gtk.Widget relative_to, GLib.MenuModel model) : base (IntPtr.Zero) { if (GetType () != typeof (Popover)) { throw new InvalidOperationException ("Can't override this constructor."); } Raw = gtk_popover_new_from_model(relative_to == null ? IntPtr.Zero : relative_to.Handle, model == null ? IntPtr.Zero : model.Handle); } [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern int gtk_popover_get_constrain_to(IntPtr raw); [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern void gtk_popover_set_constrain_to(IntPtr raw, int constraint); [GLib.Property ("constrain-to")] public Gtk.PopoverConstraint ConstrainTo { get { int raw_ret = gtk_popover_get_constrain_to(Handle); Gtk.PopoverConstraint ret = (Gtk.PopoverConstraint) raw_ret; return ret; } set { gtk_popover_set_constrain_to(Handle, (int) value); } } [GLib.Signal("closed")] public event System.EventHandler Closed { add { this.AddSignalHandler ("closed", value); } remove { this.RemoveSignalHandler ("closed", value); } } static ClosedNativeDelegate Closed_cb_delegate; static ClosedNativeDelegate ClosedVMCallback { get { if (Closed_cb_delegate == null) Closed_cb_delegate = new ClosedNativeDelegate (Closed_cb); return Closed_cb_delegate; } } static void OverrideClosed (GLib.GType gtype) { OverrideClosed (gtype, ClosedVMCallback); } static void OverrideClosed (GLib.GType gtype, ClosedNativeDelegate callback) { GtkPopoverClass class_iface = GetClassStruct (gtype, false); class_iface.Closed = callback; OverrideClassStruct (gtype, class_iface); } [UnmanagedFunctionPointer (CallingConvention.Cdecl)] delegate void ClosedNativeDelegate (IntPtr inst); static void Closed_cb (IntPtr inst) { try { Popover __obj = GLib.Object.GetObject (inst, false) as Popover; __obj.OnClosed (); } catch (Exception e) { GLib.ExceptionManager.RaiseUnhandledException (e, false); } } [GLib.DefaultSignalHandler(Type=typeof(Gtk.Popover), ConnectionMethod="OverrideClosed")] protected virtual void OnClosed () { InternalClosed (); } private void InternalClosed () { ClosedNativeDelegate unmanaged = GetClassStruct (this.LookupGType ().GetThresholdType (), true).Closed; if (unmanaged == null) return; unmanaged (this.Handle); } [StructLayout (LayoutKind.Sequential)] struct GtkPopoverClass { public ClosedNativeDelegate Closed; [MarshalAs (UnmanagedType.ByValArray, SizeConst=10)] public IntPtr[] Reserved; } static uint class_offset = ((GLib.GType) typeof (Gtk.Bin)).GetClassSize (); static Dictionary<GLib.GType, GtkPopoverClass> class_structs; static GtkPopoverClass GetClassStruct (GLib.GType gtype, bool use_cache) { if (class_structs == null) class_structs = new Dictionary<GLib.GType, GtkPopoverClass> (); if (use_cache && class_structs.ContainsKey (gtype)) return class_structs [gtype]; else { IntPtr class_ptr = new IntPtr (gtype.GetClassPtr ().ToInt64 () + class_offset); GtkPopoverClass class_struct = (GtkPopoverClass) Marshal.PtrToStructure (class_ptr, typeof (GtkPopoverClass)); if (use_cache) class_structs.Add (gtype, class_struct); return class_struct; } } static void OverrideClassStruct (GLib.GType gtype, GtkPopoverClass class_struct) { IntPtr class_ptr = new IntPtr (gtype.GetClassPtr ().ToInt64 () + class_offset); Marshal.StructureToPtr (class_struct, class_ptr, false); } [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern void gtk_popover_bind_model(IntPtr raw, IntPtr model, IntPtr action_namespace); public void BindModel(GLib.MenuModel model, string action_namespace) { IntPtr native_action_namespace = GLib.Marshaller.StringToPtrGStrdup (action_namespace); gtk_popover_bind_model(Handle, model == null ? IntPtr.Zero : model.Handle, native_action_namespace); GLib.Marshaller.Free (native_action_namespace); } [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr gtk_popover_get_default_widget(IntPtr raw); [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern void gtk_popover_set_default_widget(IntPtr raw, IntPtr widget); public Gtk.Widget DefaultWidget { get { IntPtr raw_ret = gtk_popover_get_default_widget(Handle); Gtk.Widget ret = GLib.Object.GetObject(raw_ret) as Gtk.Widget; return ret; } set { gtk_popover_set_default_widget(Handle, value == null ? IntPtr.Zero : value.Handle); } } [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern bool gtk_popover_get_modal(IntPtr raw); [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern void gtk_popover_set_modal(IntPtr raw, bool modal); public bool Modal { get { bool raw_ret = gtk_popover_get_modal(Handle); bool ret = raw_ret; return ret; } set { gtk_popover_set_modal(Handle, value); } } [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern bool gtk_popover_get_pointing_to(IntPtr raw, IntPtr rect); public bool GetPointingTo(Gdk.Rectangle rect) { IntPtr native_rect = GLib.Marshaller.StructureToPtrAlloc (rect); bool raw_ret = gtk_popover_get_pointing_to(Handle, native_rect); bool ret = raw_ret; Marshal.FreeHGlobal (native_rect); return ret; } [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern int gtk_popover_get_position(IntPtr raw); [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern void gtk_popover_set_position(IntPtr raw, int position); public Gtk.PositionType Position { get { int raw_ret = gtk_popover_get_position(Handle); Gtk.PositionType ret = (Gtk.PositionType) raw_ret; return ret; } set { gtk_popover_set_position(Handle, (int) value); } } [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr gtk_popover_get_relative_to(IntPtr raw); [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern void gtk_popover_set_relative_to(IntPtr raw, IntPtr relative_to); public Gtk.Widget RelativeTo { get { IntPtr raw_ret = gtk_popover_get_relative_to(Handle); Gtk.Widget ret = GLib.Object.GetObject(raw_ret) as Gtk.Widget; return ret; } set { gtk_popover_set_relative_to(Handle, value == null ? IntPtr.Zero : value.Handle); } } [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern bool gtk_popover_get_transitions_enabled(IntPtr raw); [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern void gtk_popover_set_transitions_enabled(IntPtr raw, bool transitions_enabled); public bool TransitionsEnabled { get { bool raw_ret = gtk_popover_get_transitions_enabled(Handle); bool ret = raw_ret; return ret; } set { gtk_popover_set_transitions_enabled(Handle, value); } } [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr gtk_popover_get_type(); public static new GLib.GType GType { get { IntPtr raw_ret = gtk_popover_get_type(); GLib.GType ret = new GLib.GType(raw_ret); return ret; } } [DllImport("libgtk-3.dll", CallingConvention = CallingConvention.Cdecl)] static extern void gtk_popover_set_pointing_to(IntPtr raw, IntPtr rect); public void SetPointingTo(Gdk.Rectangle rect) { IntPtr native_rect = GLib.Marshaller.StructureToPtrAlloc (rect); gtk_popover_set_pointing_to(Handle, native_rect); Marshal.FreeHGlobal (native_rect); } #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Osu.Judgements; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Scoring; using osu.Game.Tests.Beatmaps; namespace osu.Game.Tests.Rulesets.Scoring { public class ScoreProcessorTest { private ScoreProcessor scoreProcessor; private IBeatmap beatmap; [SetUp] public void SetUp() { scoreProcessor = new ScoreProcessor(); beatmap = new TestBeatmap(new RulesetInfo()) { HitObjects = new List<HitObject> { new HitCircle() } }; } [TestCase(ScoringMode.Standardised, HitResult.Meh, 750_000)] [TestCase(ScoringMode.Standardised, HitResult.Ok, 800_000)] [TestCase(ScoringMode.Standardised, HitResult.Great, 1_000_000)] [TestCase(ScoringMode.Classic, HitResult.Meh, 41)] [TestCase(ScoringMode.Classic, HitResult.Ok, 46)] [TestCase(ScoringMode.Classic, HitResult.Great, 72)] public void TestSingleOsuHit(ScoringMode scoringMode, HitResult hitResult, int expectedScore) { scoreProcessor.Mode.Value = scoringMode; scoreProcessor.ApplyBeatmap(beatmap); var judgementResult = new JudgementResult(beatmap.HitObjects.Single(), new OsuJudgement()) { Type = hitResult }; scoreProcessor.ApplyResult(judgementResult); Assert.That(scoreProcessor.TotalScore.Value, Is.EqualTo(expectedScore).Within(0.5d)); } /// <summary> /// Test to see that all <see cref="HitResult"/>s contribute to score portions in correct amounts. /// </summary> /// <param name="scoringMode">Scoring mode to test.</param> /// <param name="hitResult">The <see cref="HitResult"/> that will be applied to selected hit objects.</param> /// <param name="maxResult">The maximum <see cref="HitResult"/> achievable.</param> /// <param name="expectedScore">Expected score after all objects have been judged, rounded to the nearest integer.</param> /// <remarks> /// This test intentionally misses the 3rd hitobject to achieve lower than 75% accuracy and 50% max combo. /// <para> /// For standardised scoring, <paramref name="expectedScore"/> is calculated using the following formula: /// 1_000_000 * (((3 * <paramref name="hitResult"/>) / (4 * <paramref name="maxResult"/>)) * 30% + (bestCombo / maxCombo) * 70%) /// </para> /// <para> /// For classic scoring, <paramref name="expectedScore"/> is calculated using the following formula: /// <paramref name="hitResult"/> / <paramref name="maxResult"/> * 936 /// where 936 is simplified from: /// 75% * 4 * 300 * (1 + 1/25) /// </para> /// </remarks> [TestCase(ScoringMode.Standardised, HitResult.Miss, HitResult.Great, 0)] // (3 * 0) / (4 * 300) * 300_000 + (0 / 4) * 700_000 [TestCase(ScoringMode.Standardised, HitResult.Meh, HitResult.Great, 387_500)] // (3 * 50) / (4 * 300) * 300_000 + (2 / 4) * 700_000 [TestCase(ScoringMode.Standardised, HitResult.Ok, HitResult.Great, 425_000)] // (3 * 100) / (4 * 300) * 300_000 + (2 / 4) * 700_000 [TestCase(ScoringMode.Standardised, HitResult.Good, HitResult.Perfect, 492_857)] // (3 * 200) / (4 * 350) * 300_000 + (2 / 4) * 700_000 [TestCase(ScoringMode.Standardised, HitResult.Great, HitResult.Great, 575_000)] // (3 * 300) / (4 * 300) * 300_000 + (2 / 4) * 700_000 [TestCase(ScoringMode.Standardised, HitResult.Perfect, HitResult.Perfect, 575_000)] // (3 * 350) / (4 * 350) * 300_000 + (2 / 4) * 700_000 [TestCase(ScoringMode.Standardised, HitResult.SmallTickMiss, HitResult.SmallTickHit, 700_000)] // (3 * 0) / (4 * 10) * 300_000 + 700_000 (max combo 0) [TestCase(ScoringMode.Standardised, HitResult.SmallTickHit, HitResult.SmallTickHit, 925_000)] // (3 * 10) / (4 * 10) * 300_000 + 700_000 (max combo 0) [TestCase(ScoringMode.Standardised, HitResult.LargeTickMiss, HitResult.LargeTickHit, 0)] // (3 * 0) / (4 * 30) * 300_000 + (0 / 4) * 700_000 [TestCase(ScoringMode.Standardised, HitResult.LargeTickHit, HitResult.LargeTickHit, 575_000)] // (3 * 30) / (4 * 30) * 300_000 + (0 / 4) * 700_000 [TestCase(ScoringMode.Standardised, HitResult.SmallBonus, HitResult.SmallBonus, 1_000_030)] // 1 * 300_000 + 700_000 (max combo 0) + 3 * 10 (bonus points) [TestCase(ScoringMode.Standardised, HitResult.LargeBonus, HitResult.LargeBonus, 1_000_150)] // 1 * 300_000 + 700_000 (max combo 0) + 3 * 50 (bonus points) [TestCase(ScoringMode.Classic, HitResult.Miss, HitResult.Great, 0)] [TestCase(ScoringMode.Classic, HitResult.Meh, HitResult.Great, 68)] [TestCase(ScoringMode.Classic, HitResult.Ok, HitResult.Great, 81)] [TestCase(ScoringMode.Classic, HitResult.Good, HitResult.Perfect, 109)] [TestCase(ScoringMode.Classic, HitResult.Great, HitResult.Great, 149)] [TestCase(ScoringMode.Classic, HitResult.Perfect, HitResult.Perfect, 149)] [TestCase(ScoringMode.Classic, HitResult.SmallTickMiss, HitResult.SmallTickHit, 9)] [TestCase(ScoringMode.Classic, HitResult.SmallTickHit, HitResult.SmallTickHit, 15)] [TestCase(ScoringMode.Classic, HitResult.LargeTickMiss, HitResult.LargeTickHit, 0)] [TestCase(ScoringMode.Classic, HitResult.LargeTickHit, HitResult.LargeTickHit, 149)] [TestCase(ScoringMode.Classic, HitResult.SmallBonus, HitResult.SmallBonus, 18)] [TestCase(ScoringMode.Classic, HitResult.LargeBonus, HitResult.LargeBonus, 18)] public void TestFourVariousResultsOneMiss(ScoringMode scoringMode, HitResult hitResult, HitResult maxResult, int expectedScore) { var minResult = new TestJudgement(hitResult).MinResult; IBeatmap fourObjectBeatmap = new TestBeatmap(new RulesetInfo()) { HitObjects = new List<HitObject>(Enumerable.Repeat(new TestHitObject(maxResult), 4)) }; scoreProcessor.Mode.Value = scoringMode; scoreProcessor.ApplyBeatmap(fourObjectBeatmap); for (int i = 0; i < 4; i++) { var judgementResult = new JudgementResult(fourObjectBeatmap.HitObjects[i], new Judgement()) { Type = i == 2 ? minResult : hitResult }; scoreProcessor.ApplyResult(judgementResult); } Assert.That(scoreProcessor.TotalScore.Value, Is.EqualTo(expectedScore).Within(0.5d)); } /// <remarks> /// This test uses a beatmap with four small ticks and one object with the <see cref="Judgement.MaxResult"/> of <see cref="HitResult.Ok"/>. /// Its goal is to ensure that with the <see cref="ScoringMode"/> of <see cref="ScoringMode.Standardised"/>, /// small ticks contribute to the accuracy portion, but not the combo portion. /// In contrast, <see cref="ScoringMode.Classic"/> does not have separate combo and accuracy portion (they are multiplied by each other). /// </remarks> [TestCase(ScoringMode.Standardised, HitResult.SmallTickHit, 978_571)] // (3 * 10 + 100) / (4 * 10 + 100) * 300_000 + (1 / 1) * 700_000 [TestCase(ScoringMode.Standardised, HitResult.SmallTickMiss, 914_286)] // (3 * 0 + 100) / (4 * 10 + 100) * 300_000 + (1 / 1) * 700_000 [TestCase(ScoringMode.Classic, HitResult.SmallTickHit, 69)] // (((3 * 10 + 100) / (4 * 10 + 100)) * 1 * 300) * (1 + 0 / 25) [TestCase(ScoringMode.Classic, HitResult.SmallTickMiss, 60)] // (((3 * 0 + 100) / (4 * 10 + 100)) * 1 * 300) * (1 + 0 / 25) public void TestSmallTicksAccuracy(ScoringMode scoringMode, HitResult hitResult, int expectedScore) { IEnumerable<HitObject> hitObjects = Enumerable .Repeat(new TestHitObject(HitResult.SmallTickHit), 4) .Append(new TestHitObject(HitResult.Ok)); IBeatmap fiveObjectBeatmap = new TestBeatmap(new RulesetInfo()) { HitObjects = hitObjects.ToList() }; scoreProcessor.Mode.Value = scoringMode; scoreProcessor.ApplyBeatmap(fiveObjectBeatmap); for (int i = 0; i < 4; i++) { var judgementResult = new JudgementResult(fiveObjectBeatmap.HitObjects[i], new Judgement()) { Type = i == 2 ? HitResult.SmallTickMiss : hitResult }; scoreProcessor.ApplyResult(judgementResult); } var lastJudgementResult = new JudgementResult(fiveObjectBeatmap.HitObjects.Last(), new Judgement()) { Type = HitResult.Ok }; scoreProcessor.ApplyResult(lastJudgementResult); Assert.That(scoreProcessor.TotalScore.Value, Is.EqualTo(expectedScore).Within(0.5d)); } [Test] public void TestEmptyBeatmap( [Values(ScoringMode.Standardised, ScoringMode.Classic)] ScoringMode scoringMode) { scoreProcessor.Mode.Value = scoringMode; scoreProcessor.ApplyBeatmap(new TestBeatmap(new RulesetInfo())); Assert.That(scoreProcessor.TotalScore.Value, Is.Zero); } [TestCase(HitResult.IgnoreHit, HitResult.IgnoreMiss)] [TestCase(HitResult.Meh, HitResult.Miss)] [TestCase(HitResult.Ok, HitResult.Miss)] [TestCase(HitResult.Good, HitResult.Miss)] [TestCase(HitResult.Great, HitResult.Miss)] [TestCase(HitResult.Perfect, HitResult.Miss)] [TestCase(HitResult.SmallTickHit, HitResult.SmallTickMiss)] [TestCase(HitResult.LargeTickHit, HitResult.LargeTickMiss)] [TestCase(HitResult.SmallBonus, HitResult.IgnoreMiss)] [TestCase(HitResult.LargeBonus, HitResult.IgnoreMiss)] public void TestMinResults(HitResult hitResult, HitResult expectedMinResult) { Assert.AreEqual(expectedMinResult, new TestJudgement(hitResult).MinResult); } [TestCase(HitResult.None, false)] [TestCase(HitResult.IgnoreMiss, false)] [TestCase(HitResult.IgnoreHit, false)] [TestCase(HitResult.Miss, true)] [TestCase(HitResult.Meh, true)] [TestCase(HitResult.Ok, true)] [TestCase(HitResult.Good, true)] [TestCase(HitResult.Great, true)] [TestCase(HitResult.Perfect, true)] [TestCase(HitResult.SmallTickMiss, false)] [TestCase(HitResult.SmallTickHit, false)] [TestCase(HitResult.LargeTickMiss, true)] [TestCase(HitResult.LargeTickHit, true)] [TestCase(HitResult.SmallBonus, false)] [TestCase(HitResult.LargeBonus, false)] public void TestAffectsCombo(HitResult hitResult, bool expectedReturnValue) { Assert.AreEqual(expectedReturnValue, hitResult.AffectsCombo()); } [TestCase(HitResult.None, false)] [TestCase(HitResult.IgnoreMiss, false)] [TestCase(HitResult.IgnoreHit, false)] [TestCase(HitResult.Miss, true)] [TestCase(HitResult.Meh, true)] [TestCase(HitResult.Ok, true)] [TestCase(HitResult.Good, true)] [TestCase(HitResult.Great, true)] [TestCase(HitResult.Perfect, true)] [TestCase(HitResult.SmallTickMiss, true)] [TestCase(HitResult.SmallTickHit, true)] [TestCase(HitResult.LargeTickMiss, true)] [TestCase(HitResult.LargeTickHit, true)] [TestCase(HitResult.SmallBonus, false)] [TestCase(HitResult.LargeBonus, false)] public void TestAffectsAccuracy(HitResult hitResult, bool expectedReturnValue) { Assert.AreEqual(expectedReturnValue, hitResult.AffectsAccuracy()); } [TestCase(HitResult.None, false)] [TestCase(HitResult.IgnoreMiss, false)] [TestCase(HitResult.IgnoreHit, false)] [TestCase(HitResult.Miss, false)] [TestCase(HitResult.Meh, false)] [TestCase(HitResult.Ok, false)] [TestCase(HitResult.Good, false)] [TestCase(HitResult.Great, false)] [TestCase(HitResult.Perfect, false)] [TestCase(HitResult.SmallTickMiss, false)] [TestCase(HitResult.SmallTickHit, false)] [TestCase(HitResult.LargeTickMiss, false)] [TestCase(HitResult.LargeTickHit, false)] [TestCase(HitResult.SmallBonus, true)] [TestCase(HitResult.LargeBonus, true)] public void TestIsBonus(HitResult hitResult, bool expectedReturnValue) { Assert.AreEqual(expectedReturnValue, hitResult.IsBonus()); } [TestCase(HitResult.None, false)] [TestCase(HitResult.IgnoreMiss, false)] [TestCase(HitResult.IgnoreHit, true)] [TestCase(HitResult.Miss, false)] [TestCase(HitResult.Meh, true)] [TestCase(HitResult.Ok, true)] [TestCase(HitResult.Good, true)] [TestCase(HitResult.Great, true)] [TestCase(HitResult.Perfect, true)] [TestCase(HitResult.SmallTickMiss, false)] [TestCase(HitResult.SmallTickHit, true)] [TestCase(HitResult.LargeTickMiss, false)] [TestCase(HitResult.LargeTickHit, true)] [TestCase(HitResult.SmallBonus, true)] [TestCase(HitResult.LargeBonus, true)] public void TestIsHit(HitResult hitResult, bool expectedReturnValue) { Assert.AreEqual(expectedReturnValue, hitResult.IsHit()); } [TestCase(HitResult.None, false)] [TestCase(HitResult.IgnoreMiss, false)] [TestCase(HitResult.IgnoreHit, false)] [TestCase(HitResult.Miss, true)] [TestCase(HitResult.Meh, true)] [TestCase(HitResult.Ok, true)] [TestCase(HitResult.Good, true)] [TestCase(HitResult.Great, true)] [TestCase(HitResult.Perfect, true)] [TestCase(HitResult.SmallTickMiss, true)] [TestCase(HitResult.SmallTickHit, true)] [TestCase(HitResult.LargeTickMiss, true)] [TestCase(HitResult.LargeTickHit, true)] [TestCase(HitResult.SmallBonus, true)] [TestCase(HitResult.LargeBonus, true)] public void TestIsScorable(HitResult hitResult, bool expectedReturnValue) { Assert.AreEqual(expectedReturnValue, hitResult.IsScorable()); } [TestCase(HitResult.Perfect, 1_000_000)] [TestCase(HitResult.SmallTickHit, 1_000_000)] [TestCase(HitResult.LargeTickHit, 1_000_000)] [TestCase(HitResult.SmallBonus, 1_000_000 + Judgement.SMALL_BONUS_SCORE)] [TestCase(HitResult.LargeBonus, 1_000_000 + Judgement.LARGE_BONUS_SCORE)] public void TestGetScoreWithExternalStatistics(HitResult result, int expectedScore) { var statistic = new Dictionary<HitResult, int> { { result, 1 } }; scoreProcessor.ApplyBeatmap(new Beatmap { HitObjects = { new TestHitObject(result) } }); Assert.That(scoreProcessor.GetImmediateScore(ScoringMode.Standardised, result.AffectsCombo() ? 1 : 0, statistic), Is.EqualTo(expectedScore).Within(0.5d)); } private class TestJudgement : Judgement { public override HitResult MaxResult { get; } public TestJudgement(HitResult maxResult) { MaxResult = maxResult; } } private class TestHitObject : HitObject { private readonly HitResult maxResult; public override Judgement CreateJudgement() { return new TestJudgement(maxResult); } public TestHitObject(HitResult maxResult) { this.maxResult = maxResult; } } } }
//------------------------------------------------------------------------------ // <copyright file="SubMenuStyle.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System.ComponentModel; using System.Drawing; using System.Globalization; using System.Text; using System.Web.UI; /// <devdoc> /// Specifies the style of a SubMenu. /// </devdoc> public class SubMenuStyle : Style, ICustomTypeDescriptor { private const int PROP_VPADDING = 0x00010000; private const int PROP_HPADDING = 0x00020000; public SubMenuStyle() : base() { } public SubMenuStyle(StateBag bag) : base(bag) { } /// <devdoc> /// Gets and sets the horizontal padding around the node text /// </devdoc> [ DefaultValue(typeof(Unit), ""), WebCategory("Layout"), NotifyParentProperty(true), WebSysDescription(SR.SubMenuStyle_HorizontalPadding), ] public Unit HorizontalPadding { get { if (IsSet(PROP_HPADDING)) { return (Unit)(ViewState["HorizontalPadding"]); } return Unit.Empty; } set { if ((value.Type == UnitType.Percentage) || (value.Value < 0)) { throw new ArgumentOutOfRangeException("value"); } ViewState["HorizontalPadding"] = value; SetBit(PROP_HPADDING); } } /// <devdoc> /// Gets and sets the vertical padding around the node text /// </devdoc> [ DefaultValue(typeof(Unit), ""), WebCategory("Layout"), NotifyParentProperty(true), WebSysDescription(SR.SubMenuStyle_VerticalPadding), ] public Unit VerticalPadding { get { if (IsSet(PROP_VPADDING)) { return (Unit)(ViewState["VerticalPadding"]); } return Unit.Empty; } set { if ((value.Type == UnitType.Percentage) || (value.Value < 0)) { throw new ArgumentOutOfRangeException("value"); } ViewState["VerticalPadding"] = value; SetBit(PROP_VPADDING); } } /// <devdoc> /// Copies non-blank elements from the specified style, overwriting existing /// style elements if necessary. /// </devdoc> public override void CopyFrom(Style s) { if (s != null) { base.CopyFrom(s); SubMenuStyle sms = s as SubMenuStyle; if (sms != null && !sms.IsEmpty) { // Only copy the paddings if they aren't in the source Style's registered CSS class if (s.RegisteredCssClass.Length != 0) { if (sms.IsSet(PROP_VPADDING)) { ViewState.Remove("VerticalPadding"); ClearBit(PROP_VPADDING); } if (sms.IsSet(PROP_HPADDING)) { ViewState.Remove("HorizontalPadding"); ClearBit(PROP_HPADDING); } } else { if (sms.IsSet(PROP_VPADDING)) { this.VerticalPadding = sms.VerticalPadding; } if (sms.IsSet(PROP_HPADDING)) { this.HorizontalPadding = sms.HorizontalPadding; } } } } } protected override void FillStyleAttributes(CssStyleCollection attributes, IUrlResolutionService urlResolver) { // The style will be rendered on container elements that does not contain text directly. // It does not render font and forecolor. // Users should set font and forecolor on MenuItems styles. // Copying the code from the base class, except for the part that deals with Font and ForeColor. StateBag viewState = ViewState; Color c; // BackColor if (base.IsSet(PROP_BACKCOLOR)) { c = (Color)viewState["BackColor"]; if (!c.IsEmpty) { attributes.Add(HtmlTextWriterStyle.BackgroundColor, ColorTranslator.ToHtml(c)); } } // BorderColor if (base.IsSet(PROP_BORDERCOLOR)) { c = (Color)viewState["BorderColor"]; if (!c.IsEmpty) { attributes.Add(HtmlTextWriterStyle.BorderColor, ColorTranslator.ToHtml(c)); } } BorderStyle bs = this.BorderStyle; Unit bu = this.BorderWidth; if (!bu.IsEmpty) { attributes.Add(HtmlTextWriterStyle.BorderWidth, bu.ToString(CultureInfo.InvariantCulture)); if (bs == BorderStyle.NotSet) { if (bu.Value != 0.0) { attributes.Add(HtmlTextWriterStyle.BorderStyle, "solid"); } } else { attributes.Add(HtmlTextWriterStyle.BorderStyle, borderStyles[(int)bs]); } } else { if (bs != BorderStyle.NotSet) { attributes.Add(HtmlTextWriterStyle.BorderStyle, borderStyles[(int)bs]); } } Unit u; // Height if (base.IsSet(PROP_HEIGHT)) { u = (Unit)viewState["Height"]; if (!u.IsEmpty) { attributes.Add(HtmlTextWriterStyle.Height, u.ToString(CultureInfo.InvariantCulture)); } } // Width if (base.IsSet(PROP_WIDTH)) { u = (Unit)viewState["Width"]; if (!u.IsEmpty) { attributes.Add(HtmlTextWriterStyle.Width, u.ToString(CultureInfo.InvariantCulture)); } } if (!HorizontalPadding.IsEmpty || !VerticalPadding.IsEmpty) { attributes.Add(HtmlTextWriterStyle.Padding, string.Format(CultureInfo.InvariantCulture, "{0} {1} {0} {1}", VerticalPadding.IsEmpty ? Unit.Pixel(0) : VerticalPadding, HorizontalPadding.IsEmpty ? Unit.Pixel(0) : HorizontalPadding)); } } /// <devdoc> /// Copies non-blank elements from the specified style, but will not overwrite /// any existing style elements. /// </devdoc> public override void MergeWith(Style s) { if (s != null) { if (IsEmpty) { // Merging with an empty style is equivalent to copying, // which is more efficient. CopyFrom(s); return; } base.MergeWith(s); SubMenuStyle sms = s as SubMenuStyle; // Since we're already copying the registered CSS class in base.MergeWith, we don't // need to any attributes that would be included in that class. if (sms != null && !sms.IsEmpty && s.RegisteredCssClass.Length == 0) { if (sms.IsSet(PROP_VPADDING) && !this.IsSet(PROP_VPADDING)) { this.VerticalPadding = sms.VerticalPadding; } if (sms.IsSet(PROP_HPADDING) && !this.IsSet(PROP_HPADDING)) { this.HorizontalPadding = sms.HorizontalPadding; } } } } /// <devdoc> /// Clears out any defined style elements from the state bag. /// </devdoc> public override void Reset() { if (IsSet(PROP_VPADDING)) ViewState.Remove("VerticalPadding"); if (IsSet(PROP_HPADDING)) ViewState.Remove("HorizontalPadding"); base.Reset(); } #region ICustomTypeDesciptor implementation System.ComponentModel.AttributeCollection ICustomTypeDescriptor.GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } string ICustomTypeDescriptor.GetClassName() { return TypeDescriptor.GetClassName(this, true); } string ICustomTypeDescriptor.GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } TypeConverter ICustomTypeDescriptor.GetConverter() { return TypeDescriptor.GetConverter(this, true); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(this, true); } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(this, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor)this).GetProperties(null); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { PropertyDescriptorCollection oldProperties = TypeDescriptor.GetProperties(GetType(), attributes); PropertyDescriptor[] newProperties = new PropertyDescriptor[oldProperties.Count]; PropertyDescriptor fontProperty = oldProperties["Font"]; PropertyDescriptor forecolorProperty = oldProperties["ForeColor"]; Attribute[] newAttributes = new Attribute[] { new BrowsableAttribute(false), new EditorBrowsableAttribute(EditorBrowsableState.Never), new ThemeableAttribute(false), }; for (int i = 0; i < oldProperties.Count; i++) { PropertyDescriptor property = oldProperties[i]; if ((property == fontProperty) || (property == forecolorProperty)) { newProperties[i] = TypeDescriptor.CreateProperty(GetType(), property, newAttributes); } else { newProperties[i] = property; } } return new PropertyDescriptorCollection(newProperties, true); } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return this; } #endregion //ICustomTypeDescriptor implementation } }
// CRC32.cs - Computes CRC32 data checksum of a data stream // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; namespace TvdbLib.SharpZipLib.Checksums { /// <summary> /// Generate a table for a byte-wise 32-bit CRC calculation on the polynomial: /// x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. /// /// Polynomials over GF(2) are represented in binary, one bit per coefficient, /// with the lowest powers in the most significant bit. Then adding polynomials /// is just exclusive-or, and multiplying a polynomial by x is a right shift by /// one. If we call the above polynomial p, and represent a byte as the /// polynomial q, also with the lowest power in the most significant bit (so the /// byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, /// where a mod b means the remainder after dividing a by b. /// /// This calculation is done using the shift-register method of multiplying and /// taking the remainder. The register is initialized to zero, and for each /// incoming bit, x^32 is added mod p to the register if the bit is a one (where /// x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by /// x (which is shifting right by one and adding x^32 mod p if the bit shifted /// out is a one). We start with the highest power (least significant bit) of /// q and repeat for all eight bits of q. /// /// The table is simply the CRC of all possible eight bit values. This is all /// the information needed to generate CRC's on data a byte at a time for all /// combinations of CRC register values and incoming bytes. /// </summary> public sealed class Crc32 : IChecksum { const uint CrcSeed = 0xFFFFFFFF; readonly static uint[] CrcTable = new uint[] { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; internal static uint ComputeCrc32(uint oldCrc, byte value) { return (uint)(Crc32.CrcTable[(oldCrc ^ value) & 0xFF] ^ (oldCrc >> 8)); } /// <summary> /// The crc data checksum so far. /// </summary> uint crc; /// <summary> /// Returns the CRC32 data checksum computed so far. /// </summary> public long Value { get { return (long)crc; } set { crc = (uint)value; } } /// <summary> /// Resets the CRC32 data checksum as if no update was ever called. /// </summary> public void Reset() { crc = 0; } /// <summary> /// Updates the checksum with the int bval. /// </summary> /// <param name = "value"> /// the byte is taken as the lower 8 bits of value /// </param> public void Update(int value) { crc ^= CrcSeed; crc = CrcTable[(crc ^ value) & 0xFF] ^ (crc >> 8); crc ^= CrcSeed; } /// <summary> /// Updates the checksum with the bytes taken from the array. /// </summary> /// <param name="buffer"> /// buffer an array of bytes /// </param> public void Update(byte[] buffer) { if (buffer == null) { throw new ArgumentNullException("buffer"); } Update(buffer, 0, buffer.Length); } /// <summary> /// Adds the byte array to the data checksum. /// </summary> /// <param name = "buffer"> /// The buffer which contains the data /// </param> /// <param name = "offset"> /// The offset in the buffer where the data starts /// </param> /// <param name = "count"> /// The number of data bytes to update the CRC with. /// </param> public void Update(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if ( count < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "Count cannot be less than zero"); #endif } if (offset < 0 || offset + count > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } crc ^= CrcSeed; while (--count >= 0) { crc = CrcTable[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >> 8); } crc ^= CrcSeed; } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Newtonsoft.Json; using Sensus.Exceptions; using System; using System.IO; using System.Threading; using System.Threading.Tasks; using System.Text; using System.IO.Compression; using Sensus.UI.UiProperties; using System.Linq; using Microsoft.AppCenter.Analytics; using System.Collections.Generic; using Sensus.Extensions; using ICSharpCode.SharpZipLib.Tar; using System.Net; namespace Sensus.DataStores.Local { /// <summary> /// Stores each <see cref="Datum"/> as plain-text JSON in a gzip-compressed file on the device's local storage media. Also /// supports encryption prior to transmission to a <see cref="Remote.RemoteDataStore"/>. /// </summary> public class FileLocalDataStore : LocalDataStore, IClearableDataStore { /// <summary> /// Number of <see cref="Datum"/> to write before checking the size of the data store. /// </summary> private const int DATA_WRITES_PER_SIZE_CHECK = 1000; /// <summary> /// Threshold on the size of the local storage directory in MB. When this is exceeded, a write to the <see cref="Remote.RemoteDataStore"/> /// will be forced. /// </summary> private const double REMOTE_WRITE_TRIGGER_STORAGE_DIRECTORY_SIZE_MB = 10; /// <summary> /// Threshold on the size of files within the local storage directory. When this is exceeded, a new file will be started. /// </summary> private const double MAX_FILE_SIZE_MB = 5; /// <summary> /// File-based storage uses a <see cref="BufferedStream"/> for efficiency. This is the default buffer size in bytes. /// </summary> private const int DEFAULT_BUFFER_SIZE_BYTES = 4096; /// <summary> /// File extension to use for JSON files. /// </summary> private const string JSON_FILE_EXTENSION = ".json"; /// <summary> /// File extension to use for GZip files. /// </summary> private const string GZIP_FILE_EXTENSION = ".gz"; /// <summary> /// Files extension to use for encrypted files. /// </summary> private const string ENCRYPTED_FILE_EXTENSION = ".bin"; /// <summary> /// The encryption key size in bits. /// </summary> private const int ENCRYPTION_KEY_SIZE_BITS = 32 * 8; /// <summary> /// The encryption initialization vector size in bits. /// </summary> private const int ENCRYPTION_INITIALIZATION_KEY_SIZE_BITS = 16 * 8; /// <summary> /// Step 1: An in-memory buffer that can be written at high rates. /// </summary> private List<Datum> _dataBuffer; private AutoResetEvent _dataHaveBeenBuffered; private long _totalDataBuffered; /// <summary> /// Step 2: A file on disk without a file extension, written with data from the in-memory buffer. /// </summary> private string _currentPath; private BufferedStream _currentFile; private int _currentFileBufferSizeBytes; private Task _writeBufferedDataToFileTask; private List<Datum> _toWriteBuffer; private AutoResetEvent _bufferedDataHaveBeenWrittenToFile; private long _totalDataWrittenToCurrentFile; private long _totalDataWritten; private int _totalFilesOpened; private int _totalFilesClosed; private readonly object _fileLocker = new object(); /// <summary> /// Step 3: A compressed, encrypted file on disk with a file extension. These files are ready for transmission to the <see cref="Remote.RemoteDataStore"/>. /// </summary> private CompressionLevel _compressionLevel; private bool _encrypt; private List<string> _pathsPreparedForRemote; private List<string> _pathsUnpreparedForRemote; private int _totalFilesPreparedForRemote; /// <summary> /// Step 4: Transmission to the <see cref="Remote.RemoteDataStore"/>. /// </summary> private Task _writeToRemoteTask; private int _totalFilesWrittenToRemote; private readonly object _writeToRemoteTaskLocker = new object(); public override bool HasDataToShare { get { lock (_pathsPreparedForRemote) { UpdatePathsPreparedForRemote(); return _pathsPreparedForRemote.Count > 0; } } } #if UNIT_TEST [JsonIgnore] public string CurrentPath { get { return _currentPath; } } [JsonIgnore] public List<string> PathsPreparedForRemote { get { return _pathsPreparedForRemote; } } #endif /// <summary> /// Gets or sets the compression level. Options are <see cref="CompressionLevel.NoCompression"/> (no compression), <see cref="CompressionLevel.Fastest"/> /// (computationally faster but less compression), and <see cref="CompressionLevel.Optimal"/> (computationally slower but more compression). /// </summary> /// <value>The compression level.</value> [ListUiProperty("Compression Level:", true, 1, new object[] { CompressionLevel.NoCompression, CompressionLevel.Fastest, CompressionLevel.Optimal }, true)] public CompressionLevel CompressionLevel { get { return _compressionLevel; } set { _compressionLevel = value; } } /// <summary> /// Gets or sets the buffer size in bytes. All <see cref="Probes.Probe"/>d data will be held in memory until the buffer is filled, at which time /// the data will be written to the file. There is not a single-best <see cref="BufferSizeBytes"/> value. If data are collected at high rates, a /// higher value will be best to minimize write operations. If data are collected at low rates, a lower value will be best to minimize the likelihood /// of data loss when the app is killed or crashes (as the buffer resides in RAM). /// </summary> /// <value>The buffer size in bytes.</value> [EntryIntegerUiProperty("Buffer Size (Bytes):", true, 2, true)] public int BufferSizeBytes { get { return _currentFileBufferSizeBytes; } set { if (value <= 0) { value = DEFAULT_BUFFER_SIZE_BYTES; } _currentFileBufferSizeBytes = value; } } /// <summary> /// Whether or not to apply asymmetric-key encryption to data. If this is enabled, then you must either provide a public encryption /// key to <see cref="Protocol.AsymmetricEncryptionPublicKey"/> or use an [authentication server](xref:authentication_servers). /// You can generate a public encryption key following the instructions provided for /// <see cref="Protocol.AsymmetricEncryptionPublicKey"/>. Note that data are not encrypted immediately. They are first /// written to disk on the device where they live unencrypted for a period of time. /// </summary> /// <value><c>true</c> to encrypt; otherwise, <c>false</c>.</value> [OnOffUiProperty("Encrypt:", true, 6)] public bool Encrypt { get { return _encrypt; } set { _encrypt = value; } } [JsonIgnore] public string StorageDirectory { get { string directory = Path.Combine(Protocol.StorageDirectory, GetType().FullName); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } return directory; } } [JsonIgnore] public long TotalDataWrittenToCurrentFile { get { return _totalDataWrittenToCurrentFile; } } [JsonIgnore] public long TotalDataBuffered { get { return _totalDataBuffered; } } [JsonIgnore] public long TotalDataWritten { get { return _totalDataWritten; } } [JsonIgnore] public override string DisplayName { get { return "File"; } } [JsonIgnore] public override string SizeDescription { get { string description = null; try { description = Math.Round(SensusServiceHelper.GetDirectorySizeMB(StorageDirectory), 1) + " MB"; } catch (Exception) { } return description; } } public FileLocalDataStore() { // step 1: buffer _dataBuffer = new List<Datum>(); _dataHaveBeenBuffered = new AutoResetEvent(false); // step 2: file _currentPath = null; _currentFile = null; _currentFileBufferSizeBytes = DEFAULT_BUFFER_SIZE_BYTES; _writeBufferedDataToFileTask = null; _toWriteBuffer = new List<Datum>(); _bufferedDataHaveBeenWrittenToFile = new AutoResetEvent(false); // step 3: compressed, encrypted file _compressionLevel = CompressionLevel.Optimal; _encrypt = false; _pathsPreparedForRemote = new List<string>(); _pathsUnpreparedForRemote = new List<string>(); // step 4: remote data store _writeToRemoteTask = null; } public override async Task StartAsync() { await base.StartAsync(); // ensure that we have a valid encryption setup if one is requested if (_encrypt) { Exception exToThrow = null; try { using (MemoryStream testStream = new MemoryStream()) { await Protocol.EnvelopeEncryptor.EnvelopeAsync(Encoding.UTF8.GetBytes("testing"), ENCRYPTION_KEY_SIZE_BITS, ENCRYPTION_INITIALIZATION_KEY_SIZE_BITS, testStream, CancellationToken.None); } } catch (WebException webException) { // only throw the web exception if it was not caused by a connection failure. we'll get these under normal conditions. if (webException.Status != WebExceptionStatus.ConnectFailure) { exToThrow = webException; } } // throw all other exceptions catch (Exception ex) { exToThrow = ex; } if (exToThrow != null) { throw new Exception("Failed encryption test: " + exToThrow.Message, exToThrow); } } UpdatePathsPreparedForRemote(); lock (_pathsUnpreparedForRemote) { _pathsUnpreparedForRemote.Clear(); } // process any paths that were written but not prepared for transfer to the remote data store. such // paths can exist when the app crashes before a file is closed and prepared. these paths will be // indicated by a lack of file extension. foreach (string pathUnpreparedForRemote in Directory.GetFiles(StorageDirectory).Where(path => string.IsNullOrWhiteSpace(Path.GetExtension(path)))) { await PreparePathForRemoteAsync(pathUnpreparedForRemote, CancellationToken.None); } OpenFile(); } private void UpdatePathsPreparedForRemote() { lock (_pathsPreparedForRemote) { _pathsPreparedForRemote.Clear(); _pathsPreparedForRemote.AddRange(Directory.GetFiles(StorageDirectory).Where(path => !string.IsNullOrWhiteSpace(Path.GetExtension(path)))); } } private void OpenFile() { lock (_fileLocker) { // it's possible to stop the data store before entering this lock. if (!Running) { return; } // try a few times to open a new file within the storage directory _currentPath = null; Exception mostRecentException = null; for (int tryNum = 0; _currentPath == null && tryNum < 5; ++tryNum) { try { _currentPath = Path.Combine(StorageDirectory, Guid.NewGuid().ToString()); _currentFile = new BufferedStream(new FileStream(_currentPath, FileMode.CreateNew, FileAccess.Write), _currentFileBufferSizeBytes); _totalDataWrittenToCurrentFile = 0; _totalFilesOpened++; } catch (Exception ex) { mostRecentException = ex; _currentPath = null; } } // we could not open a file to write, so we cannot proceed. report the most recent exception and bail. if (_currentPath == null) { throw SensusException.Report("Failed to open file for local data store.", mostRecentException); } else { // open the JSON array byte[] jsonOpenArrayBytes = Encoding.UTF8.GetBytes("["); _currentFile.Write(jsonOpenArrayBytes, 0, jsonOpenArrayBytes.Length); } } } public override void WriteDatum(Datum datum, CancellationToken cancellationToken) { if (!Running) { return; } lock (_dataBuffer) { _dataBuffer.Add(datum); _totalDataBuffered++; _dataHaveBeenBuffered.Set(); // start the long-running task for writing data to file. also check the status of the task after // it has been created and restart the task if it stops due to cancellation, fault, or completion. if (_writeBufferedDataToFileTask == null || _writeBufferedDataToFileTask.Status == TaskStatus.Canceled || _writeBufferedDataToFileTask.Status == TaskStatus.Faulted || _writeBufferedDataToFileTask.Status == TaskStatus.RanToCompletion) { _writeBufferedDataToFileTask = Task.Run(async () => { try { while (Running) { // wait for the signal to from data from the buffer to the file _dataHaveBeenBuffered.WaitOne(); // write data. be sure to acquire locks in the same order as in Flush. bool checkSize = false; bool startNewFile = false; lock (_toWriteBuffer) { // copy the current data to the buffer to write, and clear the current buffer. we use // the intermediary buffer to free up the data buffer lock as quickly as possible for // callers to WriteDatum. all probes call WriteDatum, so we need to accommodate // potentially hundreds of samples per second. lock (_dataBuffer) { _toWriteBuffer.AddRange(_dataBuffer); _dataBuffer.Clear(); } // write each datum from the intermediary buffer to disk. for (int i = 0; i < _toWriteBuffer.Count;) { Datum datumToWrite = _toWriteBuffer[i]; bool datumWritten = false; lock (_fileLocker) { // it's possible to stop the datastore and dispose the file before entering this lock, in // which case we won't have a file to write to. check the file. if (_currentFile != null) { #region write JSON for datum to file string datumJSON = null; try { datumJSON = datumToWrite.GetJSON(Protocol.JsonAnonymizer, false); } catch (Exception ex) { SensusException.Report("Failed to get JSON for datum.", ex); } if (datumJSON != null) { try { byte[] datumJsonBytes = Encoding.UTF8.GetBytes((_totalDataWrittenToCurrentFile == 0 ? "" : ",") + Environment.NewLine + datumJSON); _currentFile.Write(datumJsonBytes, 0, datumJsonBytes.Length); _totalDataWrittenToCurrentFile++; _totalDataWritten++; datumWritten = true; // periodically check the size of the current file if (_totalDataWrittenToCurrentFile % DATA_WRITES_PER_SIZE_CHECK == 0) { checkSize = true; } } catch (Exception writeException) { SensusException.Report("Exception while writing datum JSON bytes to file: " + writeException.Message, writeException); startNewFile = true; break; } } #endregion } } if (datumWritten) { _toWriteBuffer.RemoveAt(i); } else { i++; } } } if (checkSize) { // must do the check within the lock, since other callers might be trying to close the file and null the path. lock (_fileLocker) { if (SensusServiceHelper.GetFileSizeMB(_currentPath) >= MAX_FILE_SIZE_MB) { startNewFile = true; } } } if (startNewFile) { await StartNewFileAsync(cancellationToken); } if (checkSize) { await WriteToRemoteIfTooLargeAsync(cancellationToken); } _bufferedDataHaveBeenWrittenToFile.Set(); } } catch (Exception writeTaskException) { SensusException.Report("Exception while writing buffered data to file: " + writeTaskException.Message, writeTaskException); } }); } } } public override Task WriteToRemoteAsync(CancellationToken cancellationToken) { lock (_writeToRemoteTaskLocker) { // it's possible to stop the datastore before entering this lock. if (!Running || !WriteToRemote) { return Task.CompletedTask; } // if this is the first write or the previous write completed due to cancellation, fault, or completion, then // run a new task. if a write-to-remote task is currently running, then return it to the caller instead. if (_writeToRemoteTask == null || _writeToRemoteTask.Status == TaskStatus.Canceled || _writeToRemoteTask.Status == TaskStatus.Faulted || _writeToRemoteTask.Status == TaskStatus.RanToCompletion) { _writeToRemoteTask = Task.Run(async () => { await StartNewFileAsync(cancellationToken); string[] pathsPreparedForRemote; lock (_pathsPreparedForRemote) { UpdatePathsPreparedForRemote(); pathsPreparedForRemote = _pathsPreparedForRemote.ToArray(); } // if no paths are prepared, then we have nothing to do. if (pathsPreparedForRemote.Length == 0) { return; } // write each file that is prepared for transmission to the remote data store for (int i = 0; i < pathsPreparedForRemote.Length && !cancellationToken.IsCancellationRequested; ++i) { CaptionText = "Uploading file " + (i + 1) + " of " + pathsPreparedForRemote.Length + "."; #if __IOS__ // add encouragement to keep app open so that the upload may continue CaptionText += " Please keep Sensus open..."; #endif string pathPreparedForRemote = pathsPreparedForRemote[i]; // wrap in try-catch to ensure that we process all files try { // get stream name and content type string streamName = Path.GetFileName(pathPreparedForRemote); string streamContentType; if (streamName.EndsWith(JSON_FILE_EXTENSION)) { streamContentType = "application/json"; } else if (streamName.EndsWith(GZIP_FILE_EXTENSION)) { streamContentType = "application/gzip"; } else if (streamName.EndsWith(ENCRYPTED_FILE_EXTENSION)) { streamContentType = "application/octet-stream"; } else { // this should never happen. write anyway and report the situation. streamContentType = "application/octet-stream"; SensusException.Report("Unknown stream file extension: " + streamName); } using (FileStream filePreparedForRemote = new FileStream(pathPreparedForRemote, FileMode.Open, FileAccess.Read)) { await Protocol.RemoteDataStore.WriteDataStreamAsync(filePreparedForRemote, streamName, streamContentType, cancellationToken); } // file was written remotely. delete it locally, and do this within a lock to prevent concurrent access // by the code that checks the size of the data store. lock (_pathsPreparedForRemote) { File.Delete(pathPreparedForRemote); _pathsPreparedForRemote.Remove(pathPreparedForRemote); } _totalFilesWrittenToRemote++; } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while writing prepared file to remote data store: " + ex, LoggingLevel.Normal, GetType()); } } CaptionText = null; }, cancellationToken); } return _writeToRemoteTask; } } private async Task StartNewFileAsync(CancellationToken cancellationToken) { // start a new file within a lock to ensure that anyone with the lock will have a valid file string unpreparedPath = null; lock (_fileLocker) { try { unpreparedPath = CloseFile(); } catch (Exception closeException) { SensusException.Report("Exception while closing file: " + closeException.Message, closeException); } if (Running) { try { OpenFile(); } catch (Exception openException) { SensusException.Report("Exception while opening file: " + openException.Message, openException); } } } await PreparePathForRemoteAsync(unpreparedPath, cancellationToken); } public override void CreateTarFromLocalData(string outputPath) { lock (_pathsPreparedForRemote) { UpdatePathsPreparedForRemote(); if (_pathsPreparedForRemote.Count == 0) { throw new Exception("No data available."); } using (FileStream outputFile = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) { using (TarArchive tarArchive = TarArchive.CreateOutputTarArchive(outputFile)) { foreach (string pathPreparedForRemote in _pathsPreparedForRemote) { using (FileStream filePreparedForRemote = File.OpenRead(pathPreparedForRemote)) { TarEntry tarEntry = TarEntry.CreateEntryFromFile(pathPreparedForRemote); tarEntry.Name = "data/" + Path.GetFileName(pathPreparedForRemote); tarArchive.WriteEntry(tarEntry, false); filePreparedForRemote.Close(); } } tarArchive.Close(); } outputFile.Close(); } } } protected override bool IsTooLarge() { return GetSizeMB() >= REMOTE_WRITE_TRIGGER_STORAGE_DIRECTORY_SIZE_MB; } private double GetSizeMB() { double sizeMB = 0; lock (_pathsPreparedForRemote) { sizeMB += SensusServiceHelper.GetFileSizeMB(_pathsPreparedForRemote.ToArray()); } return sizeMB; } public void Flush() { // there's a race condition between writing new data to the buffers and flushing them. enter an // infinite loop that terminates when all buffers are empty and the file stream has been flushed. while (true) { bool buffersEmpty; // check for data in any of the buffers. be sure to acquire the locks in the same order as done in WriteDatum. lock (_toWriteBuffer) { lock (_dataBuffer) { buffersEmpty = _dataBuffer.Count == 0 && _toWriteBuffer.Count == 0; } } if (buffersEmpty) { // flush any bytes from the underlying file stream lock (_fileLocker) { _currentFile?.Flush(); } break; } else { // ask the write task to write buffered data _dataHaveBeenBuffered.Set(); // wait for buffered data to be written _bufferedDataHaveBeenWrittenToFile.WaitOne(); } } } private string CloseFile() { string path = _currentPath; lock (_fileLocker) { if (_currentFile != null) { try { // close the JSON array and close the file byte[] jsonCloseArrayBytes = Encoding.UTF8.GetBytes(Environment.NewLine + "]"); _currentFile.Write(jsonCloseArrayBytes, 0, jsonCloseArrayBytes.Length); _currentFile.Flush(); _currentFile.Close(); _currentFile.Dispose(); _currentFile = null; _currentPath = null; _totalFilesClosed++; _totalDataWrittenToCurrentFile = 0; } catch (Exception ex) { SensusException.Report("Exception while closing file: " + ex.Message, ex); } } } return path; } private async Task PreparePathForRemoteAsync(string path, CancellationToken cancellationToken) { try { if (File.Exists(path)) { byte[] bytes = File.ReadAllBytes(path); string preparedPath = Path.Combine(Path.GetDirectoryName(path), Guid.NewGuid() + JSON_FILE_EXTENSION); if (_compressionLevel != CompressionLevel.NoCompression) { preparedPath += GZIP_FILE_EXTENSION; Compressor compressor = new Compressor(Compressor.CompressionMethod.GZip); MemoryStream compressedStream = new MemoryStream(); compressor.Compress(bytes, compressedStream, _compressionLevel); bytes = compressedStream.ToArray(); } if (_encrypt) { preparedPath += ENCRYPTED_FILE_EXTENSION; using (FileStream preparedFile = new FileStream(preparedPath, FileMode.Create, FileAccess.Write)) { await Protocol.EnvelopeEncryptor.EnvelopeAsync(bytes, ENCRYPTION_KEY_SIZE_BITS, ENCRYPTION_INITIALIZATION_KEY_SIZE_BITS, preparedFile, cancellationToken); } } else { File.WriteAllBytes(preparedPath, bytes); } lock (_pathsPreparedForRemote) { _pathsPreparedForRemote.Add(preparedPath); } File.Delete(path); _totalFilesPreparedForRemote++; } lock (_pathsUnpreparedForRemote) { _pathsUnpreparedForRemote.Remove(path); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while preparing path for remote: " + ex.Message, LoggingLevel.Normal, GetType()); lock (_pathsUnpreparedForRemote) { if (!_pathsUnpreparedForRemote.Contains(path)) { _pathsUnpreparedForRemote.Add(path); } } } } public override async Task StopAsync() { // flush any remaining data to disk. Flush(); // stop the data store. it could very well be that someone attempts to add additional data // following the flush and prior to stopping. these data will be lost. await base.StopAsync(); // the data stores state is stopped, but the file write task will still be running if the // condition in its while-loop hasn't been checked. to ensure that this condition is checked, // signal the long-running write task to check for data, and wait for the task to finish. _dataHaveBeenBuffered.Set(); await (_writeBufferedDataToFileTask ?? Task.CompletedTask); // if no data have been written, then there will not yet be a task. lock (_dataBuffer) { _dataBuffer.Clear(); } lock (_toWriteBuffer) { _toWriteBuffer.Clear(); } await PreparePathForRemoteAsync(CloseFile(), CancellationToken.None); } public void Clear() { if (Protocol != null) { foreach (string path in Directory.GetFiles(StorageDirectory)) { try { File.Delete(path); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to delete local file \"" + path + "\": " + ex.Message, LoggingLevel.Normal, GetType()); } } _totalDataBuffered = 0; _totalDataWrittenToCurrentFile = 0; _totalDataWritten = 0; _totalFilesOpened = 0; _totalFilesClosed = 0; _totalFilesPreparedForRemote = 0; _totalFilesWrittenToRemote = 0; } } public override async Task<HealthTestResult> TestHealthAsync(List<AnalyticsTrackedEvent> events) { // retry file preparation for any unprepared paths List<string> pathsUnpreparedForRemote; lock (_pathsUnpreparedForRemote) { pathsUnpreparedForRemote = _pathsUnpreparedForRemote.ToList(); } foreach (string pathUnpreparedForRemote in pathsUnpreparedForRemote) { await PreparePathForRemoteAsync(pathUnpreparedForRemote, CancellationToken.None); } HealthTestResult result = await base.TestHealthAsync(events); string eventName = TrackedEvent.Health + ":" + GetType().Name; Dictionary<string, string> properties = new Dictionary<string, string> { { "Percent Buffer Written To File", Convert.ToString(_totalDataWritten.RoundToWholePercentageOf(_totalDataBuffered, 5)) }, { "Percent Files Closed", Convert.ToString(_totalFilesClosed.RoundToWholePercentageOf(_currentPath == null ? _totalFilesOpened : _totalFilesOpened - 1, 5)) }, // don't count the currently open file in the denominator. we want the number to reflect the extent to which all files that should have been closed indeed were. { "Percent Closed Files Prepared For Remote", Convert.ToString(_totalFilesPreparedForRemote.RoundToWholePercentageOf(_totalFilesClosed, 5)) }, { "Percent Closed Files Written To Remote", Convert.ToString(_totalFilesWrittenToRemote.RoundToWholePercentageOf(_totalFilesClosed, 5)) }, { "Paths Unprepared For Remote", Convert.ToString(_pathsUnpreparedForRemote.Count) }, { "Prepared Files Size MB", Convert.ToString(Math.Round(GetSizeMB(), 0)) } }; Analytics.TrackEvent(eventName, properties); events.Add(new AnalyticsTrackedEvent(eventName, properties)); return result; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI { using System.Text; using NPOI.OpenXml4Net.OPC.Internal; using System; using System.Collections.Generic; using NPOI.OpenXmlFormats; /** * A {@link POITextExtractor} for returning the textual * content of the OOXML file properties, eg author * and title. */ public class POIXMLPropertiesTextExtractor : POIXMLTextExtractor { /** * Creates a new POIXMLPropertiesTextExtractor for the * given open document. */ public POIXMLPropertiesTextExtractor(POIXMLDocument doc) : base(doc) { } /** * Creates a new POIXMLPropertiesTextExtractor, for the * same file that another TextExtractor is already * working on. */ public POIXMLPropertiesTextExtractor(POIXMLTextExtractor otherExtractor) : base(otherExtractor.Document) { } private void AppendIfPresent(StringBuilder text, String thing, bool value) { AppendIfPresent(text, thing, value.ToString()); } private void AppendIfPresent(StringBuilder text, String thing, int value) { AppendIfPresent(text, thing, value.ToString()); } private void AppendIfPresent(StringBuilder text, String thing, DateTime? value) { if (value == null) { return; } AppendIfPresent(text, thing, value.ToString()); } private void AppendIfPresent(StringBuilder text, String thing, String value) { if (value == null) { return; } text.Append(thing); text.Append(" = "); text.Append(value); text.Append("\n"); } /** * Returns the core document properties, eg author */ public String GetCorePropertiesText() { if (Document == null) { // event based extractor does not have a document return ""; } StringBuilder text = new StringBuilder(); PackagePropertiesPart props = Document.GetProperties().CoreProperties.GetUnderlyingProperties(); AppendIfPresent(text, "Category", props.GetCategoryProperty()); AppendIfPresent(text, "Category", props.GetCategoryProperty()); AppendIfPresent(text, "ContentStatus", props.GetContentStatusProperty()); AppendIfPresent(text, "ContentType", props.GetContentTypeProperty()); AppendIfPresent(text, "Created", props.GetCreatedProperty().Value); AppendIfPresent(text, "CreatedString", props.GetCreatedPropertyString()); AppendIfPresent(text, "Creator", props.GetCreatorProperty()); AppendIfPresent(text, "Description", props.GetDescriptionProperty()); AppendIfPresent(text, "Identifier", props.GetIdentifierProperty()); AppendIfPresent(text, "Keywords", props.GetKeywordsProperty()); AppendIfPresent(text, "Language", props.GetLanguageProperty()); AppendIfPresent(text, "LastModifiedBy", props.GetLastModifiedByProperty()); AppendIfPresent(text, "LastPrinted", props.GetLastPrintedProperty()); AppendIfPresent(text, "LastPrintedString", props.GetLastPrintedPropertyString()); AppendIfPresent(text, "Modified", props.GetModifiedProperty()); AppendIfPresent(text, "ModifiedString", props.GetModifiedPropertyString()); AppendIfPresent(text, "Revision", props.GetRevisionProperty()); AppendIfPresent(text, "Subject", props.GetSubjectProperty()); AppendIfPresent(text, "Title", props.GetTitleProperty()); AppendIfPresent(text, "Version", props.GetVersionProperty()); return text.ToString(); } /** * Returns the extended document properties, eg * application */ public String GetExtendedPropertiesText() { if (Document == null) { // event based extractor does not have a document return ""; } StringBuilder text = new StringBuilder(); CT_ExtendedProperties props = Document.GetProperties().ExtendedProperties.GetUnderlyingProperties(); AppendIfPresent(text, "Application", props.Application); AppendIfPresent(text, "AppVersion", props.AppVersion); AppendIfPresent(text, "Characters", props.Characters); AppendIfPresent(text, "CharactersWithSpaces", props.CharactersWithSpaces); AppendIfPresent(text, "Company", props.Company); AppendIfPresent(text, "HyperlinkBase", props.HyperlinkBase); AppendIfPresent(text, "HyperlinksChanged", props.HyperlinksChanged); AppendIfPresent(text, "Lines", props.Lines); AppendIfPresent(text, "LinksUpToDate", props.LinksUpToDate); AppendIfPresent(text, "Manager", props.Manager); AppendIfPresent(text, "Pages", props.Pages); AppendIfPresent(text, "Paragraphs", props.Paragraphs); AppendIfPresent(text, "PresentationFormat", props.PresentationFormat); AppendIfPresent(text, "Template", props.Template); AppendIfPresent(text, "TotalTime", props.TotalTime); return text.ToString(); } /** * Returns the custom document properties, if * there are any */ public String GetCustomPropertiesText() { if (Document == null) { // event based extractor does not have a document return ""; } StringBuilder text = new StringBuilder(); CT_CustomProperties props = Document.GetProperties().CustomProperties.GetUnderlyingProperties(); List<CT_Property> properties = props.GetPropertyList(); foreach (CT_Property property in properties) { String val = "(not implemented!)"; //val = property.Item.ToString(); if (property.IsSetLpwstr()) { val = property.GetLpwstr(); } else if (property.IsSetLpstr()) { val = property.GetLpstr(); } else if (property.IsSetDate()) { val = property.GetDate().ToString(); } else if (property.IsSetFiletime()) { val = property.GetFiletime().ToString(); } else if (property.IsSetBool()) { val = property.GetBool().ToString(); } // Integers else if (property.IsSetI1()) { val = property.GetI1().ToString(); } else if (property.IsSetI2()) { val = property.GetI2().ToString(); } else if (property.IsSetI4()) { val = property.GetI4().ToString(); } else if (property.IsSetI8()) { val = property.GetI8().ToString(); } else if (property.IsSetInt()) { val = property.GetInt().ToString(); } // Unsigned Integers else if (property.IsSetUi1()) { val = property.GetUi1().ToString(); } else if (property.IsSetUi2()) { val = property.GetUi2().ToString(); } else if (property.IsSetUi4()) { val = property.GetUi4().ToString(); } else if (property.IsSetUi8()) { val = property.GetUi8().ToString(); } else if (property.IsSetUint()) { val = property.GetUint().ToString(); } // Reals else if (property.IsSetR4()) { val = property.GetR4().ToString(); } else if (property.IsSetR8()) { val = property.GetR8().ToString(); } else if (property.IsSetDecimal()) { Decimal? d = property.GetDecimal(); if (d == null) { val = null; } else { val = d.ToString(); } } //else if (property.IsSetArray()) //{ // // TODO Fetch the array values and output //} //else if (property.IsSetVector()) //{ // // TODO Fetch the vector values and output //} //else if (property.IsSetBlob() || property.IsSetOblob()) //{ // // TODO Decode, if possible //} //else if (property.IsSetStream() || property.IsSetOstream() || // property.IsSetVstream()) //{ // // TODO Decode, if possible //} //else if (property.IsSetStorage() || property.IsSetOstorage()) //{ // // TODO Decode, if possible //} text.Append( property.name + " = " + val + "\n" ); } return text.ToString(); } public override String Text { get { return GetCorePropertiesText() + GetExtendedPropertiesText() + GetCustomPropertiesText(); } } public override POITextExtractor MetadataTextExtractor { get { throw new InvalidOperationException("You already have the Metadata Text Extractor, not recursing!"); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; using System.Diagnostics; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System { public struct Memory<T> { // The highest order bit of _index is used to discern whether _arrayOrOwnedMemory is an array or an owned memory // if (_index >> 31) == 1, object _arrayOrOwnedMemory is an OwnedMemory<T> // else, object _arrayOrOwnedMemory is a T[] private readonly object _arrayOrOwnedMemory; private readonly int _index; private readonly int _length; private const int RemoveOwnedFlagBitMask = 0x7FFFFFFF; /// <summary> /// Creates a new memory over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); _arrayOrOwnedMemory = array; _index = 0; _length = array.Length; } /// <summary> /// Creates a new memory over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the memory.</param> /// <param name="length">The number of items in the memory.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array, int start, int length) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); _arrayOrOwnedMemory = array; _index = start; _length = length; } // Constructor for internal use only. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(OwnedMemory<T> owner, int index, int length) { if (owner == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.ownedMemory); if (index < 0 || length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(); _arrayOrOwnedMemory = owner; _index = index | (1 << 31); // Before using _index, check if _index < 0, then 'and' it with RemoveOwnedFlagBitMask _length = length; } /// <summary> /// Defines an implicit conversion of an array to a <see cref="Memory{T}"/> /// </summary> public static implicit operator Memory<T>(T[] array) => new Memory<T>(array); /// <summary> /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/> /// </summary> public static implicit operator Memory<T>(ArraySegment<T> arraySegment) => new Memory<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count); /// <summary> /// Defines an implicit conversion of a <see cref="Memory{T}"/> to a <see cref="ReadOnlyMemory{T}"/> /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) { if (memory._index < 0) return new ReadOnlyMemory<T>((OwnedMemory<T>)memory._arrayOrOwnedMemory, memory._index & RemoveOwnedFlagBitMask, memory._length); return new ReadOnlyMemory<T>((T[])memory._arrayOrOwnedMemory, memory._index, memory._length); } /// <summary> /// Returns an empty <see cref="Memory{T}"/> /// </summary> public static Memory<T> Empty { get; } = Array.Empty<T>(); /// <summary> /// The number of items in the memory. /// </summary> public int Length => _length; /// <summary> /// Returns true if Length is 0. /// </summary> public bool IsEmpty => _length == 0; /// <summary> /// Forms a slice out of the given memory, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start) { if ((uint)start > (uint)_length) ThrowHelper.ThrowArgumentOutOfRangeException(); if (_index < 0) return new Memory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, _length - start); return new Memory<T>((T[])_arrayOrOwnedMemory, _index + start, _length - start); } /// <summary> /// Forms a slice out of the given memory, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); if (_index < 0) return new Memory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, length); return new Memory<T>((T[])_arrayOrOwnedMemory, _index + start, length); } /// <summary> /// Returns a span from the memory. /// </summary> public Span<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_index < 0) return ((OwnedMemory<T>)_arrayOrOwnedMemory).AsSpan().Slice(_index & RemoveOwnedFlagBitMask, _length); return new Span<T>((T[])_arrayOrOwnedMemory, _index, _length); } } public unsafe MemoryHandle Retain(bool pin = false) { MemoryHandle memoryHandle; if (pin) { if (_index < 0) { memoryHandle = ((OwnedMemory<T>)_arrayOrOwnedMemory).Pin(); } else { var array = (T[])_arrayOrOwnedMemory; var handle = GCHandle.Alloc(array, GCHandleType.Pinned); void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref array.GetRawSzArrayData()), _index); memoryHandle = new MemoryHandle(null, pointer, handle); } } else { if (_index < 0) { ((OwnedMemory<T>)_arrayOrOwnedMemory).Retain(); memoryHandle = new MemoryHandle((OwnedMemory<T>)_arrayOrOwnedMemory); } else { memoryHandle = new MemoryHandle(null); } } return memoryHandle; } /// <summary> /// Get an array segment from the underlying memory. /// If unable to get the array segment, return false with a default array segment. /// </summary> public bool TryGetArray(out ArraySegment<T> arraySegment) { if (_index < 0) { if (((OwnedMemory<T>)_arrayOrOwnedMemory).TryGetArray(out var segment)) { arraySegment = new ArraySegment<T>(segment.Array, segment.Offset + (_index & RemoveOwnedFlagBitMask), _length); return true; } } else { arraySegment = new ArraySegment<T>((T[])_arrayOrOwnedMemory, _index, _length); return true; } arraySegment = default(ArraySegment<T>); return false; } /// <summary> /// Copies the contents from the memory into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> public T[] ToArray() => Span.ToArray(); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is ReadOnlyMemory<T>) { return ((ReadOnlyMemory<T>)obj).Equals(this); } else if (obj is Memory<T> memory) { return Equals(memory); } else { return false; } } /// <summary> /// Returns true if the memory points to the same array and has the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public bool Equals(Memory<T> other) { return _arrayOrOwnedMemory == other._arrayOrOwnedMemory && _index == other._index && _length == other._length; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return CombineHashCodes(_arrayOrOwnedMemory.GetHashCode(), (_index & RemoveOwnedFlagBitMask).GetHashCode(), _length.GetHashCode()); } private static int CombineHashCodes(int left, int right) { return ((left << 5) + left) ^ right; } private static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsRequiredOptional { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class ImplicitModelExtensions { /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='pathParameter'> /// </param> public static Error GetRequiredPath(this IImplicitModel operations, string pathParameter) { return Task.Factory.StartNew(s => ((IImplicitModel)s).GetRequiredPathAsync(pathParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='pathParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> GetRequiredPathAsync( this IImplicitModel operations, string pathParameter, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<Error> result = await operations.GetRequiredPathWithHttpMessagesAsync(pathParameter, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queryParameter'> /// </param> public static void PutOptionalQuery(this IImplicitModel operations, string queryParameter = default(string)) { Task.Factory.StartNew(s => ((IImplicitModel)s).PutOptionalQueryAsync(queryParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queryParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutOptionalQueryAsync( this IImplicitModel operations, string queryParameter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutOptionalQueryWithHttpMessagesAsync(queryParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test implicitly optional header parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queryParameter'> /// </param> public static void PutOptionalHeader(this IImplicitModel operations, string queryParameter = default(string)) { Task.Factory.StartNew(s => ((IImplicitModel)s).PutOptionalHeaderAsync(queryParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly optional header parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queryParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutOptionalHeaderAsync( this IImplicitModel operations, string queryParameter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutOptionalHeaderWithHttpMessagesAsync(queryParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test implicitly optional body parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PutOptionalBody(this IImplicitModel operations, string bodyParameter = default(string)) { Task.Factory.StartNew(s => ((IImplicitModel)s).PutOptionalBodyAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly optional body parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutOptionalBodyAsync( this IImplicitModel operations, string bodyParameter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutOptionalBodyWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error GetRequiredGlobalPath(this IImplicitModel operations) { return Task.Factory.StartNew(s => ((IImplicitModel)s).GetRequiredGlobalPathAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> GetRequiredGlobalPathAsync( this IImplicitModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<Error> result = await operations.GetRequiredGlobalPathWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Test implicitly required query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error GetRequiredGlobalQuery(this IImplicitModel operations) { return Task.Factory.StartNew(s => ((IImplicitModel)s).GetRequiredGlobalQueryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly required query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> GetRequiredGlobalQueryAsync( this IImplicitModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<Error> result = await operations.GetRequiredGlobalQueryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error GetOptionalGlobalQuery(this IImplicitModel operations) { return Task.Factory.StartNew(s => ((IImplicitModel)s).GetOptionalGlobalQueryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> GetOptionalGlobalQueryAsync( this IImplicitModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<Error> result = await operations.GetOptionalGlobalQueryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Xunit; namespace System.Threading.Tasks.Tests { public class ValueTaskTests { [Fact] public void DefaultValueTask_ValueType_DefaultValue() { Assert.True(default(ValueTask<int>).IsCompleted); Assert.True(default(ValueTask<int>).IsCompletedSuccessfully); Assert.False(default(ValueTask<int>).IsFaulted); Assert.False(default(ValueTask<int>).IsCanceled); Assert.Equal(0, default(ValueTask<int>).Result); Assert.True(default(ValueTask<string>).IsCompleted); Assert.True(default(ValueTask<string>).IsCompletedSuccessfully); Assert.False(default(ValueTask<string>).IsFaulted); Assert.False(default(ValueTask<string>).IsCanceled); Assert.Equal(null, default(ValueTask<string>).Result); } [Fact] public void CreateFromValue_IsRanToCompletion() { ValueTask<int> t = new ValueTask<int>(42); Assert.True(t.IsCompleted); Assert.True(t.IsCompletedSuccessfully); Assert.False(t.IsFaulted); Assert.False(t.IsCanceled); Assert.Equal(42, t.Result); } [Fact] public void CreateFromCompletedTask_IsRanToCompletion() { ValueTask<int> t = new ValueTask<int>(Task.FromResult(42)); Assert.True(t.IsCompleted); Assert.True(t.IsCompletedSuccessfully); Assert.False(t.IsFaulted); Assert.False(t.IsCanceled); Assert.Equal(42, t.Result); } [Fact] public void CreateFromNotCompletedTask_IsNotRanToCompletion() { var tcs = new TaskCompletionSource<int>(); ValueTask<int> t = new ValueTask<int>(tcs.Task); Assert.False(t.IsCompleted); Assert.False(t.IsCompletedSuccessfully); Assert.False(t.IsFaulted); Assert.False(t.IsCanceled); tcs.SetResult(42); Assert.Equal(42, t.Result); Assert.True(t.IsCompleted); Assert.True(t.IsCompletedSuccessfully); Assert.False(t.IsFaulted); Assert.False(t.IsCanceled); } [Fact] public void CreateFromNullTask_Throws() { Assert.Throws<ArgumentNullException>(() => new ValueTask<int>((Task<int>)null)); Assert.Throws<ArgumentNullException>(() => new ValueTask<string>((Task<string>)null)); } [Fact] public void CreateFromTask_AsTaskIdempotent() { Task<int> source = Task.FromResult(42); ValueTask<int> t = new ValueTask<int>(source); Assert.Same(source, t.AsTask()); Assert.Same(t.AsTask(), t.AsTask()); } [Fact] public void CreateFromValue_AsTaskNotIdempotent() { ValueTask<int> t = new ValueTask<int>(42); Assert.NotSame(Task.FromResult(42), t.AsTask()); Assert.NotSame(t.AsTask(), t.AsTask()); } [Fact] public async Task CreateFromValue_Await() { ValueTask<int> t = new ValueTask<int>(42); Assert.Equal(42, await t); Assert.Equal(42, await t.ConfigureAwait(false)); Assert.Equal(42, await t.ConfigureAwait(true)); } [Fact] public async Task CreateFromTask_Await_Normal() { Task<int> source = Task.Delay(1).ContinueWith(_ => 42); ValueTask<int> t = new ValueTask<int>(source); Assert.Equal(42, await t); } [Fact] public async Task CreateFromTask_Await_ConfigureAwaitFalse() { Task<int> source = Task.Delay(1).ContinueWith(_ => 42); ValueTask<int> t = new ValueTask<int>(source); Assert.Equal(42, await t.ConfigureAwait(false)); } [Fact] public async Task CreateFromTask_Await_ConfigureAwaitTrue() { Task<int> source = Task.Delay(1).ContinueWith(_ => 42); ValueTask<int> t = new ValueTask<int>(source); Assert.Equal(42, await t.ConfigureAwait(true)); } [Fact] public async Task Awaiter_OnCompleted() { // Since ValueTask implements both OnCompleted and UnsafeOnCompleted, // OnCompleted typically won't be used by await, so we add an explicit test // for it here. ValueTask<int> t = new ValueTask<int>(42); var tcs = new TaskCompletionSource<bool>(); t.GetAwaiter().OnCompleted(() => tcs.SetResult(true)); await tcs.Task; } [Theory] [InlineData(true)] [InlineData(false)] public async Task ConfiguredAwaiter_OnCompleted(bool continueOnCapturedContext) { // Since ValueTask implements both OnCompleted and UnsafeOnCompleted, // OnCompleted typically won't be used by await, so we add an explicit test // for it here. ValueTask<int> t = new ValueTask<int>(42); var tcs = new TaskCompletionSource<bool>(); t.ConfigureAwait(continueOnCapturedContext).GetAwaiter().OnCompleted(() => tcs.SetResult(true)); await tcs.Task; } [Fact] public async Task Awaiter_ContinuesOnCapturedContext() { await Task.Run(() => { var tsc = new TrackingSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(tsc); try { ValueTask<int> t = new ValueTask<int>(42); var mres = new ManualResetEventSlim(); t.GetAwaiter().OnCompleted(() => mres.Set()); Assert.True(mres.Wait(10000)); Assert.Equal(1, tsc.Posts); } finally { SynchronizationContext.SetSynchronizationContext(null); } }); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ConfiguredAwaiter_ContinuesOnCapturedContext(bool continueOnCapturedContext) { await Task.Run(() => { var tsc = new TrackingSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(tsc); try { ValueTask<int> t = new ValueTask<int>(42); var mres = new ManualResetEventSlim(); t.ConfigureAwait(continueOnCapturedContext).GetAwaiter().OnCompleted(() => mres.Set()); Assert.True(mres.Wait(10000)); Assert.Equal(continueOnCapturedContext ? 1 : 0, tsc.Posts); } finally { SynchronizationContext.SetSynchronizationContext(null); } }); } [Fact] public void GetHashCode_ContainsResult() { ValueTask<int> t = new ValueTask<int>(42); Assert.Equal(t.Result.GetHashCode(), t.GetHashCode()); } [Fact] public void GetHashCode_ContainsTask() { ValueTask<string> t = new ValueTask<string>(Task.FromResult("42")); Assert.Equal(t.AsTask().GetHashCode(), t.GetHashCode()); } [Fact] public void GetHashCode_ContainsNull() { ValueTask<string> t = new ValueTask<string>((string)null); Assert.Equal(0, t.GetHashCode()); } [Fact] public void OperatorEquals() { Assert.True(new ValueTask<int>(42) == new ValueTask<int>(42)); Assert.False(new ValueTask<int>(42) == new ValueTask<int>(43)); Assert.True(new ValueTask<string>("42") == new ValueTask<string>("42")); Assert.True(new ValueTask<string>((string)null) == new ValueTask<string>((string)null)); Assert.False(new ValueTask<string>("42") == new ValueTask<string>((string)null)); Assert.False(new ValueTask<string>((string)null) == new ValueTask<string>("42")); Assert.False(new ValueTask<int>(42) == new ValueTask<int>(Task.FromResult(42))); Assert.False(new ValueTask<int>(Task.FromResult(42)) == new ValueTask<int>(42)); } [Fact] public void OperatorNotEquals() { Assert.False(new ValueTask<int>(42) != new ValueTask<int>(42)); Assert.True(new ValueTask<int>(42) != new ValueTask<int>(43)); Assert.False(new ValueTask<string>("42") != new ValueTask<string>("42")); Assert.False(new ValueTask<string>((string)null) != new ValueTask<string>((string)null)); Assert.True(new ValueTask<string>("42") != new ValueTask<string>((string)null)); Assert.True(new ValueTask<string>((string)null) != new ValueTask<string>("42")); Assert.True(new ValueTask<int>(42) != new ValueTask<int>(Task.FromResult(42))); Assert.True(new ValueTask<int>(Task.FromResult(42)) != new ValueTask<int>(42)); } [Fact] public void Equals_ValueTask() { Assert.True(new ValueTask<int>(42).Equals(new ValueTask<int>(42))); Assert.False(new ValueTask<int>(42).Equals(new ValueTask<int>(43))); Assert.True(new ValueTask<string>("42").Equals(new ValueTask<string>("42"))); Assert.True(new ValueTask<string>((string)null).Equals(new ValueTask<string>((string)null))); Assert.False(new ValueTask<string>("42").Equals(new ValueTask<string>((string)null))); Assert.False(new ValueTask<string>((string)null).Equals(new ValueTask<string>("42"))); Assert.False(new ValueTask<int>(42).Equals(new ValueTask<int>(Task.FromResult(42)))); Assert.False(new ValueTask<int>(Task.FromResult(42)).Equals(new ValueTask<int>(42))); } [Fact] public void Equals_Object() { Assert.True(new ValueTask<int>(42).Equals((object)new ValueTask<int>(42))); Assert.False(new ValueTask<int>(42).Equals((object)new ValueTask<int>(43))); Assert.True(new ValueTask<string>("42").Equals((object)new ValueTask<string>("42"))); Assert.True(new ValueTask<string>((string)null).Equals((object)new ValueTask<string>((string)null))); Assert.False(new ValueTask<string>("42").Equals((object)new ValueTask<string>((string)null))); Assert.False(new ValueTask<string>((string)null).Equals((object)new ValueTask<string>("42"))); Assert.False(new ValueTask<int>(42).Equals((object)new ValueTask<int>(Task.FromResult(42)))); Assert.False(new ValueTask<int>(Task.FromResult(42)).Equals((object)new ValueTask<int>(42))); Assert.False(new ValueTask<int>(42).Equals((object)null)); Assert.False(new ValueTask<int>(42).Equals(new object())); Assert.False(new ValueTask<int>(42).Equals((object)42)); } [Fact] public void ToString_Success() { Assert.Equal("Hello", new ValueTask<string>("Hello").ToString()); Assert.Equal("Hello", new ValueTask<string>(Task.FromResult("Hello")).ToString()); Assert.Equal("42", new ValueTask<int>(42).ToString()); Assert.Equal("42", new ValueTask<int>(Task.FromResult(42)).ToString()); Assert.Same(string.Empty, new ValueTask<string>(string.Empty).ToString()); Assert.Same(string.Empty, new ValueTask<string>(Task.FromResult(string.Empty)).ToString()); Assert.Same(string.Empty, new ValueTask<string>(Task.FromException<string>(new InvalidOperationException())).ToString()); Assert.Same(string.Empty, new ValueTask<string>(Task.FromException<string>(new OperationCanceledException())).ToString()); Assert.Same(string.Empty, new ValueTask<string>(Task.FromCanceled<string>(new CancellationToken(true))).ToString()); Assert.Equal("0", default(ValueTask<int>).ToString()); Assert.Same(string.Empty, default(ValueTask<string>).ToString()); Assert.Same(string.Empty, new ValueTask<string>((string)null).ToString()); Assert.Same(string.Empty, new ValueTask<string>(Task.FromResult<string>(null)).ToString()); Assert.Same(string.Empty, new ValueTask<DateTime>(new TaskCompletionSource<DateTime>().Task).ToString()); } [Theory] [InlineData(typeof(ValueTask<>))] [InlineData(typeof(ValueTask<int>))] [InlineData(typeof(ValueTask<string>))] public void AsyncBuilderAttribute_ValueTaskAttributed(Type valueTaskType) { CustomAttributeData aba = valueTaskType.GetTypeInfo().CustomAttributes.Single( attr => attr.AttributeType.FullName == "System.Runtime.CompilerServices.AsyncBuilderAttribute"); Assert.True(aba.AttributeType.GetTypeInfo().IsNotPublic); Assert.Equal(typeof(AsyncValueTaskMethodBuilder<>), aba.ConstructorArguments[0].Value); } private sealed class TrackingSynchronizationContext : SynchronizationContext { internal int Posts { get; set; } public override void Post(SendOrPostCallback d, object state) { Posts++; base.Post(d, state); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Runtime; namespace System.ServiceModel.Channels { // code that pools items and closes/aborts them as necessary. // shared by IConnection and IChannel users public abstract class CommunicationPool<TKey, TItem> where TKey : class where TItem : class { private Dictionary<TKey, EndpointConnectionPool> _endpointPools; private int _openCount; // need to make sure we prune over a certain number of endpoint pools private int _pruneAccrual; private const int pruneThreshold = 30; protected CommunicationPool(int maxCount) { MaxIdleConnectionPoolCount = maxCount; _endpointPools = new Dictionary<TKey, EndpointConnectionPool>(); _openCount = 1; } public int MaxIdleConnectionPoolCount { get; } protected object ThisLock { get { return this; } } protected abstract void AbortItem(TItem item); protected abstract void CloseItem(TItem item, TimeSpan timeout); protected abstract void CloseItemAsync(TItem item, TimeSpan timeout); protected abstract TKey GetPoolKey(EndpointAddress address, Uri via); protected virtual EndpointConnectionPool CreateEndpointConnectionPool(TKey key) { return new EndpointConnectionPool(this, key); } public bool Close(TimeSpan timeout) { lock (ThisLock) { if (_openCount <= 0) { return true; } _openCount--; if (_openCount == 0) { OnClose(timeout); return true; } return false; } } private List<TItem> PruneIfNecessary() { List<TItem> itemsToClose = null; _pruneAccrual++; if (_pruneAccrual > pruneThreshold) { _pruneAccrual = 0; itemsToClose = new List<TItem>(); // first prune the connection pool contents foreach (EndpointConnectionPool pool in _endpointPools.Values) { pool.Prune(itemsToClose); } // figure out which connection pools are now empty List<TKey> endpointKeysToRemove = null; foreach (KeyValuePair<TKey, EndpointConnectionPool> poolEntry in _endpointPools) { if (poolEntry.Value.CloseIfEmpty()) { if (endpointKeysToRemove == null) { endpointKeysToRemove = new List<TKey>(); } endpointKeysToRemove.Add(poolEntry.Key); } } // and then prune the connection pools themselves if (endpointKeysToRemove != null) { for (int i = 0; i < endpointKeysToRemove.Count; i++) { _endpointPools.Remove(endpointKeysToRemove[i]); } } } return itemsToClose; } private EndpointConnectionPool GetEndpointPool(TKey key, TimeSpan timeout) { EndpointConnectionPool result = null; List<TItem> itemsToClose = null; lock (ThisLock) { if (!_endpointPools.TryGetValue(key, out result)) { itemsToClose = PruneIfNecessary(); result = CreateEndpointConnectionPool(key); _endpointPools.Add(key, result); } } Contract.Assert(result != null, "EndpointPool must be non-null at this point"); if (itemsToClose != null && itemsToClose.Count > 0) { // allocate half the remaining timeout for our graceful shutdowns TimeoutHelper timeoutHelper = new TimeoutHelper(TimeoutHelper.Divide(timeout, 2)); for (int i = 0; i < itemsToClose.Count; i++) { result.CloseIdleConnection(itemsToClose[i], timeoutHelper.RemainingTime()); } } return result; } public bool TryOpen() { lock (ThisLock) { if (_openCount <= 0) { // can't reopen connection pools since the registry purges them on close return false; } else { _openCount++; return true; } } } protected virtual void OnClosed() { } private void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); foreach (EndpointConnectionPool pool in _endpointPools.Values) { try { pool.Close(timeoutHelper.RemainingTime()); } catch (CommunicationException) { } catch (TimeoutException exception) { if (WcfEventSource.Instance.CloseTimeoutIsEnabled()) { WcfEventSource.Instance.CloseTimeout(exception.Message); } } } _endpointPools.Clear(); } public void AddConnection(TKey key, TItem connection, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); EndpointConnectionPool endpointPool = GetEndpointPool(key, timeoutHelper.RemainingTime()); endpointPool.AddConnection(connection, timeoutHelper.RemainingTime()); } public TItem TakeConnection(EndpointAddress address, Uri via, TimeSpan timeout, out TKey key) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); key = GetPoolKey(address, via); EndpointConnectionPool endpointPool = GetEndpointPool(key, timeoutHelper.RemainingTime()); return endpointPool.TakeConnection(timeoutHelper.RemainingTime()); } public void ReturnConnection(TKey key, TItem connection, bool connectionIsStillGood, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); EndpointConnectionPool endpointPool = GetEndpointPool(key, timeoutHelper.RemainingTime()); endpointPool.ReturnConnection(connection, connectionIsStillGood, timeoutHelper.RemainingTime()); } // base class for our collection of Idle connections protected abstract class IdleConnectionPool { public abstract int Count { get; } public abstract bool Add(TItem item); public abstract bool Return(TItem item); public abstract TItem Take(out bool closeItem); } protected class EndpointConnectionPool { private List<TItem> _busyConnections; private bool _closed; private IdleConnectionPool _idleConnections; public EndpointConnectionPool(CommunicationPool<TKey, TItem> parent, TKey key) { Key = key; Parent = parent; _busyConnections = new List<TItem>(); } protected TKey Key { get; } private IdleConnectionPool IdleConnections { get { if (_idleConnections == null) { _idleConnections = GetIdleConnectionPool(); } return _idleConnections; } } protected CommunicationPool<TKey, TItem> Parent { get; } protected object ThisLock { get { return this; } } // close down the pool if empty public bool CloseIfEmpty() { lock (ThisLock) { if (!_closed) { if (_busyConnections.Count > 0) { return false; } if (_idleConnections != null && _idleConnections.Count > 0) { return false; } _closed = true; } } return true; } protected virtual void AbortItem(TItem item) { Parent.AbortItem(item); } protected virtual void CloseItem(TItem item, TimeSpan timeout) { Parent.CloseItem(item, timeout); } protected virtual void CloseItemAsync(TItem item, TimeSpan timeout) { Parent.CloseItemAsync(item, timeout); } public void Abort() { if (_closed) { return; } List<TItem> idleItemsToClose = null; lock (ThisLock) { if (_closed) { return; } _closed = true; idleItemsToClose = SnapshotIdleConnections(); } AbortConnections(idleItemsToClose); } public void Close(TimeSpan timeout) { List<TItem> itemsToClose = null; lock (ThisLock) { if (_closed) { return; } _closed = true; itemsToClose = SnapshotIdleConnections(); } try { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); for (int i = 0; i < itemsToClose.Count; i++) { CloseItem(itemsToClose[i], timeoutHelper.RemainingTime()); } itemsToClose.Clear(); } finally { AbortConnections(itemsToClose); } } private void AbortConnections(List<TItem> idleItemsToClose) { for (int i = 0; i < idleItemsToClose.Count; i++) { AbortItem(idleItemsToClose[i]); } for (int i = 0; i < _busyConnections.Count; i++) { AbortItem(_busyConnections[i]); } _busyConnections.Clear(); } // must call under lock (ThisLock) since we are calling IdleConnections.Take() private List<TItem> SnapshotIdleConnections() { List<TItem> itemsToClose = new List<TItem>(); bool dummy; for (; ; ) { TItem item = IdleConnections.Take(out dummy); if (item == null) { break; } itemsToClose.Add(item); } return itemsToClose; } public void AddConnection(TItem connection, TimeSpan timeout) { bool closeConnection = false; lock (ThisLock) { if (!_closed) { if (!IdleConnections.Add(connection)) { closeConnection = true; } } else { closeConnection = true; } } if (closeConnection) { CloseIdleConnection(connection, timeout); } } protected virtual IdleConnectionPool GetIdleConnectionPool() { return new PoolIdleConnectionPool(Parent.MaxIdleConnectionPoolCount); } public virtual void Prune(List<TItem> itemsToClose) { } public TItem TakeConnection(TimeSpan timeout) { TItem item = null; List<TItem> itemsToClose = null; lock (ThisLock) { if (_closed) { return null; } bool closeItem; while (true) { item = IdleConnections.Take(out closeItem); if (item == null) { break; } if (!closeItem) { _busyConnections.Add(item); break; } if (itemsToClose == null) { itemsToClose = new List<TItem>(); } itemsToClose.Add(item); } } // cleanup any stale items accrued from IdleConnections if (itemsToClose != null) { // and only allocate half the timeout passed in for our graceful shutdowns TimeoutHelper timeoutHelper = new TimeoutHelper(TimeoutHelper.Divide(timeout, 2)); for (int i = 0; i < itemsToClose.Count; i++) { CloseIdleConnection(itemsToClose[i], timeoutHelper.RemainingTime()); } } if (WcfEventSource.Instance.ConnectionPoolMissIsEnabled()) { if (item == null && _busyConnections != null) { WcfEventSource.Instance.ConnectionPoolMiss(Key != null ? Key.ToString() : string.Empty, _busyConnections.Count); } } return item; } public void ReturnConnection(TItem connection, bool connectionIsStillGood, TimeSpan timeout) { bool closeConnection = false; bool abortConnection = false; lock (ThisLock) { if (!_closed) { if (_busyConnections.Remove(connection) && connectionIsStillGood) { if (!IdleConnections.Return(connection)) { closeConnection = true; } } else { abortConnection = true; } } else { abortConnection = true; } } if (closeConnection) { CloseIdleConnection(connection, timeout); } else if (abortConnection) { AbortItem(connection); OnConnectionAborted(); } } public void CloseIdleConnection(TItem connection, TimeSpan timeout) { bool throwing = true; try { CloseItemAsync(connection, timeout); throwing = false; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } } finally { if (throwing) { AbortItem(connection); } } } protected virtual void OnConnectionAborted() { } protected class PoolIdleConnectionPool : IdleConnectionPool { private Pool<TItem> _idleConnections; private int _maxCount; public PoolIdleConnectionPool(int maxCount) { _idleConnections = new Pool<TItem>(maxCount); _maxCount = maxCount; } public override int Count { get { return _idleConnections.Count; } } public override bool Add(TItem connection) { return ReturnToPool(connection); } public override bool Return(TItem connection) { return ReturnToPool(connection); } private bool ReturnToPool(TItem connection) { bool result = _idleConnections.Return(connection); if (!result) { if (WcfEventSource.Instance.MaxOutboundConnectionsPerEndpointExceededIsEnabled()) { WcfEventSource.Instance.MaxOutboundConnectionsPerEndpointExceeded(SR.Format(SR.TraceCodeConnectionPoolMaxOutboundConnectionsPerEndpointQuotaReached, _maxCount)); } } else if (WcfEventSource.Instance.OutboundConnectionsPerEndpointRatioIsEnabled()) { WcfEventSource.Instance.OutboundConnectionsPerEndpointRatio(_idleConnections.Count, _maxCount); } return result; } public override TItem Take(out bool closeItem) { closeItem = false; TItem ret = _idleConnections.Take(); if (WcfEventSource.Instance.OutboundConnectionsPerEndpointRatioIsEnabled()) { WcfEventSource.Instance.OutboundConnectionsPerEndpointRatio(_idleConnections.Count, _maxCount); } return ret; } } } } // all our connection pools support Idling out of connections and lease timeout // (though Named Pipes doesn't leverage the lease timeout) public abstract class ConnectionPool : IdlingCommunicationPool<string, IConnection> { private int _connectionBufferSize; private TimeSpan _maxOutputDelay; protected ConnectionPool(IConnectionOrientedTransportChannelFactorySettings settings, TimeSpan leaseTimeout) : base(settings.MaxOutboundConnectionsPerEndpoint, settings.IdleTimeout, leaseTimeout) { _connectionBufferSize = settings.ConnectionBufferSize; _maxOutputDelay = settings.MaxOutputDelay; Name = settings.ConnectionPoolGroupName; } public string Name { get; } protected override void AbortItem(IConnection item) { item.Abort(); } protected override void CloseItem(IConnection item, TimeSpan timeout) { item.Close(timeout, false); } protected override void CloseItemAsync(IConnection item, TimeSpan timeout) { item.Close(timeout, true); } public virtual bool IsCompatible(IConnectionOrientedTransportChannelFactorySettings settings) { return ( (Name == settings.ConnectionPoolGroupName) && (_connectionBufferSize == settings.ConnectionBufferSize) && (MaxIdleConnectionPoolCount == settings.MaxOutboundConnectionsPerEndpoint) && (IdleTimeout == settings.IdleTimeout) && (_maxOutputDelay == settings.MaxOutputDelay) ); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.ExceptionServices; using Microsoft.AspNetCore.Hosting.Builder; using Microsoft.AspNetCore.Hosting.Internal; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.ObjectPool; using Microsoft.Extensions.PlatformAbstractions; namespace Microsoft.AspNetCore.Hosting { /// <summary> /// A builder for <see cref="IWebHost"/> /// </summary> public class WebHostBuilder : IWebHostBuilder { private readonly IHostingEnvironment _hostingEnvironment; private readonly List<Action<IServiceCollection>> _configureServicesDelegates; private readonly List<Action<ILoggerFactory>> _configureLoggingDelegates; private IConfiguration _config = new ConfigurationBuilder().AddInMemoryCollection().Build(); private ILoggerFactory _loggerFactory; private WebHostOptions _options; /// <summary> /// Initializes a new instance of the <see cref="WebHostBuilder"/> class. /// </summary> public WebHostBuilder() { _hostingEnvironment = new HostingEnvironment(); _configureServicesDelegates = new List<Action<IServiceCollection>>(); _configureLoggingDelegates = new List<Action<ILoggerFactory>>(); // This may end up storing null, but that's indistinguishable from not adding it. UseSetting(WebHostDefaults.EnvironmentKey, Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") // Legacy keys, never remove these. ?? Environment.GetEnvironmentVariable("Hosting:Environment") ?? Environment.GetEnvironmentVariable("ASPNET_ENV")); if (Environment.GetEnvironmentVariable("Hosting:Environment") != null) { } if (Environment.GetEnvironmentVariable("ASPNET_ENV") != null) { } } /// <summary> /// Add or replace a setting in the configuration. /// </summary> /// <param name="key">The key of the setting to add or replace.</param> /// <param name="value">The value of the setting to add or replace.</param> /// <returns>The <see cref="IWebHostBuilder"/>.</returns> public IWebHostBuilder UseSetting(string key, string value) { _config[key] = value; return this; } /// <summary> /// Get the setting value from the configuration. /// </summary> /// <param name="key">The key of the setting to look up.</param> /// <returns>The value the setting currently contains.</returns> public string GetSetting(string key) { return _config[key]; } /// <summary> /// Specify the <see cref="ILoggerFactory"/> to be used by the web host. /// </summary> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/> to be used.</param> /// <returns>The <see cref="IWebHostBuilder"/>.</returns> public IWebHostBuilder UseLoggerFactory(ILoggerFactory loggerFactory) { if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } _loggerFactory = loggerFactory; return this; } /// <summary> /// Adds a delegate for configuring additional services for the host or web application. This may be called /// multiple times. /// </summary> /// <param name="configureServices">A delegate for configuring the <see cref="IServiceCollection"/>.</param> /// <returns>The <see cref="IWebHostBuilder"/>.</returns> public IWebHostBuilder ConfigureServices(Action<IServiceCollection> configureServices) { if (configureServices == null) { throw new ArgumentNullException(nameof(configureServices)); } _configureServicesDelegates.Add(configureServices); return this; } /// <summary> /// Adds a delegate for configuring the provided <see cref="ILoggerFactory"/>. This may be called multiple times. /// </summary> /// <param name="configureLogging">The delegate that configures the <see cref="ILoggerFactory"/>.</param> /// <returns>The <see cref="IWebHostBuilder"/>.</returns> public IWebHostBuilder ConfigureLogging(Action<ILoggerFactory> configureLogging) { if (configureLogging == null) { throw new ArgumentNullException(nameof(configureLogging)); } _configureLoggingDelegates.Add(configureLogging); return this; } /// <summary> /// Builds the required services and an <see cref="IWebHost"/> which hosts a web application. /// </summary> public IWebHost Build() { var hostingServices = BuildHostingServices(); var hostingContainer = hostingServices.BuildServiceProvider(); var host = new WebHost(hostingServices, hostingContainer, _options, _config); host.Initialize(); return host; } private IServiceCollection BuildHostingServices() { _options = new WebHostOptions(_config); var appEnvironment = PlatformServices.Default.Application; var contentRootPath = ResolveContentRootPath(_options.ContentRootPath, appEnvironment.ApplicationBasePath); var applicationName = _options.ApplicationName ?? appEnvironment.ApplicationName; // Initialize the hosting environment _hostingEnvironment.Initialize(applicationName, contentRootPath, _options); var services = new ServiceCollection(); services.AddSingleton(_hostingEnvironment); if (_loggerFactory == null) { _loggerFactory = new LoggerFactory(); } foreach (var configureLogging in _configureLoggingDelegates) { configureLogging(_loggerFactory); } //The configured ILoggerFactory is added as a singleton here. AddLogging below will not add an additional one. services.AddSingleton(_loggerFactory); //This is required to add ILogger of T. services.AddLogging(); services.AddTransient<IApplicationBuilderFactory, ApplicationBuilderFactory>(); services.AddTransient<IHttpContextFactory, HttpContextFactory>(); services.AddOptions(); var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore"); services.AddSingleton<DiagnosticSource>(diagnosticSource); services.AddSingleton<DiagnosticListener>(diagnosticSource); // Conjure up a RequestServices services.AddTransient<IStartupFilter, AutoRequestServicesStartupFilter>(); // Ensure object pooling is available everywhere. services.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>(); if (!string.IsNullOrEmpty(_options.ServerAssembly)) { // Add the server try { var serverType = ServerLoader.ResolveServerType(_options.ServerAssembly); services.AddSingleton(typeof(IServer), serverType); } catch (Exception ex) { var capture = ExceptionDispatchInfo.Capture(ex); services.AddSingleton<IServer>(_ => { capture.Throw(); return null; }); } } if (!string.IsNullOrEmpty(_options.StartupAssembly)) { try { var startupType = StartupLoader.FindStartupType(_options.StartupAssembly, _hostingEnvironment.EnvironmentName); if (typeof(IStartup).GetTypeInfo().IsAssignableFrom(startupType.GetTypeInfo())) { services.AddSingleton(typeof(IStartup), startupType); } else { services.AddSingleton(typeof(IStartup), sp => { var hostingEnvironment = sp.GetRequiredService<IHostingEnvironment>(); var methods = StartupLoader.LoadMethods(sp, startupType, hostingEnvironment.EnvironmentName); return new ConventionBasedStartup(methods); }); } } catch (Exception ex) { var capture = ExceptionDispatchInfo.Capture(ex); services.AddSingleton<IStartup>(_ => { capture.Throw(); return null; }); } } foreach (var configureServices in _configureServicesDelegates) { configureServices(services); } return services; } private string ResolveContentRootPath(string contentRootPath, string basePath) { if (string.IsNullOrEmpty(contentRootPath)) { return basePath; } if (Path.IsPathRooted(contentRootPath)) { return contentRootPath; } return Path.Combine(Path.GetFullPath(basePath), contentRootPath); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Xunit; using Xunit.Abstractions; using Xunit.Sdk; namespace StaticTestGenerator { /// <summary> /// Utility that reflects over an xunit test assembly and generates a static .cs/.csproj containing invocations /// of all of the tests, with minimal additional ceremony and no use of reflection. /// </summary> public static class Program { /// <summary>Entrypoint to the utility.</summary> /// <param name="args">Command-line arguments.</param> public static void Main(string[] args) { // Validate the command line and parse out the relevant pieces. if (!TryParseCommandLine(args, out string testAssemblyPath, out string runtimeAssembliesPath, out string outputPath, out Xunit.ConsoleClient.CommandLine? xunitCommandLine)) { return; } // Set up an assembly resolving event handler to help locate helper assemblies that are needed // to process the test assembly, such as xunit assemblies and corefx test helpers. string[] probingPaths = new[] { Path.GetDirectoryName(testAssemblyPath), runtimeAssembliesPath, outputPath, AppContext.BaseDirectory }; AppDomain.CurrentDomain.AssemblyResolve += (object sender, ResolveEventArgs args) => { // Clean up the dll name. string name = args.Name; int comma = name.IndexOf(','); if (comma > 0) { name = name.Substring(0, comma); } if (!name.EndsWith(".dll")) { name += ".dll"; } // Try to find and load the assembly from each of directory in turn. foreach (string probingPath in probingPaths) { try { Assembly a = Assembly.LoadFrom(Path.Combine(probingPath, name)); Log($"Loaded {a} from {a.Location}"); return a; } catch { } } return null; }; // Discover all of the test methods in the test assembly, and find all theory inputs. DiscoverTestMethods(testAssemblyPath, out Assembly testAssembly, out TestDiscoverySink sink); Dictionary<IXunitTestCase, List<TestCase>> testCaseData = ComputeTestMethodTestCases(sink); int numUnsupported = 0, numCalls = 0; XunitFilters xunitFilters = xunitCommandLine!.Project.Filters; var sb = new StringBuilder(); // Output the beginning of the program. Log(""); sb.AppendLine(CodeTemplateStart); // Output calls for each test case. foreach (IXunitTestCase testCase in sink.TestCases) { // Skip test cases that aren't relevant to the current platform, OS, etc. This is based // primarily on the traits applied earlier. if (!xunitFilters.Filter(testCase)) { continue; } MethodInfo m = ((ReflectionMethodInfo)testCase.Method).MethodInfo; Type t = m.ReflectedType; // Skip test cases we can't support. Some of these xunit doesn't support // either, so it's just for good measure; in other cases, xunit can support // them but with a lot of work at run time, often involving complicated reflection. if (t.IsGenericType) { Log($"Unsupported {t.Name}.{testCase.Method.Name}. Generic type."); numUnsupported++; continue; } if (!IsPublic(t)) { Log($"Unsupported {t.Name}.{testCase.Method.Name}. Non-public type."); numUnsupported++; continue; } if (!m.IsPublic) { Log($"Unsupported {t.Name}.{testCase.Method.Name}. Non-public method."); numUnsupported++; continue; } if (!m.IsStatic && !HasSupportedConstructor(t)) { Log($"Unsupported {t.Name}.{testCase.Method.Name}. Unsupported ctor."); numUnsupported++; continue; } // Output a call per theory data for this test case. sb.AppendLine("{"); List<TestCase> testCases = testCaseData[testCase]; for (int i = 0; i < testCases.Count; i++) { TestCase test = testCases[i]; MethodInfo? mi = test.MemberDataMember as MethodInfo ?? (test.MemberDataMember as PropertyInfo)?.GetGetMethod(); // Skip theory data we can't support. if (mi != null) { if (!mi.IsPublic || !mi.IsStatic) { Log($"Unsupported {t.Name}.{testCase.Method.Name}. Non-public MemberData {mi.Name}."); numUnsupported++; continue; } if (m.IsGenericMethod) { Log($"Unsupported {t.Name}.{testCase.Method.Name}. Generic method requires reflection invoke."); numUnsupported++; continue; } } if (test.MemberDataMember is FieldInfo fi && (!fi.IsPublic || !fi.IsStatic)) { Log($"Unsupported {t.Name}.{testCase.Method.Name}. Non-public MemberData field {fi.Name}."); numUnsupported++; continue; } if (test.Values != null) { if (!test.Values.All(v => v == null || (v is Type t && IsPublic(t)) || IsPublic(v.GetType()))) { Log($"Unsupported {t.Name}.{testCase.Method.Name}. Non-public theory argument."); numUnsupported++; continue; } } // Compute a display name to render. This will be displayed in an error message, and // can be used to then correlate back to the offending line in the generated .cs file. string displayName = testCase.DisplayName; if (testCases.Count > 1) { displayName += "{" + i + "}"; } // Write out the call. GenerateTestCaseCode(sb, displayName, t, m, test); numCalls++; } sb.AppendLine("}"); } // Output the end of the program. sb.AppendLine(CodeTemplateEnd); Log(""); Log($"Num unsupported: {numUnsupported}"); Log($"Num calls written: {numCalls}"); Log(""); // Make sure our output directory exists if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } // Write out the .cs file string csPath = Path.Combine(outputPath, "Program.cs"); File.WriteAllText(csPath, CSharpSyntaxTree.ParseText(sb.ToString()).GetRoot().NormalizeWhitespace().ToString()); Log($"Wrote {csPath}"); // Write out the associated .csproj string csprojPath = Path.Combine(outputPath, Path.GetFileNameWithoutExtension(testAssemblyPath) + "-runner.csproj"); File.WriteAllText( csprojPath, CSProjTemplate .Replace("#HelperAssemblyLocation#", runtimeAssembliesPath) .Replace("#TestAssembly#", Path.GetFullPath(testAssemblyPath)) .Replace("#TestAssemblyLocation#", testAssemblyPath)); Log($"Wrote {csprojPath}"); } /// <summary>Parse the command-line.</summary> /// <param name="args">The arguments passed to Main.</param> /// <param name="testAssemblyPath">The location of the xunit test assembly to be analyzed. The resulting .cs file will call into this assembly.</param> /// <param name="runtimeAssembliesPath">The directory containing all of the helper assemblies needed, e.g. xunit's assemblies, corefx utility assemblies, etc.</param> /// <param name="outputPath">The directory into which the resulting project should be written.</param> /// <param name="xunitCommandLine">The xunit command-line object to pass to xunit test discovery.</param> /// <returns></returns> private static bool TryParseCommandLine( string[] args, out string testAssemblyPath, out string runtimeAssembliesPath, out string outputPath, out Xunit.ConsoleClient.CommandLine? xunitCommandLine) { if (args.Length >= 3) { static string EnsureEndsWithSeparator(string path) => !path.EndsWith(Path.DirectorySeparatorChar) && !path.EndsWith(Path.AltDirectorySeparatorChar) ? path + Path.DirectorySeparatorChar : path; runtimeAssembliesPath = EnsureEndsWithSeparator(args[1]); testAssemblyPath = Path.GetFullPath(args[2]); outputPath = EnsureEndsWithSeparator(Path.Combine(args[0], Path.GetFileNameWithoutExtension(testAssemblyPath))); // Gather arguments for xunit. var argsForXunit = new List<string>(); argsForXunit.Add(testAssemblyPath); // first argument is the test assembly foreach (string extraArg in args.Skip(3)) { // If an argument is a response file, load its contents and add that instead. if (extraArg.StartsWith("@")) { argsForXunit.AddRange(from line in File.ReadAllLines(extraArg.Substring(1)) where line.Length > 0 && line[0] != '#' from part in line.Split(' ') select part); } else { // Otherwise, add the argument as-is. argsForXunit.Add(extraArg); } } // If the only argument added was the test assembly path, use default arguments. if (argsForXunit.Count == 1) { argsForXunit.AddRange(s_defaultXunitOptions); } // Finally, hand off these arguments to xunit. xunitCommandLine = Xunit.ConsoleClient.CommandLine.Parse(argsForXunit.ToArray()); Log($"Test assembly path : {testAssemblyPath}"); Log($"Helper assemblies path: {runtimeAssembliesPath}"); Log($"Output path : {outputPath}"); Log($"Xunit arguments : {string.Join(" ", argsForXunit)}"); Log(""); return true; } // Invalid command line arguments. Console.WriteLine("Usage: <output_directory> <helper_assemblies_directory> <test_assembly_path> <xunit_console_options>"); Console.WriteLine(" Example:"); Console.WriteLine(@" dotnet run d:\tmpoutput d:\repos\corefx\artifacts\bin\testhost\netcoreapp-Windows_NT-Debug-x64\shared\Microsoft.NETCore.App\$(ProductVersion) d:\repos\corefx\artifacts\bin\System.Runtime.Tests\netcoreapp-Windows_NT-Debug\System.Runtime.Tests.dll"); testAssemblyPath = string.Empty; runtimeAssembliesPath = string.Empty; outputPath = string.Empty; xunitCommandLine = null; return false; } /// <summary>Find all test methods in the test assembly. The resulting <paramref name="sink"/> will contain the found tests.</summary> /// <param name="testAssemblyPath">The path to the test assembly.</param> /// <param name="testAssembly">The loaded test assembly.</param> /// <param name="sink">The discovered tests.</param> private static void DiscoverTestMethods(string testAssemblyPath, out Assembly testAssembly, out TestDiscoverySink sink) { // Load the test assembly. testAssembly = Assembly.LoadFrom(testAssemblyPath); Log($"Loaded {testAssembly.GetName().Name} from {testAssembly.Location}"); // Find all tests. var discoverer = new Xunit2Discoverer( AppDomainSupport.Denied, new NullSourceInformationProvider(), new ReflectionAssemblyInfo(testAssembly), xunitExecutionAssemblyPath: null, shadowCopyFolder: null, new Xunit.NullMessageSink()); sink = new TestDiscoverySink(); discoverer.Find(includeSourceInformation: false, sink, TestFrameworkOptions.ForDiscovery(new TestAssemblyConfiguration() { DiagnosticMessages = false, InternalDiagnosticMessages = false, PreEnumerateTheories = false, StopOnFail = false })); // Wait for the find to complete. sink.Finished.WaitOne(); Log($"Found {sink.TestCases.Count} test methods."); } /// <summary>Find all test cases associated with the found tests (e.g. one test case per theory input to each test).</summary> /// <param name="sink">The sink containing the discovered tests.</param> /// <returns>A dictionary of all tests and their associated test cases.</returns> private static Dictionary<IXunitTestCase, List<TestCase>> ComputeTestMethodTestCases(TestDiscoverySink sink) { // Create the dictionary containing all tests and associated test cases. Dictionary<IXunitTestCase, List<TestCase>> testCases = sink .TestCases .Cast<IXunitTestCase>() .Select(tc => { MethodInfo testMethod = ((ReflectionMethodInfo)tc.Method).MethodInfo; Type testMethodType = testMethod.ReflectedType; var cases = new List<TestCase>(); if (testMethod.GetParameters().Length > 0) { // The test method has arguments, so look for all of the standard data attributes we can use to invoke the theory. foreach (DataAttribute attr in testMethod.GetCustomAttributes<DataAttribute>(inherit: true)) { try { // DataAttributes can themselves be marked to be skipped. Ignore the attribute if it is. if (!string.IsNullOrWhiteSpace(attr.Skip)) { continue; } switch (attr) { case MemberDataAttribute memberData: // For a [MemberData(...)], it might point to a method, property, or field; get the right // piece of metadata. Also, for methods, there might be data to pass to the method // when invoking it; store that as well. Type memberDataType = memberData.MemberType ?? testMethod.DeclaringType; MethodInfo testDataMethod = memberDataType.GetMethod(memberData.MemberName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy); if (testDataMethod != null) { cases.Add(new TestCase { MemberDataMember = testDataMethod, Values = memberData.Parameters }); break; } PropertyInfo testDataProperty = memberDataType.GetProperty(memberData.MemberName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy); if (testDataProperty != null) { cases.Add(new TestCase { MemberDataMember = testDataProperty }); break; } FieldInfo testDataField = memberDataType.GetField(memberData.MemberName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy); if (testDataField != null) { cases.Add(new TestCase { MemberDataMember = testDataField }); break; } Log($"Error finding {memberData.MemberName} in MemberData on {testMethod.Name}"); break; case ClassDataAttribute classData: if (classData.Class != null) { cases.Add(new TestCase { MemberDataMember = classData.Class }); } break; case InlineDataAttribute inlineData: cases.AddRange(from values in attr.GetData(testMethod) select new TestCase { Values = values }); break; } } catch (Exception e) { Log($"Error processing {attr} on test method {testMethod.Name}: {e.Message}."); } } // There may also be custom data attributes. We can't just use their GetData methods, as they // may return data we can't serialize into the .cs file. That means we need to be able to serialize // the construction of the attribute itself into the source file, so that we can effectively treat it // like we do a member info. To do that, we enumerate attribute datas. foreach (CustomAttributeData cad in testMethod.GetCustomAttributesData()) { try { Type attrType = cad.AttributeType; if (!attrType.IsSubclassOf(typeof(DataAttribute))) { // We only care about DataAttribute-derived types. continue; } if (typeof(MemberDataAttribute).IsAssignableFrom(attrType) || typeof(ClassDataAttribute).IsAssignableFrom(attrType) || typeof(InlineDataAttribute).IsAssignableFrom(attrType)) { // Already handled these in the previous loop. continue; } // Skip attributes we can't handle if (!attrType.IsPublic || !cad.Constructor.IsPublic || !cad.ConstructorArguments.All(c => c.ArgumentType.IsPublic)) { Log($"Unsupported custom data attribute {cad.AttributeType} on test method {testMethod.Name}."); continue; } // Store the attribute type and the ctor values for it. object[] values = (object[])UnwrapCustomAttributeTypedArguments(typeof(object), cad.ConstructorArguments); cases.Add(new TestCase { MemberDataMember = cad.Constructor, Values = values }); } catch (Exception e) { Log($"Error processing {cad.AttributeType} on test method {testMethod.Name}: {e.Message}."); } } } else { // There are no arguments to the method, so we just add a single test case to represent invoking the method. cases.Add(new TestCase()); } return KeyValuePair.Create(tc, cases); }).ToDictionary(k => k.Key, k => k.Value); return testCases; } private static Array UnwrapCustomAttributeTypedArguments(Type elementType, IList<CustomAttributeTypedArgument> args) { Array result = Array.CreateInstance(elementType, args.Count); for (int i = 0; i < args.Count; i++) { CustomAttributeTypedArgument cata = args[i]; object newArg = cata.Value is IReadOnlyCollection<CustomAttributeTypedArgument> roc ? UnwrapCustomAttributeTypedArguments(cata.ArgumentType.GetElementType(), roc.ToArray()) : cata.Value; try { result.SetValue(newArg, i); } catch { throw new Exception($"Couldn't store {newArg} into array {result}"); } } return result; } /// <summary>Writes the code for invoking the test case into the <see cref="StringBuilder"/>.</summary> /// <param name="sb">The destination StringBuilder.</param> /// <param name="testCaseDisplayName">The display name of the test case.</param> /// <param name="testMethodType">The type on which the test method lives.</param> /// <param name="testMethod">The test method.</param> /// <param name="testCase">The test case.</param> private static void GenerateTestCaseCode( StringBuilder sb, string testCaseDisplayName, Type testMethodType, MethodInfo testMethod, TestCase testCase) { // Writes out ".MethodName(arg1, arg2, ...)" when all arguments are statically available. // The arguments are written as literals. void WriteArgumentListStatic(object[]? arguments, ParameterInfo[] parameters) { // Handle optional arguments by populating the input array with the defaults // whereever they exist and didn't already contain a value. Also handle // a null input as meaning a null argument as input to a parameter. if (arguments == null) { if (parameters.Length > 0) { arguments = new object[parameters.Length]; } } else if (arguments.Length < parameters.Length) { var newArguments = new object[parameters.Length]; Array.Copy(arguments, 0, newArguments, 0, arguments.Length); for (int i = arguments.Length; i < parameters.Length; i++) { if (parameters[i].HasDefaultValue) { newArguments[i] = parameters[i].DefaultValue; } } arguments = newArguments; } // Write out the argument list sb.Append("("); for (int i = 0; i < parameters.Length; i++) { if (i != 0) { sb.Append(", "); } sb.Append(EncodeLiteral(arguments?[i], parameters[i].ParameterType)); } sb.Append(")"); } // Writes out ".MethodName(Cast<T0>(args[0]), Cast<T1>(args[1]), ...)" when all arguments are only // known at execution time from invoking a theory member data. void WriteArgumentListDynamic(string argumentsName, ParameterInfo[] parameters) { sb.Append("("); for (int i = 0; i < parameters.Length; i++) { if (i != 0) { sb.Append(", "); } sb.Append($"Cast<{GetTypeName(parameters[i].ParameterType)}>({argumentsName}[{i}])"); } sb.Append(")"); } // TODO: Support IDisposable on these objects passed to the ctors, and create one that's shared/reused // across every method on the same test class. // Gets the argument string to pass to the test class. This may include instantiating // a class fixture to pass into the test class' ctor. string GetConstructorArgs() { ConstructorInfo[] ctors = testMethodType.GetConstructors(); foreach (ConstructorInfo ctor in ctors) { ParameterInfo[] parameters = ctor.GetParameters(); switch (parameters.Length) { case 0: return string.Empty; case 1: string typeName = parameters[0].ParameterType.Name == "ITestOutputHelper" ? "DefaultTestOutputHelper" : GetTypeName(parameters[0].ParameterType); return $"new {typeName}()"; } } Log($"Error processing ctors for {testMethod.Name}."); return string.Empty; } // Write out the method call to invoke the test case with all arguments known at compile time. void WriteInvocationStatic(object[]? arguments, ParameterInfo[] parameters) { if (testMethod.IsStatic) { sb.Append($"Execute(\"{testCaseDisplayName}\", () => {GetTypeName(testMethodType)}.{testMethod.Name}"); WriteArgumentListStatic(arguments, parameters); sb.AppendLine(");"); } else if (testMethodType.GetInterface("IDisposable") != null) { sb.AppendLine($"using (var inst = new {GetTypeName(testMethodType)}({GetConstructorArgs()}))"); sb.Append($"Execute(\"{testCaseDisplayName}\", () => inst.{testMethod.Name}"); WriteArgumentListStatic(arguments, parameters); sb.AppendLine(");"); } else { sb.Append($"Execute(\"{testCaseDisplayName}\", () => new {GetTypeName(testMethodType)}({GetConstructorArgs()}).{testMethod.Name}"); WriteArgumentListStatic(arguments, parameters); sb.AppendLine(");"); } } // Write out the method call to invoke the test case with all arguments known at run time. void WriteInvocationDynamic(string argumentsName, ParameterInfo[] parameters) { if (testMethod.IsStatic) { sb.Append($"Execute(\"{testCaseDisplayName}\", () => {GetTypeName(testMethodType)}.{testMethod.Name}"); WriteArgumentListDynamic(argumentsName, parameters); sb.AppendLine(");"); } else if (testMethodType.GetInterface("IDisposable") != null) { sb.AppendLine($"using (var inst = new {GetTypeName(testMethodType)}({GetConstructorArgs()}))"); sb.Append($"Execute(\"{testCaseDisplayName}\", () => inst.{testMethod.Name}"); WriteArgumentListDynamic(argumentsName, parameters); sb.AppendLine(");"); } else { sb.Append($"Execute(\"{testCaseDisplayName}\", () => new {GetTypeName(testMethodType)}({GetConstructorArgs()}).{testMethod.Name}"); WriteArgumentListDynamic(argumentsName, parameters); sb.AppendLine(");"); } } // Get the parameters for the test method. ParameterInfo[] parameters = testMethod.GetParameters(); // Write out the invocation, with input coming from a theory data attribute if relevant. switch (testCase.MemberDataMember) { case MethodInfo mi: // This is a theory with data coming from a MemberData method. string memberDataArgs = string.Empty; if (testCase.Values != null) { // There are arguments to the member data; serialize them to be used in the call to it. ParameterInfo[] memberDataParameters = mi.GetParameters(); var argsSb = new StringBuilder(); for (int i = 0; i < testCase.Values.Length; i++) { if (i != 0) { argsSb.Append(", "); } argsSb.Append(EncodeLiteral(testCase.Values[i], memberDataParameters[i].ParameterType)); } memberDataArgs = argsSb.ToString(); } sb.AppendLine($"foreach (object[] row in {GetTypeName(mi.ReflectedType)}.{mi.Name}({memberDataArgs}))"); WriteInvocationDynamic("row", parameters); break; case PropertyInfo pi: // This is a theory with data coming from a MemberData property. sb.AppendLine($"foreach (object[] row in {GetTypeName(pi.ReflectedType)}.{pi.Name})"); WriteInvocationDynamic("row", parameters); break; case FieldInfo fi: // This is a theory with data coming from a MemberData field. sb.AppendLine($"foreach (object[] row in {GetTypeName(fi.ReflectedType)}.{fi.Name})"); WriteInvocationDynamic("row", parameters); break; case Type ti: // This is a theory with data coming from a ClassData data attribute. sb.AppendLine($"foreach (object[] row in ((IEnumerable<object[]>)new {GetTypeName(ti)}())"); WriteInvocationDynamic("row", parameters); break; case ConstructorInfo ci: // This is a theory with data coming from a custom data attribute. sb.AppendLine($"foreach (object[] row in new {GetTypeName(ci.DeclaringType)}"); WriteArgumentListStatic(testCase.Values, ci.GetParameters()); sb.Append(".GetData(null))"); // TODO: Generate code to construct a method info to pass in instead of null? WriteInvocationDynamic("row", parameters); break; default: // This is either a method with no arguments, or it's a theory with theory data // coming from an InlineData or some other means where we know all of the values // at compile time. WriteInvocationStatic(testCase.Values, parameters); break; } } /// <summary>Encodes the provided object as a literal.</summary> /// <param name="literal">The literal to encode.</param> /// <param name="expectedType">The type that's expected at the usage location.</param> /// <returns>A string representing the encoded literal.</returns> private static string EncodeLiteral(object? literal, Type? expectedType) { if (literal == null) { return "null"; } if (literal is Type t) { return $"typeof({GetTypeName(t)})"; } if (literal is Array arr) { Type elementType = literal.GetType().GetElementType(); return $"new {GetTypeName(elementType)}[]" + "{" + string.Join(",", arr.Cast<object>().Select(o => EncodeLiteral(o, elementType))) + "}"; } if (literal is Guid guid) { return $"Guid.Parse(\"{guid}\")"; } if (literal is IntPtr ptr) { return $"new IntPtr(0x{((long)ptr).ToString("X")})"; } if (literal is UIntPtr uptr) { return $"new UIntPtr(0x{((ulong)uptr).ToString("X")})"; } string? result = null; if (literal is Enum e) { result = $"({GetTypeName(e.GetType())})({e.ToString("D")}{(Convert.GetTypeCode(literal) == TypeCode.UInt64 ? "UL" : "L")})"; } else { switch (Type.GetTypeCode(literal.GetType())) { case TypeCode.Boolean: result = ((bool)literal).ToString().ToLowerInvariant(); break; case TypeCode.Char: result = $"'\\u{((int)(char)literal).ToString("X4")}'"; break; case TypeCode.SByte: result = $"(sbyte)({literal.ToString()})"; break; case TypeCode.Byte: result = $"(byte){literal.ToString()}"; break; case TypeCode.Int16: result = $"(short)({literal.ToString()})"; break; case TypeCode.UInt16: result = $"(ushort){literal.ToString()}"; break; case TypeCode.Int32: result = $"({literal.ToString()})"; break; case TypeCode.UInt32: result = $"{literal.ToString()}U"; break; case TypeCode.Int64: result = $"({literal.ToString()}L)"; break; case TypeCode.UInt64: result = $"{literal.ToString()}UL"; break; case TypeCode.Decimal: result = $"({literal.ToString()}M)"; break; case TypeCode.Single: result = float.IsNegativeInfinity((float)literal) ? "float.NegativeInfinity" : float.IsInfinity((float)literal) ? "float.PositiveInfinity" : float.IsNaN((float)literal) ? "float.NaN" : $"(float)({((float)literal).ToString("R")}F)"; break; case TypeCode.Double: result = double.IsNegativeInfinity((double)literal) ? "double.NegativeInfinity" : double.IsInfinity((double)literal) ? "double.PositiveInfinity" : double.IsNaN((double)literal) ? "double.NaN" : $"(double)({((double)literal).ToString("R")}D)"; break; case TypeCode.String: var sb = new StringBuilder(); sb.Append('"'); foreach (char c in literal.ToString()) { if (c == '\\') { sb.Append("\\\\"); } else if (c == '"') { sb.Append("\\\""); } else if (c >= 32 && c < 127) { sb.Append(c); } else { sb.Append($"\\u{((int)c).ToString("X4")}"); } } sb.Append('"'); result = sb.ToString(); break; default: Log($"Error encoding literal {literal} ({literal?.GetType()})"); return string.Empty; } } if (expectedType != null && Nullable.GetUnderlyingType(expectedType) == null && literal.GetType() != expectedType && !expectedType.IsGenericParameter) { result = $"({GetTypeName(expectedType)})({result})"; } return result; } /// <summary>Gets the full type name that can be written into the source, e.g. in a typeof or in a method invocation.</summary> /// <param name="type">The type.</param> /// <returns>The rendered type name.</returns> private static string GetTypeName(Type type) { if (type == typeof(void)) { return "void"; } if (type == typeof(object)) { return "object"; } if (!type.IsEnum) { switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: return "bool"; case TypeCode.Byte: return "byte"; case TypeCode.Char: return "char"; case TypeCode.Decimal: return "decimal"; case TypeCode.Double: return "double"; case TypeCode.Int16: return "short"; case TypeCode.Int32: return "int"; case TypeCode.Int64: return "long"; case TypeCode.SByte: return "sbyte"; case TypeCode.Single: return "float"; case TypeCode.String: return "string"; case TypeCode.UInt16: return "ushort"; case TypeCode.UInt32: return "uint"; case TypeCode.UInt64: return "ulong"; } } if (type.IsArray) { return GetTypeName(type.GetElementType()) + "[" + new string(',', type.GetArrayRank() - 1) + "]"; } if (type.IsPointer) { return GetTypeName(type.GetElementType()) + "*"; } Type[] genericArgs = type.GetGenericArguments(); Type[] parentGenericArgs = type.DeclaringType?.GetGenericArguments() ?? Type.EmptyTypes; string? name = null; if (type.IsNested) { if (type.DeclaringType.IsGenericType && !type.DeclaringType.IsConstructedGenericType && type.IsConstructedGenericType) { name = GetTypeName(type.DeclaringType.MakeGenericType(genericArgs.Take(parentGenericArgs.Length).ToArray())); } else { name = GetTypeName(type.DeclaringType); } name += "." + type.Name; } else if (!string.IsNullOrEmpty(type.Namespace)) { name = type.Namespace + "." + type.Name; } else { name = type.Name; } if (!type.IsGenericType) { return name; } int backtickPos = name.IndexOf("`"); if (backtickPos == -1) { return name; } name = name.Substring(0, backtickPos); if (type.IsNested && type.DeclaringType.IsGenericType) { genericArgs = genericArgs.Skip(parentGenericArgs.Length).ToArray(); } return name + "<" + (type.IsConstructedGenericType ? string.Join(", ", genericArgs.Select(g => GetTypeName(g))) : new string(',', genericArgs.Length - 1)) + ">"; } /// <summary>Determines whether the type has public visibility such that we can emit calls into it.</summary> /// <param name="type">The type.</param> /// <returns>true if we can make calls to the type; otherwise, false.</returns> private static bool IsPublic(Type type) { if (type.IsArray || type.IsPointer) { return IsPublic(type.GetElementType()); } if (type.IsNested) { return type.IsNestedPublic && IsPublic(type.DeclaringType); } return type.IsPublic; } /// <summary>Determines whether the test class has a ctor we can use to instantiate it.</summary> /// <param name="testClassType">The type.</param> /// <returns>true if we can instantiate the test class; otherwise, false.</returns> private static bool HasSupportedConstructor(Type testClassType) { foreach (ConstructorInfo ci in testClassType.GetConstructors()) { ParameterInfo[] parameters = ci.GetParameters(); switch (parameters.Length) { case 0: // If there's a default ctor, we're good to go. return true; case 1: // If the test class takes an ITestOutputHelper, we can manufacture a TestOutputHelper. if (parameters[0].ParameterType == typeof(ITestOutputHelper)) { return true; } // If the test class takes a type that has a public ctor we can // use to create it, then we're also fine. Type ctorArgType = parameters[0].ParameterType; if (IsPublic(ctorArgType) && ctorArgType.GetConstructor(Type.EmptyTypes) != null) { return true; } break; } } // We don't know how to instantiate this test class. return false; } /// <summary>Log a message to the console.</summary> /// <param name="message">The message to log.</param> private static void Log(string message) { message ??= string.Empty; Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write(DateTime.Now + " | "); Console.ResetColor(); const string ErrorStart = "Error"; const string WarningStart = "Unsupported"; if (message.StartsWith(ErrorStart)) { Console.ForegroundColor = ConsoleColor.Red; Console.Write(ErrorStart); Console.ResetColor(); message = message.Substring(ErrorStart.Length); } else if (message.StartsWith(WarningStart)) { Console.ForegroundColor = ConsoleColor.Yellow; Console.Write(WarningStart); Console.ResetColor(); message = message.Substring(WarningStart.Length); } Console.WriteLine(message); } /// <summary>Represents a test case for a test method.</summary> private sealed class TestCase { /// <summary>The method, property, or field to invoke or access to retrieve theory data.</summary> public MemberInfo? MemberDataMember; /// <summary> /// If <see cref="MemberDataMember"/> is a MethodInfo, the arguments to the test method, if there are any. /// Otherwise, the arguments to the member data method, or null if there aren't any. /// </summary> public object[]? Values; } /// <summary>Default options to use when constructing xunit options if no additional options are provided.</summary> private static readonly string[] s_defaultXunitOptions = new string[] { "-notrait", "category=nonnetcoreapptests", "-notrait", "category=nonwindowstests", "-notrait", "category=IgnoreForCI", "-notrait", "category=failing", "-notrait", "category=OuterLoop" }; /// <summary>The code to write out to the output file before all of the test cases.</summary> private const string CodeTemplateStart = @"using System; using System.Threading.Tasks; using Microsoft.DotNet.XUnitExtensions; using Xunit.Abstractions; public static class Test { private static bool s_verbose; private static int s_succeeded, s_failed; public static void Main(string[] args) { if (args[0] == ""-v"") s_verbose = true; "; /// <summary>The code to write out to the output file after all of the test cases.</summary> private const string CodeTemplateEnd = @" Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Yellow; int total = s_succeeded + s_failed; Console.WriteLine($""Total : {total}""); if (total > 0) { Console.WriteLine($""Passed: {s_succeeded} ({(s_succeeded * 100.0 / total).ToString(""N"")}%)""); Console.WriteLine($""Failed: {s_failed} ({(s_failed * 100.0 / total).ToString(""N"")}%)""); } Console.ResetColor(); } private static void Execute(string name, Action action) { if (s_verbose) Console.WriteLine(name); try { action(); s_succeeded++; } catch (SkipTestException) { } catch (Exception e) { s_failed++; Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine(name + "" [FAIL]""); Console.ResetColor(); Console.Error.WriteLine(e); } } private static void Execute(string name, Func<Task> action) { if (s_verbose) Console.WriteLine(name); try { action().GetAwaiter().GetResult(); s_succeeded++; } catch (SkipTestException) { } catch (Exception e) { s_failed++; Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine(name + "" [FAIL]""); Console.ResetColor(); Console.Error.WriteLine(e); } } private static T Cast<T>(object obj) => obj is null ? default : obj is T t ? t : (T)Convert.ChangeType(obj, typeof(T)); private sealed class DefaultTestOutputHelper : ITestOutputHelper { public void WriteLine(string message) { if (s_verbose) Console.WriteLine(""TestOutputHelper: "" + message); } public void WriteLine(string format, params object[] args) { if (s_verbose) Console.WriteLine(""TestOutputHelper: "" + string.Format(format, args)); } } } "; /// <summary>The template for the .csproj.</summary> private const string CSProjTemplate = @"<Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp3.0</TargetFramework> <LangVersion>preview</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <NoWarn>IDE0049</NoWarn> <!-- names can be simplified --> </PropertyGroup> <ItemGroup> <Reference Include=""xunit.core""><HintPath>#HelperAssemblyLocation#xunit.core.dll</HintPath></Reference> <Reference Include=""xunit.assert""><HintPath>#HelperAssemblyLocation#xunit.assert.dll</HintPath></Reference> <Reference Include=""xunit.abstractions""><HintPath>#HelperAssemblyLocation#xunit.abstractions.dll</HintPath></Reference> <Reference Include=""System.Runtime.CompilerServices.Unsafe""><HintPath>#HelperAssemblyLocation#System.Runtime.CompilerServices.Unsafe.dll</HintPath></Reference> <Reference Include=""Microsoft.DotNet.XUnitExtensions""><HintPath>#HelperAssemblyLocation#Microsoft.DotNet.XUnitExtensions.dll</HintPath></Reference> <Reference Include=""#TestAssembly#""><HintPath>#TestAssemblyLocation#</HintPath></Reference> </ItemGroup> </Project>"; } }
// ConsoleCrayon.cs // // using System; namespace EmergeTk { internal static class ConsoleCrayon { #region Public API private static ConsoleColor foreground_color; public static ConsoleColor ForegroundColor { get { return foreground_color; } set { foreground_color = value; SetColor (foreground_color, true); } } private static ConsoleColor background_color; public static ConsoleColor BackgroundColor { get { return background_color; } set { background_color = value; SetColor (background_color, false); } } public static void ResetColor () { if (XtermColors) { Console.Write (GetAnsiResetControlCode ()); } else if (Environment.OSVersion.Platform != PlatformID.Unix && !RuntimeIsMono) { Console.ResetColor (); } } private static void SetColor (ConsoleColor color, bool isForeground) { if (color < ConsoleColor.Black || color > ConsoleColor.White) { throw new ArgumentOutOfRangeException ("color", "Not a ConsoleColor value."); } if (XtermColors) { Console.Write (GetAnsiColorControlCode (color, isForeground)); } else if (Environment.OSVersion.Platform != PlatformID.Unix && !RuntimeIsMono) { if (isForeground) { Console.ForegroundColor = color; } else { Console.BackgroundColor = color; } } } #endregion #region Ansi/VT Code Calculation // Modified from Mono's System.TermInfoDriver // License: MIT/X11 // Authors: Gonzalo Paniagua Javier (gonzalo@ximian.com) // (C) 2005,2006 Novell, Inc (http://www.novell.com) static int TranslateColor (ConsoleColor desired, out bool light) { switch (desired) { // Dark colours case ConsoleColor.Black: light = false; return 0; case ConsoleColor.DarkRed: light = false; return 1; case ConsoleColor.DarkGreen: light = false; return 2; case ConsoleColor.DarkYellow: light = false; return 3; case ConsoleColor.DarkBlue: light = false; return 4; case ConsoleColor.DarkMagenta: light = false; return 5; case ConsoleColor.DarkCyan: light = false; return 6; case ConsoleColor.Gray: light = false; return 7; // Light colours case ConsoleColor.DarkGray: light = true; return 0; case ConsoleColor.Red: light = true; return 1; case ConsoleColor.Green: light = true; return 2; case ConsoleColor.Yellow: light = true; return 3; case ConsoleColor.Blue: light = true; return 4; case ConsoleColor.Magenta: light = true; return 5; case ConsoleColor.Cyan: light = true; return 6; default: case ConsoleColor.White: light = true; return 7; } } private static string GetAnsiColorControlCode (ConsoleColor colour, bool isForeground) { bool light; // lighter fg colours are 90 -> 97 rather than 30 -> 37 // lighter bg colours are 100 -> 107 rather than 40 -> 47 int code = TranslateColor (colour, out light) + (isForeground? 30 : 40) + (light? 60 : 0); return String.Format ("\x001b[{0}m", code); } private static string GetAnsiResetControlCode () { return "\x001b[0m"; } #endregion #region xterm Detection private static bool? xterm_colors = null; public static bool XtermColors { get { if (xterm_colors == null) { DetectXtermColors (); } return xterm_colors.Value; } } [System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty")] private extern static int _isatty (int fd); private static bool isatty (int fd) { try { return _isatty (fd) == 1; } catch { return false; } } private static void DetectXtermColors () { bool _xterm_colors = false; switch (Environment.GetEnvironmentVariable ("TERM")) { case "xterm": case "linux": if (Environment.GetEnvironmentVariable ("COLORTERM") != null) { _xterm_colors = true; } break; case "xterm-color": _xterm_colors = true; break; } xterm_colors = _xterm_colors && isatty (1) && isatty (2); } #endregion #region Runtime Detection private static bool? runtime_is_mono; public static bool RuntimeIsMono { get { if (runtime_is_mono == null) { runtime_is_mono = Type.GetType ("System.MonoType") != null; } return runtime_is_mono.Value; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Threading { // ManualResetEventSlim wraps a manual-reset event internally with a little bit of // spinning. When an event will be set imminently, it is often advantageous to avoid // a 4k+ cycle context switch in favor of briefly spinning. Therefore we layer on to // a brief amount of spinning that should, on the average, make using the slim event // cheaper than using Win32 events directly. This can be reset manually, much like // a Win32 manual-reset would be. // // Notes: // We lazily allocate the Win32 event internally. Therefore, the caller should // always call Dispose to clean it up, just in case. This API is a no-op of the // event wasn't allocated, but if it was, ensures that the event goes away // eagerly, instead of waiting for finalization. /// <summary> /// Provides a slimmed down version of <see cref="T:System.Threading.ManualResetEvent"/>. /// </summary> /// <remarks> /// All public and protected members of <see cref="ManualResetEventSlim"/> are thread-safe and may be used /// concurrently from multiple threads, with the exception of Dispose, which /// must only be used when all other operations on the <see cref="ManualResetEventSlim"/> have /// completed, and Reset, which should only be used when no other threads are /// accessing the event. /// </remarks> [DebuggerDisplay("Set = {IsSet}")] public class ManualResetEventSlim : IDisposable { // These are the default spin counts we use on single-proc and MP machines. private const int DEFAULT_SPIN_SP = 1; private volatile object m_lock; // A lock used for waiting and pulsing. Lazily initialized via EnsureLockObjectCreated() private volatile ManualResetEvent m_eventObj; // A true Win32 event used for waiting. // -- State -- // //For a packed word a uint would seem better, but Interlocked.* doesn't support them as uint isn't CLS-compliant. private volatile int m_combinedState; //ie a uint. Used for the state items listed below. //1-bit for signalled state private const int SignalledState_BitMask = unchecked((int)0x80000000);//1000 0000 0000 0000 0000 0000 0000 0000 private const int SignalledState_ShiftCount = 31; //1-bit for disposed state private const int Dispose_BitMask = unchecked((int)0x40000000);//0100 0000 0000 0000 0000 0000 0000 0000 //11-bits for m_spinCount private const int SpinCountState_BitMask = unchecked((int)0x3FF80000); //0011 1111 1111 1000 0000 0000 0000 0000 private const int SpinCountState_ShiftCount = 19; private const int SpinCountState_MaxValue = (1 << 11) - 1; //2047 //19-bits for m_waiters. This allows support of 512K threads waiting which should be ample private const int NumWaitersState_BitMask = unchecked((int)0x0007FFFF); // 0000 0000 0000 0111 1111 1111 1111 1111 private const int NumWaitersState_ShiftCount = 0; private const int NumWaitersState_MaxValue = (1 << 19) - 1; //512K-1 // ----------- // #if DEBUG private static int s_nextId; // The next id that will be given out. private int m_id = Interlocked.Increment(ref s_nextId); // A unique id for debugging purposes only. private long m_lastSetTime; private long m_lastResetTime; #endif /// <summary> /// Gets the underlying <see cref="T:System.Threading.WaitHandle"/> object for this <see /// cref="ManualResetEventSlim"/>. /// </summary> /// <value>The underlying <see cref="T:System.Threading.WaitHandle"/> event object fore this <see /// cref="ManualResetEventSlim"/>.</value> /// <remarks> /// Accessing this property forces initialization of an underlying event object if one hasn't /// already been created. To simply wait on this <see cref="ManualResetEventSlim"/>, /// the public Wait methods should be preferred. /// </remarks> public WaitHandle WaitHandle { get { ThrowIfDisposed(); if (m_eventObj == null) { // Lazily initialize the event object if needed. LazyInitializeEvent(); } return m_eventObj; } } /// <summary> /// Gets whether the event is set. /// </summary> /// <value>true if the event has is set; otherwise, false.</value> public bool IsSet { get { return 0 != ExtractStatePortion(m_combinedState, SignalledState_BitMask); } private set { UpdateStateAtomically(((value) ? 1 : 0) << SignalledState_ShiftCount, SignalledState_BitMask); } } /// <summary> /// Gets the number of spin waits that will be occur before falling back to a true wait. /// </summary> public int SpinCount { get { return ExtractStatePortionAndShiftRight(m_combinedState, SpinCountState_BitMask, SpinCountState_ShiftCount); } private set { Debug.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); Debug.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); // Don't worry about thread safety because it's set one time from the constructor m_combinedState = (m_combinedState & ~SpinCountState_BitMask) | (value << SpinCountState_ShiftCount); } } /// <summary> /// How many threads are waiting. /// </summary> private int Waiters { get { return ExtractStatePortionAndShiftRight(m_combinedState, NumWaitersState_BitMask, NumWaitersState_ShiftCount); } set { //setting to <0 would indicate an internal flaw, hence Assert is appropriate. Debug.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error."); // it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here. if (value >= NumWaitersState_MaxValue) throw new InvalidOperationException(string.Format(SR.ManualResetEventSlim_ctor_TooManyWaiters, NumWaitersState_MaxValue)); UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask); } } //----------------------------------------------------------------------------------- // Constructs a new event, optionally specifying the initial state and spin count. // The defaults are that the event is unsignaled and some reasonable default spin. // /// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim"/> /// class with an initial state of nonsignaled. /// </summary> public ManualResetEventSlim() : this(false) { } /// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim"/> /// class with a boolean value indicating whether to set the initial state to signaled. /// </summary> /// <param name="initialState">true to set the initial state signaled; false to set the initial state /// to nonsignaled.</param> public ManualResetEventSlim(bool initialState) { // Specify the default spin count, and use default spin if we're // on a multi-processor machine. Otherwise, we won't. Initialize(initialState, SpinWait.SpinCountforSpinBeforeWait); } /// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim"/> /// class with a Boolean value indicating whether to set the initial state to signaled and a specified /// spin count. /// </summary> /// <param name="initialState">true to set the initial state to signaled; false to set the initial state /// to nonsignaled.</param> /// <param name="spinCount">The number of spin waits that will occur before falling back to a true /// wait.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="spinCount"/> is less than /// 0 or greater than the maximum allowed value.</exception> public ManualResetEventSlim(bool initialState, int spinCount) { if (spinCount < 0) { throw new ArgumentOutOfRangeException(nameof(spinCount)); } if (spinCount > SpinCountState_MaxValue) { throw new ArgumentOutOfRangeException( nameof(spinCount), string.Format(SR.ManualResetEventSlim_ctor_SpinCountOutOfRange, SpinCountState_MaxValue)); } // We will suppress default spin because the user specified a count. Initialize(initialState, spinCount); } /// <summary> /// Initializes the internal state of the event. /// </summary> /// <param name="initialState">Whether the event is set initially or not.</param> /// <param name="spinCount">The spin count that decides when the event will block.</param> private void Initialize(bool initialState, int spinCount) { m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0; //the spinCount argument has been validated by the ctors. //but we now sanity check our predefined constants. Debug.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); Debug.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); SpinCount = PlatformHelper.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount; } /// <summary> /// Helper to ensure the lock object is created before first use. /// </summary> private void EnsureLockObjectCreated() { if (m_lock != null) return; object newObj = new object(); Interlocked.CompareExchange(ref m_lock, newObj, null); // failure is benign. Someone else set the value. } /// <summary> /// This method lazily initializes the event object. It uses CAS to guarantee that /// many threads racing to call this at once don't result in more than one event /// being stored and used. The event will be signaled or unsignaled depending on /// the state of the thin-event itself, with synchronization taken into account. /// </summary> /// <returns>True if a new event was created and stored, false otherwise.</returns> private bool LazyInitializeEvent() { bool preInitializeIsSet = IsSet; ManualResetEvent newEventObj = new ManualResetEvent(preInitializeIsSet); // We have to CAS this in case we are racing with another thread. We must // guarantee only one event is actually stored in this field. if (Interlocked.CompareExchange(ref m_eventObj, newEventObj, null) != null) { // Someone else set the value due to a race condition. Destroy the garbage event. newEventObj.Dispose(); return false; } else { // Now that the event is published, verify that the state hasn't changed since // we snapped the preInitializeState. Another thread could have done that // between our initial observation above and here. The barrier incurred from // the CAS above (in addition to m_state being volatile) prevents this read // from moving earlier and being collapsed with our original one. bool currentIsSet = IsSet; if (currentIsSet != preInitializeIsSet) { Debug.Assert(currentIsSet, "The only safe concurrent transition is from unset->set: detected set->unset."); // We saw it as unsignaled, but it has since become set. lock (newEventObj) { // If our event hasn't already been disposed of, we must set it. if (m_eventObj == newEventObj) { newEventObj.Set(); } } } return true; } } /// <summary> /// Sets the state of the event to signaled, which allows one or more threads waiting on the event to /// proceed. /// </summary> public void Set() { Set(false); } /// <summary> /// Private helper to actually perform the Set. /// </summary> /// <param name="duringCancellation">Indicates whether we are calling Set() during cancellation.</param> /// <exception cref="T:System.OperationCanceledException">The object has been canceled.</exception> private void Set(bool duringCancellation) { // We need to ensure that IsSet=true does not get reordered past the read of m_eventObj // This would be a legal movement according to the .NET memory model. // The code is safe as IsSet involves an Interlocked.CompareExchange which provides a full memory barrier. IsSet = true; // If there are waiting threads, we need to pulse them. if (Waiters > 0) { Debug.Assert(m_lock != null); //if waiters>0, then m_lock has already been created. lock (m_lock) { Monitor.PulseAll(m_lock); } } ManualResetEvent eventObj = m_eventObj; //Design-decision: do not set the event if we are in cancellation -> better to deadlock than to wake up waiters incorrectly //It would be preferable to wake up the event and have it throw OCE. This requires MRE to implement cancellation logic if (eventObj != null && !duringCancellation) { // We must surround this call to Set in a lock. The reason is fairly subtle. // Sometimes a thread will issue a Wait and wake up after we have set m_state, // but before we have gotten around to setting m_eventObj (just below). That's // because Wait first checks m_state and will only access the event if absolutely // necessary. However, the coding pattern { event.Wait(); event.Dispose() } is // quite common, and we must support it. If the waiter woke up and disposed of // the event object before the setter has finished, however, we would try to set a // now-disposed Win32 event. Crash! To deal with this race condition, we use a lock to // protect access to the event object when setting and disposing of it. We also // double-check that the event has not become null in the meantime when in the lock. lock (eventObj) { if (m_eventObj != null) { // If somebody is waiting, we must set the event. m_eventObj.Set(); } } } #if DEBUG m_lastSetTime = DateTime.UtcNow.Ticks; #endif } /// <summary> /// Sets the state of the event to nonsignaled, which causes threads to block. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Reset()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> public void Reset() { ThrowIfDisposed(); // If there's an event, reset it. if (m_eventObj != null) { m_eventObj.Reset(); } // There is a race condition here. If another thread Sets the event, we will get into a state // where m_state will be unsignaled, yet the Win32 event object will have been signaled. // This could cause waiting threads to wake up even though the event is in an // unsignaled state. This is fine -- those that are calling Reset concurrently are // responsible for doing "the right thing" -- e.g. rechecking the condition and // resetting the event manually. // And finally set our state back to unsignaled. IsSet = false; #if DEBUG m_lastResetTime = DateTime.UtcNow.Ticks; #endif } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set. /// </summary> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. /// </remarks> public void Wait() { Wait(Timeout.Infinite, new CancellationToken()); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> receives a signal, /// while observing a <see cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> /// <exception cref="T:System.OperationCanceledExcepton"><paramref name="cancellationToken"/> was /// canceled.</exception> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. /// </remarks> public void Wait(CancellationToken cancellationToken) { Wait(Timeout.Infinite, cancellationToken); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// <see cref="T:System.TimeSpan"/> to measure the time interval. /// </summary> /// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds /// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely. /// </param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> public bool Wait(TimeSpan timeout) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } return Wait((int)totalMilliseconds, new CancellationToken()); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a <see /// cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds /// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely. /// </param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.Threading.OperationCanceledException"><paramref /// name="cancellationToken"/> was canceled.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } return Wait((int)totalMilliseconds, cancellationToken); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// 32-bit signed integer to measure the time interval. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> public bool Wait(int millisecondsTimeout) { return Wait(millisecondsTimeout, new CancellationToken()); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// 32-bit signed integer to measure the time interval, while observing a <see /// cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> /// <exception cref="T:System.Threading.OperationCanceledException"><paramref /// name="cancellationToken"/> was canceled.</exception> public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); // an early convenience check if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout)); } if (!IsSet) { if (millisecondsTimeout == 0) { // For 0-timeouts, we just return immediately. return false; } // We spin briefly before falling back to allocating and/or waiting on a true event. uint startTime = 0; bool bNeedTimeoutAdjustment = false; int realMillisecondsTimeout = millisecondsTimeout; //this will be adjusted if necessary. if (millisecondsTimeout != Timeout.Infinite) { // We will account for time spent spinning, so that we can decrement it from our // timeout. In most cases the time spent in this section will be negligible. But // we can't discount the possibility of our thread being switched out for a lengthy // period of time. The timeout adjustments only take effect when and if we actually // decide to block in the kernel below. startTime = TimeoutHelper.GetTime(); bNeedTimeoutAdjustment = true; } // Spin int spinCount = SpinCount; var spinner = new SpinWait(); while (spinner.Count < spinCount) { spinner.SpinOnce(SpinWait.Sleep1ThresholdForLongSpinBeforeWait); if (IsSet) { return true; } if (spinner.Count >= 100 && spinner.Count % 10 == 0) // check the cancellation token if the user passed a very large spin count cancellationToken.ThrowIfCancellationRequested(); } // Now enter the lock and wait. EnsureLockObjectCreated(); // We must register and unregister the token outside of the lock, to avoid deadlocks. using (cancellationToken.UnsafeRegister(s_cancellationTokenCallback, this)) { lock (m_lock) { // Loop to cope with spurious wakeups from other waits being canceled while (!IsSet) { // If our token was canceled, we must throw and exit. cancellationToken.ThrowIfCancellationRequested(); //update timeout (delays in wait commencement are due to spinning and/or spurious wakeups from other waits being canceled) if (bNeedTimeoutAdjustment) { realMillisecondsTimeout = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout); if (realMillisecondsTimeout <= 0) return false; } // There is a race condition that Set will fail to see that there are waiters as Set does not take the lock, // so after updating waiters, we must check IsSet again. // Also, we must ensure there cannot be any reordering of the assignment to Waiters and the // read from IsSet. This is guaranteed as Waiters{set;} involves an Interlocked.CompareExchange // operation which provides a full memory barrier. // If we see IsSet=false, then we are guaranteed that Set() will see that we are // waiting and will pulse the monitor correctly. Waiters = Waiters + 1; if (IsSet) //This check must occur after updating Waiters. { Waiters--; //revert the increment. return true; } // Now finally perform the wait. try { // ** the actual wait ** if (!Monitor.Wait(m_lock, realMillisecondsTimeout)) return false; //return immediately if the timeout has expired. } finally { // Clean up: we're done waiting. Waiters = Waiters - 1; } // Now just loop back around, and the right thing will happen. Either: // 1. We had a spurious wake-up due to some other wait being canceled via a different cancellationToken (rewait) // or 2. the wait was successful. (the loop will break) } } } } // automatically disposes (and unregisters) the callback return true; //done. The wait was satisfied. } /// <summary> /// Releases all resources used by the current instance of <see cref="ManualResetEventSlim"/>. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// When overridden in a derived class, releases the unmanaged resources used by the /// <see cref="ManualResetEventSlim"/>, and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; /// false to release only unmanaged resources.</param> /// <remarks> /// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose(bool)"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> protected virtual void Dispose(bool disposing) { if ((m_combinedState & Dispose_BitMask) != 0) return; // already disposed m_combinedState |= Dispose_BitMask; //set the dispose bit if (disposing) { // We will dispose of the event object. We do this under a lock to protect // against the race condition outlined in the Set method above. ManualResetEvent eventObj = m_eventObj; if (eventObj != null) { lock (eventObj) { eventObj.Dispose(); m_eventObj = null; } } } } /// <summary> /// Throw ObjectDisposedException if the MRES is disposed /// </summary> private void ThrowIfDisposed() { if ((m_combinedState & Dispose_BitMask) != 0) throw new ObjectDisposedException(SR.ManualResetEventSlim_Disposed); } /// <summary> /// Private helper method to wake up waiters when a cancellationToken gets canceled. /// </summary> private static Action<object> s_cancellationTokenCallback = new Action<object>(CancellationTokenCallback); private static void CancellationTokenCallback(object obj) { ManualResetEventSlim mre = obj as ManualResetEventSlim; Debug.Assert(mre != null, "Expected a ManualResetEventSlim"); Debug.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use. lock (mre.m_lock) { Monitor.PulseAll(mre.m_lock); // awaken all waiters } } /// <summary> /// Private helper method for updating parts of a bit-string state value. /// Mainly called from the IsSet and Waiters properties setters /// </summary> /// <remarks> /// Note: the parameter types must be int as CompareExchange cannot take a Uint /// </remarks> /// <param name="newBits">The new value</param> /// <param name="updateBitsMask">The mask used to set the bits</param> private void UpdateStateAtomically(int newBits, int updateBitsMask) { SpinWait sw = new SpinWait(); Debug.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask."); do { int oldState = m_combinedState; // cache the old value for testing in CAS // Procedure:(1) zero the updateBits. eg oldState = [11111111] flag= [00111000] newState = [11000111] // then (2) map in the newBits. eg [11000111] newBits=00101000, newState=[11101111] int newState = (oldState & ~updateBitsMask) | newBits; if (Interlocked.CompareExchange(ref m_combinedState, newState, oldState) == oldState) { return; } sw.SpinOnce(); } while (true); } /// <summary> /// Private helper method - performs Mask and shift, particular helpful to extract a field from a packed word. /// eg ExtractStatePortionAndShiftRight(0x12345678, 0xFF000000, 24) => 0x12, ie extracting the top 8-bits as a simple integer /// /// ?? is there a common place to put this rather than being private to MRES? /// </summary> /// <param name="state"></param> /// <param name="mask"></param> /// <param name="rightBitShiftCount"></param> /// <returns></returns> private static int ExtractStatePortionAndShiftRight(int state, int mask, int rightBitShiftCount) { //convert to uint before shifting so that right-shift does not replicate the sign-bit, //then convert back to int. return unchecked((int)(((uint)(state & mask)) >> rightBitShiftCount)); } /// <summary> /// Performs a Mask operation, but does not perform the shift. /// This is acceptable for boolean values for which the shift is unnecessary /// eg (val &amp; Mask) != 0 is an appropriate way to extract a boolean rather than using /// ((val &amp; Mask) &gt;&gt; shiftAmount) == 1 /// /// ?? is there a common place to put this rather than being private to MRES? /// </summary> /// <param name="state"></param> /// <param name="mask"></param> private static int ExtractStatePortion(int state, int mask) { return state & mask; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: Default way to read streams of resources on ** demand. ** ** Version 2 support on October 6, 2003 ** ===========================================================*/ namespace System.Resources { using System; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Security; using System.Globalization; using System.Configuration.Assemblies; using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.Contracts; // Provides the default implementation of IResourceReader, reading // .resources file from the system default binary format. This class // can be treated as an enumerator once. // // See the RuntimeResourceSet overview for details on the system // default file format. // internal struct ResourceLocator { internal Object _value; // Can be null. Consider WeakReference instead? internal int _dataPos; internal ResourceLocator(int dataPos, Object value) { _dataPos = dataPos; _value = value; } internal int DataPosition { get { return _dataPos; } //set { _dataPos = value; } } // Allows adding in profiling data in a future version, or a special // resource profiling build. We could also use WeakReference. internal Object Value { get { return _value; } set { _value = value; } } internal static bool CanCache(ResourceTypeCode value) { Debug.Assert(value >= 0, "negative ResourceTypeCode. What?"); return value <= ResourceTypeCode.LastPrimitive; } } public sealed class ResourceReader : IResourceReader { // A reasonable default buffer size for reading from files, especially // when we will likely be seeking frequently. Could be smaller, but does // it make sense to use anything less than one page? private const int DefaultFileStreamBufferSize = 4096; private BinaryReader _store; // backing store we're reading from. // Used by RuntimeResourceSet and this class's enumerator. Maps // resource name to a value, a ResourceLocator, or a // LooselyLinkedManifestResource. internal Dictionary<String, ResourceLocator> _resCache; private long _nameSectionOffset; // Offset to name section of file. private long _dataSectionOffset; // Offset to Data section of file. // Note this class is tightly coupled with UnmanagedMemoryStream. // At runtime when getting an embedded resource from an assembly, // we're given an UnmanagedMemoryStream referring to the mmap'ed portion // of the assembly. The pointers here are pointers into that block of // memory controlled by the OS's loader. private int[] _nameHashes; // hash values for all names. private unsafe int* _nameHashesPtr; // In case we're using UnmanagedMemoryStream private int[] _namePositions; // relative locations of names private unsafe int* _namePositionsPtr; // If we're using UnmanagedMemoryStream private RuntimeType[] _typeTable; // Lazy array of Types for resource values. private int[] _typeNamePositions; // To delay initialize type table private int _numResources; // Num of resources files, in case arrays aren't allocated. // We'll include a separate code path that uses UnmanagedMemoryStream to // avoid allocating String objects and the like. private UnmanagedMemoryStream _ums; // Version number of .resources file, for compatibility private int _version; #if RESOURCE_FILE_FORMAT_DEBUG private bool _debug; // Whether this file has debugging stuff in it. #endif public ResourceReader(String fileName) { _resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default); _store = new BinaryReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.RandomAccess), Encoding.UTF8); BCLDebug.Log("RESMGRFILEFORMAT", "ResourceReader .ctor(String). UnmanagedMemoryStream: " + (_ums != null)); try { ReadResources(); } catch { _store.Close(); // If we threw an exception, close the file. throw; } } public ResourceReader(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (!stream.CanRead) throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotReadable")); Contract.EndContractBlock(); _resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default); _store = new BinaryReader(stream, Encoding.UTF8); // We have a faster code path for reading resource files from an assembly. _ums = stream as UnmanagedMemoryStream; BCLDebug.Log("RESMGRFILEFORMAT", "ResourceReader .ctor(Stream). UnmanagedMemoryStream: " + (_ums != null)); ReadResources(); } // This is the constructor the RuntimeResourceSet calls, // passing in the stream to read from and the RuntimeResourceSet's // internal hash table (hash table of names with file offsets // and values, coupled to this ResourceReader). internal ResourceReader(Stream stream, Dictionary<String, ResourceLocator> resCache) { Contract.Requires(stream != null, "Need a stream!"); Contract.Requires(stream.CanRead, "Stream should be readable!"); Contract.Requires(resCache != null, "Need a Dictionary!"); _resCache = resCache; _store = new BinaryReader(stream, Encoding.UTF8); _ums = stream as UnmanagedMemoryStream; BCLDebug.Log("RESMGRFILEFORMAT", "ResourceReader .ctor(Stream, Hashtable). UnmanagedMemoryStream: " + (_ums != null)); ReadResources(); } public void Close() { Dispose(true); } public void Dispose() { Close(); } private unsafe void Dispose(bool disposing) { if (_store != null) { _resCache = null; if (disposing) { // Close the stream in a thread-safe way. This fix means // that we may call Close n times, but that's safe. BinaryReader copyOfStore = _store; _store = null; if (copyOfStore != null) copyOfStore.Close(); } _store = null; _namePositions = null; _nameHashes = null; _ums = null; _namePositionsPtr = null; _nameHashesPtr = null; } } internal static unsafe int ReadUnalignedI4(int* p) { byte* buffer = (byte*)p; // Unaligned, little endian format return buffer[0] | (buffer[1] << 8) | (buffer[2] << 16) | (buffer[3] << 24); } private void SkipString() { int stringLength = _store.Read7BitEncodedInt(); if (stringLength < 0) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_NegativeStringLength")); } _store.BaseStream.Seek(stringLength, SeekOrigin.Current); } private unsafe int GetNameHash(int index) { Debug.Assert(index >= 0 && index < _numResources, "Bad index into hash array. index: " + index); Debug.Assert((_ums == null && _nameHashes != null && _nameHashesPtr == null) || (_ums != null && _nameHashes == null && _nameHashesPtr != null), "Internal state mangled."); if (_ums == null) return _nameHashes[index]; else return ReadUnalignedI4(&_nameHashesPtr[index]); } private unsafe int GetNamePosition(int index) { Debug.Assert(index >= 0 && index < _numResources, "Bad index into name position array. index: " + index); Debug.Assert((_ums == null && _namePositions != null && _namePositionsPtr == null) || (_ums != null && _namePositions == null && _namePositionsPtr != null), "Internal state mangled."); int r; if (_ums == null) r = _namePositions[index]; else r = ReadUnalignedI4(&_namePositionsPtr[index]); if (r < 0 || r > _dataSectionOffset - _nameSectionOffset) { throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesNameInvalidOffset", r)); } return r; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IDictionaryEnumerator GetEnumerator() { if (_resCache == null) throw new InvalidOperationException(Environment.GetResourceString("ResourceReaderIsClosed")); return new ResourceEnumerator(this); } internal ResourceEnumerator GetEnumeratorInternal() { return new ResourceEnumerator(this); } // From a name, finds the associated virtual offset for the data. // To read the data, seek to _dataSectionOffset + dataPos, then // read the resource type & data. // This does a binary search through the names. internal int FindPosForResource(String name) { Debug.Assert(_store != null, "ResourceReader is closed!"); int hash = FastResourceComparer.HashFunction(name); BCLDebug.Log("RESMGRFILEFORMAT", "FindPosForResource for " + name + " hash: " + hash.ToString("x", CultureInfo.InvariantCulture)); // Binary search over the hashes. Use the _namePositions array to // determine where they exist in the underlying stream. int lo = 0; int hi = _numResources - 1; int index = -1; bool success = false; while (lo <= hi) { index = (lo + hi) >> 1; // Do NOT use subtraction here, since it will wrap for large // negative numbers. int currentHash = GetNameHash(index); int c; if (currentHash == hash) c = 0; else if (currentHash < hash) c = -1; else c = 1; //BCLDebug.Log("RESMGRFILEFORMAT", " Probing index "+index+" lo: "+lo+" hi: "+hi+" c: "+c); if (c == 0) { success = true; break; } if (c < 0) lo = index + 1; else hi = index - 1; } if (!success) { #if RESOURCE_FILE_FORMAT_DEBUG String lastReadString; lock(this) { _store.BaseStream.Seek(_nameSectionOffset + GetNamePosition(index), SeekOrigin.Begin); lastReadString = _store.ReadString(); } BCLDebug.Log("RESMGRFILEFORMAT", LogLevel.Status, "FindPosForResource for ", name, " failed. i: ", index, " lo: ", lo, " hi: ", hi, " last read string: \"", lastReadString, '\''); #endif return -1; } // index is the location in our hash array that corresponds with a // value in the namePositions array. // There could be collisions in our hash function. Check on both sides // of index to find the range of hash values that are equal to the // target hash value. if (lo != index) { lo = index; while (lo > 0 && GetNameHash(lo - 1) == hash) lo--; } if (hi != index) { hi = index; while (hi < _numResources - 1 && GetNameHash(hi + 1) == hash) hi++; } lock (this) { for (int i = lo; i <= hi; i++) { _store.BaseStream.Seek(_nameSectionOffset + GetNamePosition(i), SeekOrigin.Begin); if (CompareStringEqualsName(name)) { int dataPos = _store.ReadInt32(); if (dataPos < 0 || dataPos >= _store.BaseStream.Length - _dataSectionOffset) { throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesDataInvalidOffset", dataPos)); } return dataPos; } } } BCLDebug.Log("RESMGRFILEFORMAT", "FindPosForResource for " + name + ": Found a hash collision, HOWEVER, neither of these collided values equaled the given string."); return -1; } // This compares the String in the .resources file at the current position // with the string you pass in. // Whoever calls this method should make sure that they take a lock // so no one else can cause us to seek in the stream. private unsafe bool CompareStringEqualsName(String name) { Debug.Assert(_store != null, "ResourceReader is closed!"); int byteLen = _store.Read7BitEncodedInt(); if (byteLen < 0) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_NegativeStringLength")); } if (_ums != null) { byte* bytes = _ums.PositionPointer; // Skip over the data in the Stream, positioning ourselves right after it. _ums.Seek(byteLen, SeekOrigin.Current); if (_ums.Position > _ums.Length) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesNameTooLong")); } // On 64-bit machines, these char*'s may be misaligned. Use a // byte-by-byte comparison instead. //return FastResourceComparer.CompareOrdinal((char*)bytes, byteLen/2, name) == 0; return FastResourceComparer.CompareOrdinal(bytes, byteLen, name) == 0; } else { // This code needs to be fast byte[] bytes = new byte[byteLen]; int numBytesToRead = byteLen; while (numBytesToRead > 0) { int n = _store.Read(bytes, byteLen - numBytesToRead, numBytesToRead); if (n == 0) throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceNameCorrupted")); numBytesToRead -= n; } return FastResourceComparer.CompareOrdinal(bytes, byteLen / 2, name) == 0; } } // This is used in the enumerator. The enumerator iterates from 0 to n // of our resources and this returns the resource name for a particular // index. The parameter is NOT a virtual offset. private unsafe String AllocateStringForNameIndex(int index, out int dataOffset) { Debug.Assert(_store != null, "ResourceReader is closed!"); byte[] bytes; int byteLen; long nameVA = GetNamePosition(index); lock (this) { _store.BaseStream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin); // Can't use _store.ReadString, since it's using UTF-8! byteLen = _store.Read7BitEncodedInt(); if (byteLen < 0) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_NegativeStringLength")); } if (_ums != null) { if (_ums.Position > _ums.Length - byteLen) throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesIndexTooLong", index)); String s = null; char* charPtr = (char*)_ums.PositionPointer; #if IA64 if (((int)charPtr & 1) != 0) { char[] destArray = new char[byteLen/2]; fixed(char* pDest = destArray) { Buffer.Memcpy((byte*)pDest, (byte*)charPtr, byteLen); } s = new String(destArray); } else { #endif //IA64 s = new String(charPtr, 0, byteLen / 2); #if IA64 } #endif //IA64 _ums.Position += byteLen; dataOffset = _store.ReadInt32(); if (dataOffset < 0 || dataOffset >= _store.BaseStream.Length - _dataSectionOffset) { throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesDataInvalidOffset", dataOffset)); } return s; } bytes = new byte[byteLen]; // We must read byteLen bytes, or we have a corrupted file. // Use a blocking read in case the stream doesn't give us back // everything immediately. int count = byteLen; while (count > 0) { int n = _store.Read(bytes, byteLen - count, count); if (n == 0) throw new EndOfStreamException(Environment.GetResourceString("BadImageFormat_ResourceNameCorrupted_NameIndex", index)); count -= n; } dataOffset = _store.ReadInt32(); if (dataOffset < 0 || dataOffset >= _store.BaseStream.Length - _dataSectionOffset) { throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesDataInvalidOffset", dataOffset)); } } return Encoding.Unicode.GetString(bytes, 0, byteLen); } // This is used in the enumerator. The enumerator iterates from 0 to n // of our resources and this returns the resource value for a particular // index. The parameter is NOT a virtual offset. private Object GetValueForNameIndex(int index) { Debug.Assert(_store != null, "ResourceReader is closed!"); long nameVA = GetNamePosition(index); lock (this) { _store.BaseStream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin); SkipString(); //BCLDebug.Log("RESMGRFILEFORMAT", "GetValueForNameIndex for index: "+index+" skip (name length): "+skip); int dataPos = _store.ReadInt32(); if (dataPos < 0 || dataPos >= _store.BaseStream.Length - _dataSectionOffset) { throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesDataInvalidOffset", dataPos)); } BCLDebug.Log("RESMGRFILEFORMAT", "GetValueForNameIndex: dataPos: " + dataPos); ResourceTypeCode junk; if (_version == 1) return LoadObjectV1(dataPos); else return LoadObjectV2(dataPos, out junk); } } // This takes a virtual offset into the data section and reads a String // from that location. // Anyone who calls LoadObject should make sure they take a lock so // no one can cause us to do a seek in here. internal String LoadString(int pos) { Debug.Assert(_store != null, "ResourceReader is closed!"); _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); String s = null; int typeIndex = _store.Read7BitEncodedInt(); if (_version == 1) { if (typeIndex == -1) return null; if (FindType(typeIndex) != typeof(String)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Type", FindType(typeIndex).FullName)); s = _store.ReadString(); } else { ResourceTypeCode typeCode = (ResourceTypeCode)typeIndex; if (typeCode != ResourceTypeCode.String && typeCode != ResourceTypeCode.Null) { String typeString; if (typeCode < ResourceTypeCode.StartOfUserTypes) typeString = typeCode.ToString(); else typeString = FindType(typeCode - ResourceTypeCode.StartOfUserTypes).FullName; throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Type", typeString)); } if (typeCode == ResourceTypeCode.String) // ignore Null s = _store.ReadString(); } BCLDebug.Log("RESMGRFILEFORMAT", "LoadString(" + pos.ToString("x", CultureInfo.InvariantCulture) + " returned " + (s == null ? "[a null string]" : s)); return s; } // Called from RuntimeResourceSet internal Object LoadObject(int pos) { if (_version == 1) return LoadObjectV1(pos); ResourceTypeCode typeCode; return LoadObjectV2(pos, out typeCode); } internal Object LoadObject(int pos, out ResourceTypeCode typeCode) { if (_version == 1) { Object o = LoadObjectV1(pos); typeCode = (o is String) ? ResourceTypeCode.String : ResourceTypeCode.StartOfUserTypes; return o; } return LoadObjectV2(pos, out typeCode); } // This takes a virtual offset into the data section and reads an Object // from that location. // Anyone who calls LoadObject should make sure they take a lock so // no one can cause us to do a seek in here. internal Object LoadObjectV1(int pos) { Debug.Assert(_store != null, "ResourceReader is closed!"); Debug.Assert(_version == 1, ".resources file was not a V1 .resources file!"); try { // mega try-catch performs exceptionally bad on x64; factored out body into // _LoadObjectV1 and wrap here. return _LoadObjectV1(pos); } catch (EndOfStreamException eof) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"), eof); } catch (ArgumentOutOfRangeException e) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"), e); } } private Object _LoadObjectV1(int pos) { _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); int typeIndex = _store.Read7BitEncodedInt(); if (typeIndex == -1) return null; RuntimeType type = FindType(typeIndex); BCLDebug.Log("RESMGRFILEFORMAT", "LoadObject type: " + type.Name + " pos: 0x" + _store.BaseStream.Position.ToString("x", CultureInfo.InvariantCulture)); // Consider putting in logic to see if this type is a // primitive or a value type first, so we can reach the // deserialization code faster for arbitrary objects. if (type == typeof(String)) return _store.ReadString(); else if (type == typeof(Int32)) return _store.ReadInt32(); else if (type == typeof(Byte)) return _store.ReadByte(); else if (type == typeof(SByte)) return _store.ReadSByte(); else if (type == typeof(Int16)) return _store.ReadInt16(); else if (type == typeof(Int64)) return _store.ReadInt64(); else if (type == typeof(UInt16)) return _store.ReadUInt16(); else if (type == typeof(UInt32)) return _store.ReadUInt32(); else if (type == typeof(UInt64)) return _store.ReadUInt64(); else if (type == typeof(Single)) return _store.ReadSingle(); else if (type == typeof(Double)) return _store.ReadDouble(); else if (type == typeof(DateTime)) { // Ideally we should use DateTime's ToBinary & FromBinary, // but we can't for compatibility reasons. return new DateTime(_store.ReadInt64()); } else if (type == typeof(TimeSpan)) return new TimeSpan(_store.ReadInt64()); else if (type == typeof(Decimal)) { int[] bits = new int[4]; for (int i = 0; i < bits.Length; i++) bits[i] = _store.ReadInt32(); return new Decimal(bits); } else { throw new NotSupportedException(Environment.GetResourceString("NotSupported_ResourceObjectSerialization")); } } internal Object LoadObjectV2(int pos, out ResourceTypeCode typeCode) { Debug.Assert(_store != null, "ResourceReader is closed!"); Debug.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!"); try { // mega try-catch performs exceptionally bad on x64; factored out body into // _LoadObjectV2 and wrap here. return _LoadObjectV2(pos, out typeCode); } catch (EndOfStreamException eof) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"), eof); } catch (ArgumentOutOfRangeException e) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"), e); } } private Object _LoadObjectV2(int pos, out ResourceTypeCode typeCode) { _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); typeCode = (ResourceTypeCode)_store.Read7BitEncodedInt(); BCLDebug.Log("RESMGRFILEFORMAT", "LoadObjectV2 type: " + typeCode + " pos: 0x" + _store.BaseStream.Position.ToString("x", CultureInfo.InvariantCulture)); switch (typeCode) { case ResourceTypeCode.Null: return null; case ResourceTypeCode.String: return _store.ReadString(); case ResourceTypeCode.Boolean: return _store.ReadBoolean(); case ResourceTypeCode.Char: return (char)_store.ReadUInt16(); case ResourceTypeCode.Byte: return _store.ReadByte(); case ResourceTypeCode.SByte: return _store.ReadSByte(); case ResourceTypeCode.Int16: return _store.ReadInt16(); case ResourceTypeCode.UInt16: return _store.ReadUInt16(); case ResourceTypeCode.Int32: return _store.ReadInt32(); case ResourceTypeCode.UInt32: return _store.ReadUInt32(); case ResourceTypeCode.Int64: return _store.ReadInt64(); case ResourceTypeCode.UInt64: return _store.ReadUInt64(); case ResourceTypeCode.Single: return _store.ReadSingle(); case ResourceTypeCode.Double: return _store.ReadDouble(); case ResourceTypeCode.Decimal: return _store.ReadDecimal(); case ResourceTypeCode.DateTime: // Use DateTime's ToBinary & FromBinary. Int64 data = _store.ReadInt64(); return DateTime.FromBinary(data); case ResourceTypeCode.TimeSpan: Int64 ticks = _store.ReadInt64(); return new TimeSpan(ticks); // Special types case ResourceTypeCode.ByteArray: { int len = _store.ReadInt32(); if (len < 0) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", len)); } if (_ums == null) { if (len > _store.BaseStream.Length) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", len)); } return _store.ReadBytes(len); } if (len > _ums.Length - _ums.Position) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", len)); } byte[] bytes = new byte[len]; int r = _ums.Read(bytes, 0, len); Debug.Assert(r == len, "ResourceReader needs to use a blocking read here. (Call _store.ReadBytes(len)?)"); return bytes; } case ResourceTypeCode.Stream: { int len = _store.ReadInt32(); if (len < 0) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", len)); } if (_ums == null) { byte[] bytes = _store.ReadBytes(len); // Lifetime of memory == lifetime of this stream. return new PinnedBufferMemoryStream(bytes); } // make sure we don't create an UnmanagedMemoryStream that is longer than the resource stream. if (len > _ums.Length - _ums.Position) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", len)); } // For the case that we've memory mapped in the .resources // file, just return a Stream pointing to that block of memory. unsafe { return new UnmanagedMemoryStream(_ums.PositionPointer, len, len, FileAccess.Read); } } default: if (typeCode < ResourceTypeCode.StartOfUserTypes) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch")); } break; } // Normal serialized objects throw new NotSupportedException(Environment.GetResourceString("NotSupported_ResourceObjectSerialization")); } // Reads in the header information for a .resources file. Verifies some // of the assumptions about this resource set, and builds the class table // for the default resource file format. private void ReadResources() { Debug.Assert(_store != null, "ResourceReader is closed!"); try { // mega try-catch performs exceptionally bad on x64; factored out body into // _ReadResources and wrap here. _ReadResources(); } catch (EndOfStreamException eof) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"), eof); } catch (IndexOutOfRangeException e) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"), e); } } private void _ReadResources() { // Read ResourceManager header // Check for magic number int magicNum = _store.ReadInt32(); if (magicNum != ResourceManager.MagicNumber) throw new ArgumentException(Environment.GetResourceString("Resources_StreamNotValid")); // Assuming this is ResourceManager header V1 or greater, hopefully // after the version number there is a number of bytes to skip // to bypass the rest of the ResMgr header. For V2 or greater, we // use this to skip to the end of the header int resMgrHeaderVersion = _store.ReadInt32(); int numBytesToSkip = _store.ReadInt32(); if (numBytesToSkip < 0 || resMgrHeaderVersion < 0) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted")); } if (resMgrHeaderVersion > 1) { BCLDebug.Log("RESMGRFILEFORMAT", LogLevel.Status, "ReadResources: Unexpected ResMgr header version: {0} Skipping ahead {1} bytes.", resMgrHeaderVersion, numBytesToSkip); _store.BaseStream.Seek(numBytesToSkip, SeekOrigin.Current); } else { BCLDebug.Log("RESMGRFILEFORMAT", "ReadResources: Parsing ResMgr header v1."); // We don't care about numBytesToSkip; read the rest of the header // Read in type name for a suitable ResourceReader // Note ResourceWriter & InternalResGen use different Strings. String readerType = _store.ReadString(); readerType = System.CoreLib.FixupCoreLibName(readerType); AssemblyName mscorlib = new AssemblyName(ResourceManager.MscorlibName); if (!ResourceManager.CompareNames(readerType, ResourceManager.ResReaderTypeName, mscorlib)) throw new NotSupportedException(Environment.GetResourceString("NotSupported_WrongResourceReader_Type", readerType)); // Skip over type name for a suitable ResourceSet SkipString(); } // Read RuntimeResourceSet header // Do file version check int version = _store.ReadInt32(); if (version != RuntimeResourceSet.Version && version != 1) throw new ArgumentException(Environment.GetResourceString("Arg_ResourceFileUnsupportedVersion", RuntimeResourceSet.Version, version)); _version = version; #if RESOURCE_FILE_FORMAT_DEBUG // Look for ***DEBUG*** to see if this is a debuggable file. long oldPos = _store.BaseStream.Position; _debug = false; try { String debugString = _store.ReadString(); _debug = String.Equals("***DEBUG***", debugString); } catch(IOException) { } catch(OutOfMemoryException) { } if (_debug) { Console.WriteLine("ResourceReader is looking at a debuggable .resources file, version {0}", _version); } else { _store.BaseStream.Position = oldPos; } #endif _numResources = _store.ReadInt32(); if (_numResources < 0) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted")); } BCLDebug.Log("RESMGRFILEFORMAT", "ReadResources: Expecting " + _numResources + " resources."); #if RESOURCE_FILE_FORMAT_DEBUG if (ResourceManager.DEBUG >= 4) Console.WriteLine("ResourceReader::ReadResources - Reading in "+_numResources+" resources"); #endif // Read type positions into type positions array. // But delay initialize the type table. int numTypes = _store.ReadInt32(); if (numTypes < 0) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted")); } _typeTable = new RuntimeType[numTypes]; _typeNamePositions = new int[numTypes]; for (int i = 0; i < numTypes; i++) { _typeNamePositions[i] = (int)_store.BaseStream.Position; // Skip over the Strings in the file. Don't create types. SkipString(); } #if RESOURCE_FILE_FORMAT_DEBUG if (ResourceManager.DEBUG >= 5) Console.WriteLine("ResourceReader::ReadResources - Reading in "+numTypes+" type table entries"); #endif // Prepare to read in the array of name hashes // Note that the name hashes array is aligned to 8 bytes so // we can use pointers into it on 64 bit machines. (4 bytes // may be sufficient, but let's plan for the future) // Skip over alignment stuff. All public .resources files // should be aligned No need to verify the byte values. long pos = _store.BaseStream.Position; int alignBytes = ((int)pos) & 7; if (alignBytes != 0) { for (int i = 0; i < 8 - alignBytes; i++) { _store.ReadByte(); } } // Read in the array of name hashes #if RESOURCE_FILE_FORMAT_DEBUG // Skip over "HASHES->" if (_debug) { _store.BaseStream.Position += 8; } #endif if (_ums == null) { _nameHashes = new int[_numResources]; for (int i = 0; i < _numResources; i++) { _nameHashes[i] = _store.ReadInt32(); } } else { int seekPos = unchecked(4 * _numResources); if (seekPos < 0) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted")); } unsafe { _nameHashesPtr = (int*)_ums.PositionPointer; // Skip over the array of nameHashes. _ums.Seek(seekPos, SeekOrigin.Current); // get the position pointer once more to check that the whole table is within the stream byte* junk = _ums.PositionPointer; } } // Read in the array of relative positions for all the names. #if RESOURCE_FILE_FORMAT_DEBUG // Skip over "POS---->" if (_debug) { _store.BaseStream.Position += 8; } #endif if (_ums == null) { _namePositions = new int[_numResources]; for (int i = 0; i < _numResources; i++) { int namePosition = _store.ReadInt32(); if (namePosition < 0) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted")); } _namePositions[i] = namePosition; } } else { int seekPos = unchecked(4 * _numResources); if (seekPos < 0) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted")); } unsafe { _namePositionsPtr = (int*)_ums.PositionPointer; // Skip over the array of namePositions. _ums.Seek(seekPos, SeekOrigin.Current); // get the position pointer once more to check that the whole table is within the stream byte* junk = _ums.PositionPointer; } } // Read location of data section. _dataSectionOffset = _store.ReadInt32(); if (_dataSectionOffset < 0) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted")); } // Store current location as start of name section _nameSectionOffset = _store.BaseStream.Position; // _nameSectionOffset should be <= _dataSectionOffset; if not, it's corrupt if (_dataSectionOffset < _nameSectionOffset) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted")); } BCLDebug.Log("RESMGRFILEFORMAT", String.Format(CultureInfo.InvariantCulture, "ReadResources: _nameOffset = 0x{0:x} _dataOffset = 0x{1:x}", _nameSectionOffset, _dataSectionOffset)); } // This allows us to delay-initialize the Type[]. This might be a // good startup time savings, since we might have to load assemblies // and initialize Reflection. private RuntimeType FindType(int typeIndex) { if (typeIndex < 0 || typeIndex >= _typeTable.Length) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_InvalidType")); } if (_typeTable[typeIndex] == null) { long oldPos = _store.BaseStream.Position; try { _store.BaseStream.Position = _typeNamePositions[typeIndex]; String typeName = _store.ReadString(); _typeTable[typeIndex] = (RuntimeType)Type.GetType(typeName, true); } // If serialization isn't supported, we convert FileNotFoundException to // NotSupportedException for consistency with v2. This is a corner-case, but the // idea is that we want to give the user a more accurate error message. Even if // the dependency were found, we know it will require serialization since it // can't be one of the types we special case. So if the dependency were found, // it would go down the serialization code path, resulting in NotSupported for // SKUs without serialization. // // We don't want to regress the expected case by checking the type info before // getting to Type.GetType -- this is costly with v1 resource formats. catch (FileNotFoundException) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_ResourceObjectSerialization")); } finally { _store.BaseStream.Position = oldPos; } } Debug.Assert(_typeTable[typeIndex] != null, "Should have found a type!"); return _typeTable[typeIndex]; } public void GetResourceData(String resourceName, out String resourceType, out byte[] resourceData) { if (resourceName == null) throw new ArgumentNullException(nameof(resourceName)); Contract.EndContractBlock(); if (_resCache == null) throw new InvalidOperationException(Environment.GetResourceString("ResourceReaderIsClosed")); // Get the type information from the data section. Also, // sort all of the data section's indexes to compute length of // the serialized data for this type (making sure to subtract // off the length of the type code). int[] sortedDataPositions = new int[_numResources]; int dataPos = FindPosForResource(resourceName); if (dataPos == -1) { throw new ArgumentException(Environment.GetResourceString("Arg_ResourceNameNotExist", resourceName)); } lock (this) { // Read all the positions of data within the data section. for (int i = 0; i < _numResources; i++) { _store.BaseStream.Position = _nameSectionOffset + GetNamePosition(i); // Skip over name of resource int numBytesToSkip = _store.Read7BitEncodedInt(); if (numBytesToSkip < 0) { throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesNameInvalidOffset", numBytesToSkip)); } _store.BaseStream.Position += numBytesToSkip; int dPos = _store.ReadInt32(); if (dPos < 0 || dPos >= _store.BaseStream.Length - _dataSectionOffset) { throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesDataInvalidOffset", dPos)); } sortedDataPositions[i] = dPos; } Array.Sort(sortedDataPositions); int index = Array.BinarySearch(sortedDataPositions, dataPos); Debug.Assert(index >= 0 && index < _numResources, "Couldn't find data position within sorted data positions array!"); long nextData = (index < _numResources - 1) ? sortedDataPositions[index + 1] + _dataSectionOffset : _store.BaseStream.Length; int len = (int)(nextData - (dataPos + _dataSectionOffset)); Debug.Assert(len >= 0 && len <= (int)_store.BaseStream.Length - dataPos + _dataSectionOffset, "Length was negative or outside the bounds of the file!"); // Read type code then byte[] _store.BaseStream.Position = _dataSectionOffset + dataPos; ResourceTypeCode typeCode = (ResourceTypeCode)_store.Read7BitEncodedInt(); if (typeCode < 0 || typeCode >= ResourceTypeCode.StartOfUserTypes + _typeTable.Length) { throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_InvalidType")); } resourceType = TypeNameFromTypeCode(typeCode); // The length must be adjusted to subtract off the number // of bytes in the 7 bit encoded type code. len -= (int)(_store.BaseStream.Position - (_dataSectionOffset + dataPos)); byte[] bytes = _store.ReadBytes(len); if (bytes.Length != len) throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourceNameCorrupted")); resourceData = bytes; } } private String TypeNameFromTypeCode(ResourceTypeCode typeCode) { Contract.Requires(typeCode >= 0, "can't be negative"); if (typeCode < ResourceTypeCode.StartOfUserTypes) { Debug.Assert(!String.Equals(typeCode.ToString(), "LastPrimitive"), "Change ResourceTypeCode metadata order so LastPrimitive isn't what Enum.ToString prefers."); return "ResourceTypeCode." + typeCode.ToString(); } else { int typeIndex = typeCode - ResourceTypeCode.StartOfUserTypes; Debug.Assert(typeIndex >= 0 && typeIndex < _typeTable.Length, "TypeCode is broken or corrupted!"); long oldPos = _store.BaseStream.Position; try { _store.BaseStream.Position = _typeNamePositions[typeIndex]; return _store.ReadString(); } finally { _store.BaseStream.Position = oldPos; } } } internal sealed class ResourceEnumerator : IDictionaryEnumerator { private const int ENUM_DONE = Int32.MinValue; private const int ENUM_NOT_STARTED = -1; private ResourceReader _reader; private bool _currentIsValid; private int _currentName; private int _dataPosition; // cached for case-insensitive table internal ResourceEnumerator(ResourceReader reader) { _currentName = ENUM_NOT_STARTED; _reader = reader; _dataPosition = -2; } public bool MoveNext() { if (_currentName == _reader._numResources - 1 || _currentName == ENUM_DONE) { _currentIsValid = false; _currentName = ENUM_DONE; return false; } _currentIsValid = true; _currentName++; return true; } public Object Key { get { if (_currentName == ENUM_DONE) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded)); if (!_currentIsValid) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted)); if (_reader._resCache == null) throw new InvalidOperationException(Environment.GetResourceString("ResourceReaderIsClosed")); return _reader.AllocateStringForNameIndex(_currentName, out _dataPosition); } } public Object Current { get { return Entry; } } // Warning: This requires that you call the Key or Entry property FIRST before calling it! internal int DataPosition { get { return _dataPosition; } } public DictionaryEntry Entry { get { if (_currentName == ENUM_DONE) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded)); if (!_currentIsValid) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted)); if (_reader._resCache == null) throw new InvalidOperationException(Environment.GetResourceString("ResourceReaderIsClosed")); String key; Object value = null; lock (_reader) { // locks should be taken in the same order as in RuntimeResourceSet.GetObject to avoid deadlock lock (_reader._resCache) { key = _reader.AllocateStringForNameIndex(_currentName, out _dataPosition); // AllocateStringForNameIndex could lock on _reader ResourceLocator locator; if (_reader._resCache.TryGetValue(key, out locator)) { value = locator.Value; } if (value == null) { if (_dataPosition == -1) value = _reader.GetValueForNameIndex(_currentName); else value = _reader.LoadObject(_dataPosition); // If enumeration and subsequent lookups happen very // frequently in the same process, add a ResourceLocator // to _resCache here. But WinForms enumerates and // just about everyone else does lookups. So caching // here may bloat working set. } } } return new DictionaryEntry(key, value); } } public Object Value { get { if (_currentName == ENUM_DONE) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded)); if (!_currentIsValid) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted)); if (_reader._resCache == null) throw new InvalidOperationException(Environment.GetResourceString("ResourceReaderIsClosed")); // Consider using _resCache here, eventually, if // this proves to be an interesting perf scenario. // But mixing lookups and enumerators shouldn't be // particularly compelling. return _reader.GetValueForNameIndex(_currentName); } } public void Reset() { if (_reader._resCache == null) throw new InvalidOperationException(Environment.GetResourceString("ResourceReaderIsClosed")); _currentIsValid = false; _currentName = ENUM_NOT_STARTED; } } } }
using System; using System.Linq; using FF9; using Memoria; using Memoria.Data; public class btl_scrp { public static UInt16 GetBattleID(UInt32 list_no) { UInt16 num = 0; for (BTL_DATA next = FF9StateSystem.Battle.FF9Battle.btl_list.next; next != null; next = next.next) { switch (list_no) { case 0u: if (next.bi.player != 0) num |= next.btl_id; break; case 1u: if (next.bi.player == 0) num |= next.btl_id; break; case 2u: num |= next.btl_id; break; } } return num; } public static BattleUnit FindBattleUnit(UInt16 btl_id) { return FF9StateSystem.Battle.FF9Battle.EnumerateBattleUnits().FirstOrDefault(u => u.Id == btl_id); } public static BattleUnit FindBattleUnitUnlimited(UInt16 btl_id) { FF9StateBattleSystem ff9Battle = FF9StateSystem.Battle.FF9Battle; for (Int32 i = 0; i < 8; i++) if (ff9Battle.btl_data[i].btl_id == btl_id) return new BattleUnit(ff9Battle.btl_data[i]); return null; } // Try to have the most possible AI script compatibility public static CMD_DATA GetCurrentCommandSmart(BTL_DATA btl) { FF9StateBattleSystem ff9Battle = FF9StateSystem.Battle.FF9Battle; if (btl == null || Configuration.Battle.Speed < 3) return ff9Battle.cur_cmd; CMD_DATA cmd = PersistenSingleton<EventEngine>.Instance.GetTriggeringCommand(btl); if (cmd != null) return cmd; for (Int32 i = 0; i < 6; i++) if (ff9Battle.cur_cmd_list.Contains(btl.cmd[i])) return btl.cmd[i]; return ff9Battle.cur_cmd; } #region Memoria Battle Script public static UInt16 GetCurrentCommandData(UInt16 data_type, BTL_DATA btl = null) { // Access the current command's stats from battle scripts (SV_5 and SV_6) // Usage: // set SV_5 = Spell stat ID of the currently used spell to access // set spellstat = SV_6 CMD_DATA cmd = GetCurrentCommandSmart(btl); if (cmd == null) return 0; switch (data_type) { case 1000: return (UInt16)cmd.tar_id; case 1001: return (UInt16)cmd.cmd_no; case 1002: return (UInt16)cmd.sub_no; case 1003: return (UInt16)(cmd.IsShortRange ? 1 : 0); case 1004: return (UInt16)cmd.info.cursor; case 1005: return (UInt16)cmd.info.stat; case 1006: return (UInt16)cmd.info.priority; case 1007: return (UInt16)cmd.info.cover; case 1008: return (UInt16)cmd.ScriptId; case 1009: return (UInt16)cmd.Power; case 1010: return (UInt16)cmd.Element; case 1011: return (UInt16)cmd.HitRate; case 1012: return (UInt16)cmd.AbilityCategory; case 1013: return (UInt16)0; case 1014: return (UInt16)cmd.info.CustomMPCost; case 1015: return (UInt16)cmd.AbilityType; case 1016: return (UInt16)((UInt32)cmd.AbilityStatus >> 16); case 1017: return (UInt16)((UInt32)cmd.AbilityStatus & 0xFFFF); case 1018: return (UInt16)cmd.info.dodge; case 1019: return (UInt16)cmd.info.reflec; case 1020: return (UInt16)cmd.info.meteor_miss; case 1021: return (UInt16)cmd.info.short_summon; case 1022: return (UInt16)cmd.info.mon_reflec; case 1023: return (UInt16)(cmd.info.IsZeroMP ? 1 : 0); case 1024: return (UInt16)(cmd.info.ReflectNull ? 1 : 0); } if (data_type < 17 && cmd.aa == null) return 0; switch (data_type) { case 0: return (UInt16)cmd.aa.Info.Target; case 1: return (UInt16)(cmd.aa.Info.DefaultAlly ? 1 : 0); case 2: return (UInt16)cmd.aa.Info.DisplayStats; case 3: return (UInt16)cmd.aa.Info.VfxIndex; case 4: return (UInt16)0; // SoundFxIndex... Memoria ignores it case 5: return (UInt16)(cmd.aa.Info.ForDead ? 1 : 0); case 6: return (UInt16)(cmd.aa.Info.DefaultCamera ? 1 : 0); case 7: return (UInt16)(cmd.aa.Info.DefaultOnDead ? 1 : 0); case 8: return (UInt16)cmd.aa.Ref.ScriptId; case 9: return (UInt16)cmd.aa.Ref.Power; case 10: return (UInt16)cmd.aa.Ref.Elements; case 11: return (UInt16)cmd.aa.Ref.Rate; case 12: return (UInt16)cmd.aa.Category; case 13: return (UInt16)cmd.aa.AddNo; case 14: return (UInt16)cmd.aa.MP; case 15: return (UInt16)cmd.aa.Type; case 16: return (UInt16)cmd.aa.Vfx2; case 17: return (UInt16)cmd.tar_id; case 18: return (UInt16)cmd.cmd_no; case 19: return (UInt16)cmd.sub_no; } return 0; } public static void SetCurrentCommandData(UInt16 data_type, Int32 val, BTL_DATA btl = null) { // Modify the current command's stats from battle scripts (SV_5 and SV_6) // Usage: // set SV_5 = Spell stat ID of the currently used spell to modify // set SV_6 = newvalue // Note that changes to party's spells are permanent until the game closes CMD_DATA cmd = GetCurrentCommandSmart(btl); if (cmd == null) return; switch (data_type) { case 1000: cmd.tar_id = (UInt16)val; return; case 1001: cmd.cmd_no = (BattleCommandId)val; return; case 1002: cmd.sub_no = (Byte)val; return; case 1003: cmd.IsShortRange = val != 0; return; case 1004: cmd.info.cursor = (Byte)val; return; case 1005: cmd.info.stat = (Byte)val; return; case 1006: cmd.info.priority = (Byte)val; return; case 1007: cmd.info.cover = (Byte)val; return; case 1008: cmd.ScriptId = (Byte)val; return; case 1009: cmd.Power = (Byte)val; return; case 1010: cmd.Element = (EffectElement)val; return; case 1011: cmd.HitRate = (Byte)val; return; case 1012: cmd.AbilityCategory = (Byte)val; return; case 1013: return; case 1014: cmd.info.CustomMPCost = val; return; case 1015: cmd.AbilityType = (Byte)val; return; case 1016: cmd.AbilityStatus = (BattleStatus)(((UInt32)cmd.AbilityStatus & 0xFFFFu) | ((UInt32)(val & 0xFFFF) << 16)); return; case 1017: cmd.AbilityStatus = (BattleStatus)(((UInt32)cmd.AbilityStatus & 0xFFFF0000u) | (UInt32)(val & 0xFFFF)); return; case 1018: cmd.info.dodge = (Byte)val; return; case 1019: cmd.info.reflec = (Byte)val; return; case 1020: cmd.info.meteor_miss = (Byte)val; return; case 1021: cmd.info.short_summon = (Byte)val; return; case 1022: cmd.info.mon_reflec = (Byte)val; return; case 1023: cmd.info.IsZeroMP = val != 0; return; case 1024: cmd.info.ReflectNull = val != 0; return; } if (data_type < 17 && cmd.aa == null) return; switch (data_type) { case 0: cmd.aa.Info.Target = (TargetType)val; return; case 1: cmd.aa.Info.DefaultAlly = val != 0; return; case 2: cmd.aa.Info.DisplayStats = (TargetDisplay)val; return; case 3: cmd.aa.Info.VfxIndex = (Int16)val; return; case 4: return; case 5: cmd.aa.Info.ForDead = val != 0; return; case 6: cmd.aa.Info.DefaultCamera = val != 0; return; case 7: cmd.aa.Info.DefaultOnDead = val != 0; return; case 8: cmd.aa.Ref.ScriptId = (Byte)val; return; case 9: cmd.aa.Ref.Power = (Byte)val; return; case 10: cmd.aa.Ref.Elements = (Byte)val; return; case 11: cmd.aa.Ref.Rate = (Byte)val; return; case 12: cmd.aa.Category = (Byte)val; return; case 13: cmd.aa.AddNo = (Byte)val; return; case 14: cmd.aa.MP = (Byte)val; return; case 15: cmd.aa.Type = (Byte)val; return; case 16: cmd.aa.Vfx2 = (UInt16)val; return; case 17: cmd.tar_id = (UInt16)val; return; case 18: cmd.cmd_no = (BattleCommandId)val; return; case 19: cmd.sub_no = (Byte)val; return; } } #endregion public static Int32 GetCharacterData(BTL_DATA btl, UInt32 id) { Int32 result = 16777215; switch (id) { case 35u: result = (Int32)btl.max.hp; break; case 36u: result = (Int32)btl.cur.hp; break; case 37u: result = (Int32)btl.max.mp; break; case 38u: result = (Int32)btl.cur.mp; break; case 39u: result = (Int32)btl.max.at; break; case 40u: result = (Int32)btl.cur.at; break; case 41u: if (btl.bi.player != 0) result = btl_util.getPlayerPtr(btl).level; else result = btl_util.getEnemyTypePtr(btl).level; break; case 42u: result = (Int32)((UInt32)btl.stat.invalid >> 24); break; case 43u: result = (Int32)((UInt32)btl.stat.invalid & 16777215u); break; case 44u: result = (Int32)((UInt32)btl.stat.permanent >> 24); break; case 45u: result = (Int32)((UInt32)btl.stat.permanent & 16777215u); break; case 46u: result = (Int32)((UInt32)btl.stat.cur >> 24); break; case 47u: result = (Int32)((UInt32)btl.stat.cur & 16777215u); break; case 48u: result = btl.def_attr.invalid; break; case 49u: result = btl.def_attr.absorb; break; case 50u: result = btl.def_attr.half; break; case 51u: result = btl.def_attr.weak; break; case 52u: result = btl.bi.target; break; case 53u: result = btl.bi.disappear; break; case 57u: result = (Int32)btl.dms_geo_id; break; case 58u: result = btl.mesh_current; break; case 64u: result = btl.bi.row; break; case 65u: result = btl.bi.line_no; break; case 66u: result = btl_util.getPlayerPtr(btl).info.serial_no; break; case 67u: result = btl_util.getPlayerPtr(btl).category; break; case 68u: result = btl_util.getEnemyTypePtr(btl).category; break; case 69u: result = btl.bi.def_idle; break; case 70u: result = btl.bi.slot_no; break; case 72u: result = btl.elem.str; break; case 73u: result = btl.elem.mgc; break; case 74u: result = btl.defence.PhisicalDefence; break; case 75u: result = btl.defence.PhisicalEvade; break; case 76u: result = btl.defence.MagicalDefence; break; case 77u: result = btl.defence.MagicalEvade; break; case 100u: // access/modify an enemy's item to steal with SV_FunctionEnemy[100] and followings if (btl.bi.player == 0) result = btl_util.getEnemyPtr(btl).steal_item[0]; break; case 101u: if (btl.bi.player == 0) result = btl_util.getEnemyPtr(btl).steal_item[1]; break; case 102u: if (btl.bi.player == 0) result = btl_util.getEnemyPtr(btl).steal_item[2]; break; case 103u: if (btl.bi.player == 0) result = btl_util.getEnemyPtr(btl).steal_item[3]; break; case 104u: // access/modify an enemy's item to drop with SV_FunctionEnemy[104] and followings if (btl.bi.player == 0) result = btl_util.getEnemyTypePtr(btl).bonus.item[0]; break; case 105u: if (btl.bi.player == 0) result = btl_util.getEnemyTypePtr(btl).bonus.item[1]; break; case 106u: if (btl.bi.player == 0) result = btl_util.getEnemyTypePtr(btl).bonus.item[2]; break; case 107u: if (btl.bi.player == 0) result = btl_util.getEnemyTypePtr(btl).bonus.item[3]; break; case 108u: if (btl.bi.player == 0) result = (Int32)(btl_util.getEnemyTypePtr(btl).bonus.card); break; case 109u: // flags (die_atk, die_dmg, then 6 custom flags) if (btl.bi.player == 0) result = btl_util.getEnemyPtr(btl).info.flags; break; case 110u: // Out of reach: enemies inside battles flagged with "NoNeighboring" are all set to out of reach but they can also be placed individually using SV_FunctionEnemy[110] or setting the "OutOfReach" flag in the battle's ".memnfo" file result = btl.out_of_reach ? 1 : 0; break; case 111u: // SV_FunctionEnemy[111] can be used to control an enemy's transparency if (btl.bi.player == 0) result = btl_util.getEnemyPtr(btl).info.die_fade_rate; break; case 112u: result = (Int32)btl_mot.getMotion(btl); // Current battle animation by motion ID (stand = 0, etc... see btl_mot) break; case 113u: if (btl.bi.player == 0) result = btl_util.getEnemyTypePtr(btl).category; else result = ENEMY.ENEMY_CATEGORY_HUMANOID; break; case 114u: { // Return the current attack ID if it is currently performed by the indicated character CMD_DATA charCmd; if (btl_util.IsBtlUsingCommand(btl, out charCmd)) { if (btl.bi.player == 0) { if (charCmd == btl.cmd[3] || charCmd == btl.cmd[4] || charCmd == btl.cmd[5]) result = charCmd.sub_no; } else { if (charCmd == btl.cmd[1]) result = charCmd.sub_no; } } break; } case 140: result = (Int32)btl.pos.x; break; case 141: result = (Int32)(-btl.pos.y); break; case 142: result = (Int32)btl.pos.z; break; case 143: result = (Int32)btl.rot.eulerAngles.x; break; case 144: result = (Int32)btl.rot.eulerAngles.y; break; case 145: result = (Int32)btl.rot.eulerAngles.z; break; } return result; } public static void SetCharacterData(BTL_DATA btl, UInt32 id, Int32 val) { FF9StateBattleSystem ff9Battle = FF9StateSystem.Battle.FF9Battle; switch (id) { case 32u: for (Int32 i = 0; i < btl.meshCount; i++) btl.SetIsEnabledMeshRenderer(i, true); btl.getShadow().SetActive(true); btl.SetIsEnabledWeaponRenderer(true); btl.SetIsEnabledBattleModelRenderer(true); btl_sys.AddCharacter(btl); break; case 33u: for (Int32 j = 0; j < btl.meshCount; j++) btl.SetIsEnabledMeshRenderer(j, false); btl.getShadow().SetActive(false); btl.SetIsEnabledWeaponRenderer(false); btl.SetIsEnabledBattleModelRenderer(false); btl_cmd.KillCommand2(btl); btl_sys.DelCharacter(btl); break; case 34u: if (btl_cmd.KillCommand2(btl)) btl.sel_mode = 0; break; case 35u: btl.max.hp = (UInt32)val; break; case 36u: btl.cur.hp = (UInt32)val; break; case 37u: btl.max.mp = (UInt32)val; break; case 38u: btl.cur.mp = (UInt32)val; break; case 40u: btl.cur.at = (Int16)val; break; case 42u: btl.stat.invalid = (BattleStatus)(((UInt32)btl.stat.invalid & 0xFFFFFFu) | ((UInt32)val << 24)); break; case 43u: btl.stat.invalid = (BattleStatus)(((UInt32)btl.stat.invalid & 0xFF000000u) | (UInt32)val); break; case 44u: btl.stat.permanent = (BattleStatus)(((UInt32)btl.stat.permanent & 0xFFFFFFu) | ((UInt32)val << 24)); break; case 45u: btl.stat.permanent = (BattleStatus)(((UInt32)btl.stat.permanent & 0xFF000000u) | (UInt32)val); break; case 46u: // Statuses can be modified by battle scripts thanks to these: set SV_FunctionEnemy[STATUS_CURRENT_A] |= Status to add btl_stat.RemoveStatuses(btl, (BattleStatus)((UInt32)btl.stat.cur & (~((UInt32)val << 24)) & 0xFF000000u)); btl_stat.AlterStatuses(btl, (BattleStatus)(val << 24)); break; case 47u: btl_stat.RemoveStatuses(btl, (BattleStatus)((UInt32)btl.stat.cur & (~(UInt32)val) & 0xFFFFFFu)); btl_stat.AlterStatuses(btl, (BattleStatus)(val & 0xFFFFFFu)); break; case 48u: btl.def_attr.invalid = (Byte)val; break; case 49u: btl.def_attr.absorb = (Byte)val; break; case 50u: btl.def_attr.half = (Byte)val; break; case 51u: btl.def_attr.weak = (Byte)val; break; case 52u: if (ff9Battle.btl_phase == 2) { btl.tar_mode = 0; btl.bi.target = 0; btl.bi.atb = 0; btl.bi.select = 0; } else { btl.tar_mode = (Byte)(2u + val); } break; case 53u: btl.SetDisappear(val != 0, 3); break; case 54u: btl.bi.shadow = (Byte)val; btl.getShadow().SetActive(btl.bi.shadow != 0); break; case 55u: // Many AI scripts setup a custom model size for enemies; when they do, they handle Mini in the EventEngine.Request(tagNumber = 7) function ("CounterEx" in Hades Workshop) geo.geoScaleSet(btl, (Int32)val, true, true); if (ff9Battle.btl_phase == 2) // When modified during BattleLoad, consider it to be the default btl.geo_scale_default = val; break; case 56u: geo.geoScaleReset(btl, true); break; case 59u: btl_mot.HideMesh(btl, (UInt16)val, false); btl.mesh_current = (UInt16)(btl.mesh_current | (UInt16)val); break; case 60u: btl_mot.ShowMesh(btl, (UInt16)val, false); btl.mesh_current = (UInt16)(btl.mesh_current & (UInt16)(~(UInt16)val)); break; case 61u: GeoTexAnim.geoTexAnimPlay(btl.texanimptr, (Int32)val); break; case 62u: GeoTexAnim.geoTexAnimStop(btl.texanimptr, (Int32)val); break; case 63u: GeoTexAnim.geoTexAnimPlayOnce(btl.texanimptr, (Int32)val); break; case 69u: btl.bi.def_idle = (Byte)val; break; case 71u: btl_sys.SetBonus(btl_util.getEnemyTypePtr(btl)); break; case 72u: btl.elem.str = (Byte)val; btl.stat_modifier[0] = false; break; case 73u: btl.elem.mgc = (Byte)val; btl.stat_modifier[1] = false; break; case 74u: btl.defence.PhisicalDefence = (Byte)val; btl.stat_modifier[2] = false; break; case 75u: btl.defence.PhisicalEvade = (Byte)val; btl.stat_modifier[3] = false; break; case 76u: btl.defence.MagicalDefence = (Byte)val; btl.stat_modifier[4] = false; break; case 77u: btl.defence.MagicalEvade = (Byte)val; btl.stat_modifier[5] = false; break; case 78u: btl.cur.at = btl.max.at; btl.sel_mode = 1; btl_cmd.SetCommand(btl.cmd[0], BattleCommandId.SummonEiko, 187u, (UInt16)val, 8u); UIManager.Battle.FF9BMenu_EnableMenu(true); break; // The modifiers that Memoria adds case 100u: if (btl.bi.player == 0) btl_util.getEnemyPtr(btl).steal_item[0] = (byte)val; break; case 101u: if (btl.bi.player == 0) btl_util.getEnemyPtr(btl).steal_item[1] = (byte)val; break; case 102u: if (btl.bi.player == 0) btl_util.getEnemyPtr(btl).steal_item[2] = (byte)val; break; case 103u: if (btl.bi.player == 0) btl_util.getEnemyPtr(btl).steal_item[3] = (byte)val; break; case 104u: if (btl.bi.player == 0) btl_util.getEnemyTypePtr(btl).bonus.item[0] = (byte)val; break; case 105u: if (btl.bi.player == 0) btl_util.getEnemyTypePtr(btl).bonus.item[1] = (byte)val; break; case 106u: if (btl.bi.player == 0) btl_util.getEnemyTypePtr(btl).bonus.item[2] = (byte)val; break; case 107u: if (btl.bi.player == 0) btl_util.getEnemyTypePtr(btl).bonus.item[3] = (byte)val; break; case 108u: if (btl.bi.player == 0) btl_util.getEnemyTypePtr(btl).bonus.card = (byte)val; break; case 109u: if (btl.bi.player == 0) btl_util.getEnemyPtr(btl).info.flags = (byte)val; break; case 110u: btl.out_of_reach = val != 0; break; case 111u: if (btl.bi.player == 0) btl_util.getEnemyPtr(btl).info.die_fade_rate = (byte)val; btl_util.SetFadeRate(btl, val); break; case 112u: btl_mot.setMotion(btl, (byte)val); btl.evt.animFrame = 0; break; case 113u: if (btl.bi.player == 0) btl_util.getEnemyTypePtr(btl).category = (byte)val; break; case 114u: { ushort tar_id = (ushort)PersistenSingleton<EventEngine>.Instance.GetSysList(0); if (btl.bi.player == 0) { if (btl_cmd.CheckUsingCommand(btl.cmd[3])) { if (btl_cmd.CheckUsingCommand(btl.cmd[4])) { if (!btl_cmd.CheckUsingCommand(btl.cmd[5])) btl_cmd.SetEnemyCommand((ushort)PersistenSingleton<EventEngine>.Instance.GetSysList(1), tar_id, BattleCommandId.ScriptCounter3, (uint)val); } else { btl_cmd.SetEnemyCommand((ushort)PersistenSingleton<EventEngine>.Instance.GetSysList(1), tar_id, BattleCommandId.ScriptCounter2, (uint)val); } } else { btl_cmd.SetEnemyCommand((ushort)PersistenSingleton<EventEngine>.Instance.GetSysList(1), tar_id, BattleCommandId.ScriptCounter1, (uint)val); } } else { int target_number = 0; for (int i = 0; i < 8; i++) if ((tar_id & (1 << i)) != 0) target_number++; if (!btl_cmd.CheckUsingCommand(btl.cmd[1])) btl_cmd.SetCommand(btl.cmd[1], BattleCommandId.Counter, (uint)val, tar_id, (target_number > 1) ? 1u : 0u); } break; } case 130u: // Note: Very crafty. Creates elemental orbs (special SPS) rotating around the BTL_DATA... if (val == 3) { UnityEngine.Vector3 btl_pos = btl.gameObject.transform.GetChildByName("bone000").position; HonoluluBattleMain.battleSPS.AddSpecialSPSObj(0, 12, btl_pos, 4.0f); HonoluluBattleMain.battleSPS.AddSpecialSPSObj(1, 13, btl_pos, 4.0f); HonoluluBattleMain.battleSPS.AddSpecialSPSObj(2, 14, btl_pos, 4.0f); } else if (val == 2) // ... and remove them 1 by 1 HonoluluBattleMain.battleSPS.RemoveSpecialSPSObj(2); else if (val == 1) HonoluluBattleMain.battleSPS.RemoveSpecialSPSObj(1); else if (val == 0) HonoluluBattleMain.battleSPS.RemoveSpecialSPSObj(0); break; case 140: btl.pos.x = (float)val; btl.evt.posBattle.x = btl.pos.x; btl.evt.pos[0] = btl.pos.z; break; case 141: btl.pos.y = -(float)val; btl.evt.posBattle.y = btl.pos.y; btl.evt.pos[1] = btl.pos.z; break; case 142: btl.pos.z = (float)val; btl.evt.posBattle.z = btl.pos.z; btl.evt.pos[2] = btl.pos.z; break; case 143: btl.rot.eulerAngles = new UnityEngine.Vector3((float)val, btl.rot.eulerAngles.y, btl.rot.eulerAngles.z); btl.evt.rotBattle.eulerAngles = new UnityEngine.Vector3((float)val, btl.rot.eulerAngles.y, btl.rot.eulerAngles.z); break; case 144: btl.rot.eulerAngles = new UnityEngine.Vector3(btl.rot.eulerAngles.x, (float)val, btl.rot.eulerAngles.z); btl.evt.rotBattle.eulerAngles = new UnityEngine.Vector3(btl.rot.eulerAngles.x, (float)val, btl.rot.eulerAngles.z); break; case 145: btl.rot.eulerAngles = new UnityEngine.Vector3(btl.rot.eulerAngles.x, btl.rot.eulerAngles.y, (float)val); btl.evt.rotBattle.eulerAngles = new UnityEngine.Vector3(btl.rot.eulerAngles.x, btl.rot.eulerAngles.y, (float)val); break; } } public static UInt32 GetBattleData(Int32 id) { UInt32 result = UInt32.MaxValue; FF9StateBattleSystem ff9Battle = FF9StateSystem.Battle.FF9Battle; FF9StateGlobal ff = FF9StateSystem.Common.FF9; BattleUnit unit = FindBattleUnitUnlimited((UInt16)PersistenSingleton<EventEngine>.Instance.GetSysList(1)); CMD_DATA curCmd = GetCurrentCommandSmart(unit?.Data); switch (id) { case 32: result = (Byte)ff9Battle.btl_scene.Info.StartType; break; case 33: result = ff.party.gil; break; case 34: result = ff9Battle.btl_phase; break; case 35: result = ff9Battle.btl_seq; break; case 36: if (curCmd != null && curCmd.regist != null) result = curCmd.regist.btl_id; break; case 37: if (curCmd != null) result = curCmd.tar_id; break; case 38: if (curCmd != null && curCmd.regist != null && curCmd.regist.weapon != null) result = curCmd.regist.weapon.Ref.Elements; break; case 39: if (curCmd != null && curCmd.regist != null) result = (UInt32)curCmd.Element; break; case 40: result = ff9Battle.btl_load_status; break; case 41: result = battle.btl_bonus.exp; break; case 42: result = 0u; for (BTL_DATA next = ff9Battle.btl_list.next; next != null; next = next.next) { UInt32 serialNumber = btl_util.getSerialNumber(next); if (serialNumber == 10u || serialNumber == 11u) { result = !btl_cmd.CheckSpecificCommand(next, BattleCommandId.SysLastPhoenix) ? 0u : 1u; break; } } break; case 43: result = curCmd != null ? (UInt32)curCmd.info.effect_counter : 0; // The number of times the effect point has been reached for the current attack, for multi-hit pattern changes break; } return result; } public static void SetBattleData(UInt32 id, Int32 val) { FF9StateBattleSystem ff9Battle = FF9StateSystem.Battle.FF9Battle; FF9StateGlobal ff = FF9StateSystem.Common.FF9; switch (id) { case 32u: UIManager.Battle.FF9BMenu_EnableMenu(false); ff9Battle.btl_escape_key = 0; ff9Battle.cmd_status &= 65533; ff9Battle.btl_phase = 5; ff9Battle.btl_seq = 2; btl_cmd.KillAllCommand(ff9Battle); for (BTL_DATA next = ff9Battle.btl_list.next; next != null; next = next.next) next.bi.cmd_idle = 0; break; case 33u: if (ff9Battle.btl_phase == 1) { ff.btl_result = (Byte)val; if (val == 1 && ff9Battle.btl_scene.Info.WinPose != 0) { ff9Battle.btl_phase = 5; ff9Battle.btl_seq = 4; } else { if (ff.btl_result == 1) ff.btl_result = 2; ff9Battle.btl_phase = 8; ff9Battle.btl_seq = 0; } } break; case 34u: if (ff9Battle.btl_phase == 1) { ff9Battle.btl_phase = 7; ff9Battle.btl_seq = 0; ff.btl_result = 3; } break; case 35u: if (ff9Battle.btl_phase == 1) { BTL_SCENE_INFO info = ff9Battle.btl_scene.Info; ff9Battle.btl_phase = 3; ff9Battle.btl_seq = 0; if (info.SpecialStart == 0 || info.BackAttack == 0) info.StartType = battle_start_type_tags.BTL_START_NORMAL_ATTACK; } break; case 36u: if (ff9Battle.btl_phase == 1) SFX.SetCamera(val); break; case 37u: { FF9StateGlobal ff9StateGlobal = ff; ff9StateGlobal.btl_flag = (Byte)(ff9StateGlobal.btl_flag | 1); PersistenSingleton<EventEngine>.Instance.SetNextMap(val); break; } case 38u: ff.party.gil += (UInt32)val; if (ff.party.gil > 9999999u) ff.party.gil = 9999999u; break; case 39u: if (ff.dragon_no < 9999) { FF9StateGlobal ff9StateGlobal2 = ff; ff9StateGlobal2.dragon_no = (Int16)(ff9StateGlobal2.dragon_no + 1); } break; case 40u: { btlsnd.ff9btlsnd_song_vol_intplall(30, 0); FF9StateGlobal ff2 = FF9StateSystem.Common.FF9; ff2.btl_flag = (Byte)(ff2.btl_flag | 16); break; } case 43u: CMD_DATA curCmd = GetCurrentCommandSmart(FindBattleUnitUnlimited((UInt16)PersistenSingleton<EventEngine>.Instance.GetSysList(1))?.Data); if (curCmd != null) curCmd.info.effect_counter = val; break; } } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Diagnostics; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; namespace Microsoft.PythonTools.Infrastructure { static class TaskExtensions { /// <summary> /// Suppresses warnings about unawaited tasks and rethrows task exceptions back to the callers synchronization context if it is possible /// </summary> /// <remarks> /// <see cref="OperationCanceledException"/> is always ignored. /// </remarks> public static void DoNotWait(this Task task) { if (task.IsCompleted) { ReThrowTaskException(task); return; } if (TestEnvironment.Current != null && TestEnvironment.Current.TryAddTaskToWait(task)) { return; } var synchronizationContext = SynchronizationContext.Current; if (synchronizationContext != null && synchronizationContext.GetType() != typeof (SynchronizationContext)) { task.ContinueWith(DoNotWaitSynchronizationContextContinuation, synchronizationContext, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } else { task.ContinueWith(DoNotWaitThreadContinuation, TaskContinuationOptions.ExecuteSynchronously); } } private static void ReThrowTaskException(object state) { var task = (Task)state; if (task.IsFaulted && task.Exception != null) { var exception = task.Exception.InnerException; ExceptionDispatchInfo.Capture(exception).Throw(); } } private static void DoNotWaitThreadContinuation(Task task) { if (task.IsFaulted && task.Exception != null) { var exception = task.Exception.InnerException; ThreadPool.QueueUserWorkItem(s => ((ExceptionDispatchInfo)s).Throw(), ExceptionDispatchInfo.Capture(exception)); } } private static void DoNotWaitSynchronizationContextContinuation(Task task, object state) { var context = (SynchronizationContext) state; context.Post(ReThrowTaskException, task); } /// <summary> /// Waits for a task to complete. If an exception occurs, the exception /// will be unwrapped. If the timeout expires, the default value for /// <b>T</b> will be returned. /// </summary> public static T WaitOrDefault<T>(this Task<T> task, int milliseconds) { return WaitOrDefault(task, TimeSpan.FromMilliseconds(milliseconds)); } /// <summary> /// Waits for a task to complete. If an exception occurs, the exception /// will be unwrapped. If the timeout expires, the default value for /// <b>T</b> will be returned. /// </summary> public static T WaitOrDefault<T>(this Task<T> task, TimeSpan timeout) { try { if (task.Wait(timeout)) { return task.Result; } } catch (AggregateException ae) { if (ae.InnerException != null) { ExceptionDispatchInfo.Capture(ae.InnerException).Throw(); } throw; } return default(T); } /// <summary> /// Waits for a task to complete. If an exception occurs, the exception /// will be raised without being wrapped in a /// <see cref="AggregateException"/>. /// </summary> public static void WaitAndUnwrapExceptions(this Task task) { task.GetAwaiter().GetResult(); } /// <summary> /// Waits for a task to complete. If an exception occurs, the exception /// will be raised without being wrapped in a /// <see cref="AggregateException"/>. /// </summary> public static T WaitAndUnwrapExceptions<T>(this Task<T> task) { return task.GetAwaiter().GetResult(); } /// <summary> /// Waits for a task to complete. If an exception occurs, the exception /// will be raised without being wrapped in a /// <see cref="AggregateException"/>. /// </summary> public static T WaitAndUnwrapExceptions<T>(this Task<T> task, Func<T> onCancel) { try { return task.GetAwaiter().GetResult(); } catch (OperationCanceledException) { return onCancel(); } } /// <summary> /// Silently handles the specified exception. /// </summary> public static Task SilenceException<T>(this Task task) where T : Exception { return task.ContinueWith(t => { try { t.Wait(); } catch (AggregateException ex) { ex.Handle(e => e is T); } }); } /// <summary> /// Silently handles the specified exception. /// </summary> public static Task<U> SilenceException<T, U>(this Task<U> task) where T : Exception { return task.ContinueWith(t => { try { return t.Result; } catch (AggregateException ex) { ex.Handle(e => e is T); return default(U); } }); } private sealed class SemaphoreLock : IDisposable { private SemaphoreSlim _semaphore; public SemaphoreLock(SemaphoreSlim semaphore) { _semaphore = semaphore; } public void Reset() { _semaphore = null; } void IDisposable.Dispose() { try { _semaphore?.Release(); } catch (ObjectDisposedException ex) { throw new OperationCanceledException("semaphore was disposed", ex); } finally { _semaphore = null; GC.SuppressFinalize(this); } } ~SemaphoreLock() { try { _semaphore?.Release(); } catch (ObjectDisposedException) { } } } public static async Task<IDisposable> LockAsync(this SemaphoreSlim semaphore, CancellationToken cancellationToken) { var res = new SemaphoreLock(semaphore); try { try { await semaphore.WaitAsync(cancellationToken); var res2 = res; res = null; return res2; } finally { res?.Reset(); } } catch (ObjectDisposedException ex) { throw new OperationCanceledException("semaphore was disposed", ex); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Threading; namespace System.Text { public abstract class EncoderFallback { private static EncoderFallback s_replacementFallback; // Default fallback, uses no best fit & "?" private static EncoderFallback s_exceptionFallback; // Get each of our generic fallbacks. public static EncoderFallback ReplacementFallback { get { if (s_replacementFallback == null) Interlocked.CompareExchange<EncoderFallback>(ref s_replacementFallback, new EncoderReplacementFallback(), null); return s_replacementFallback; } } public static EncoderFallback ExceptionFallback { get { if (s_exceptionFallback == null) Interlocked.CompareExchange<EncoderFallback>(ref s_exceptionFallback, new EncoderExceptionFallback(), null); return s_exceptionFallback; } } // Fallback // // Return the appropriate unicode string alternative to the character that need to fall back. // Most implementations will be: // return new MyCustomEncoderFallbackBuffer(this); public abstract EncoderFallbackBuffer CreateFallbackBuffer(); // Maximum number of characters that this instance of this fallback could return public abstract int MaxCharCount { get; } } public abstract class EncoderFallbackBuffer { // Most implementations will probably need an implementation-specific constructor // Public methods that cannot be overridden that let us do our fallback thing // These wrap the internal methods so that we can check for people doing stuff that is incorrect public abstract bool Fallback(char charUnknown, int index); public abstract bool Fallback(char charUnknownHigh, char charUnknownLow, int index); // Get next character public abstract char GetNextChar(); // Back up a character public abstract bool MovePrevious(); // How many chars left in this fallback? public abstract int Remaining { get; } // Not sure if this should be public or not. // Clear the buffer public virtual void Reset() { while (GetNextChar() != (char)0) ; } // Internal items to help us figure out what we're doing as far as error messages, etc. // These help us with our performance and messages internally internal unsafe char* charStart; internal unsafe char* charEnd; internal EncoderNLS encoder; internal bool setEncoder; internal bool bUsedEncoder; internal bool bFallingBack = false; internal int iRecursionCount = 0; private const int iMaxRecursion = 250; // Internal Reset // For example, what if someone fails a conversion and wants to reset one of our fallback buffers? internal unsafe void InternalReset() { charStart = null; bFallingBack = false; iRecursionCount = 0; Reset(); } // Set the above values // This can't be part of the constructor because EncoderFallbacks would have to know how to implement these. internal unsafe void InternalInitialize(char* charStart, char* charEnd, EncoderNLS encoder, bool setEncoder) { this.charStart = charStart; this.charEnd = charEnd; this.encoder = encoder; this.setEncoder = setEncoder; this.bUsedEncoder = false; this.bFallingBack = false; this.iRecursionCount = 0; } internal char InternalGetNextChar() { char ch = GetNextChar(); bFallingBack = (ch != 0); if (ch == 0) iRecursionCount = 0; return ch; } // Fallback the current character using the remaining buffer and encoder if necessary // This can only be called by our encodings (other have to use the public fallback methods), so // we can use our EncoderNLS here too. // setEncoder is true if we're calling from a GetBytes method, false if we're calling from a GetByteCount // // Note that this could also change the contents of this.encoder, which is the same // object that the caller is using, so the caller could mess up the encoder for us // if they aren't careful. internal unsafe virtual bool InternalFallback(char ch, ref char* chars) { // Shouldn't have null charStart Debug.Assert(charStart != null, "[EncoderFallback.InternalFallbackBuffer]Fallback buffer is not initialized"); // Get our index, remember chars was preincremented to point at next char, so have to -1 int index = (int)(chars - charStart) - 1; // See if it was a high surrogate if (Char.IsHighSurrogate(ch)) { // See if there's a low surrogate to go with it if (chars >= this.charEnd) { // Nothing left in input buffer // No input, return 0 if mustflush is false if (this.encoder != null && !this.encoder.MustFlush) { // Done, nothing to fallback if (this.setEncoder) { bUsedEncoder = true; this.encoder._charLeftOver = ch; } bFallingBack = false; return false; } } else { // Might have a low surrogate char cNext = *chars; if (Char.IsLowSurrogate(cNext)) { // If already falling back then fail if (bFallingBack && iRecursionCount++ > iMaxRecursion) ThrowLastCharRecursive(Char.ConvertToUtf32(ch, cNext)); // Next is a surrogate, add it as surrogate pair, and increment chars chars++; bFallingBack = Fallback(ch, cNext, index); return bFallingBack; } // Next isn't a low surrogate, just fallback the high surrogate } } // If already falling back then fail if (bFallingBack && iRecursionCount++ > iMaxRecursion) ThrowLastCharRecursive((int)ch); // Fall back our char bFallingBack = Fallback(ch, index); return bFallingBack; } // private helper methods internal void ThrowLastCharRecursive(int charRecursive) { // Throw it, using our complete character throw new ArgumentException( SR.Format(SR.Argument_RecursiveFallback, charRecursive), "chars"); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40 || PORTABLE) using System.Numerics; #endif using System.Text; using System.IO; using System.Xml; using System.Globalization; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json { internal enum ReadType { Read, ReadAsInt32, ReadAsBytes, ReadAsString, ReadAsDecimal, ReadAsDateTime, #if !NET20 ReadAsDateTimeOffset #endif } /// <summary> /// Represents a reader that provides fast, non-cached, forward-only access to JSON text data. /// </summary> public class JsonTextReader : JsonReader, IJsonLineInfo { private const char UnicodeReplacementChar = '\uFFFD'; private readonly TextReader _reader; private char[] _chars; private int _charsUsed; private int _charPos; private int _lineStartPos; private int _lineNumber; private bool _isEndOfFile; private StringBuffer _buffer; private StringReference _stringReference; /// <summary> /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>. /// </summary> /// <param name="reader">The <c>TextReader</c> containing the XML data to read.</param> public JsonTextReader(TextReader reader) { if (reader == null) throw new ArgumentNullException("reader"); _reader = reader; _lineNumber = 1; _chars = new char[1025]; } #if DEBUG internal void SetCharBuffer(char[] chars) { _chars = chars; } #endif private StringBuffer GetBuffer() { if (_buffer == null) { _buffer = new StringBuffer(1025); } else { _buffer.Position = 0; } return _buffer; } private void OnNewLine(int pos) { _lineNumber++; _lineStartPos = pos - 1; } private void ParseString(char quote) { _charPos++; ShiftBufferIfNeeded(); ReadStringIntoBuffer(quote); if (_readType == ReadType.ReadAsBytes) { byte[] data; if (_stringReference.Length == 0) { data = new byte[0]; } else { data = Convert.FromBase64CharArray(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length); } SetToken(JsonToken.Bytes, data); } else if (_readType == ReadType.ReadAsString) { string text = _stringReference.ToString(); SetToken(JsonToken.String, text); _quoteChar = quote; } else { string text = _stringReference.ToString(); if (_dateParseHandling != DateParseHandling.None) { DateParseHandling dateParseHandling; if (_readType == ReadType.ReadAsDateTime) dateParseHandling = DateParseHandling.DateTime; #if !NET20 else if (_readType == ReadType.ReadAsDateTimeOffset) dateParseHandling = DateParseHandling.DateTimeOffset; #endif else dateParseHandling = _dateParseHandling; object dt; if (DateTimeUtils.TryParseDateTime(text, dateParseHandling, DateTimeZoneHandling, out dt)) { SetToken(JsonToken.Date, dt); return; } } SetToken(JsonToken.String, text); _quoteChar = quote; } } private static void BlockCopyChars(char[] src, int srcOffset, char[] dst, int dstOffset, int count) { const int charByteCount = 2; Buffer.BlockCopy(src, srcOffset * charByteCount, dst, dstOffset * charByteCount, count * charByteCount); } private void ShiftBufferIfNeeded() { // once in the last 10% of the buffer shift the remainling content to the start to avoid // unnessesarly increasing the buffer size when reading numbers/strings int length = _chars.Length; if (length - _charPos <= length * 0.1) { int count = _charsUsed - _charPos; if (count > 0) BlockCopyChars(_chars, _charPos, _chars, 0, count); _lineStartPos -= _charPos; _charPos = 0; _charsUsed = count; _chars[_charsUsed] = '\0'; } } private int ReadData(bool append) { return ReadData(append, 0); } private int ReadData(bool append, int charsRequired) { if (_isEndOfFile) return 0; // char buffer is full if (_charsUsed + charsRequired >= _chars.Length - 1) { if (append) { // copy to new array either double the size of the current or big enough to fit required content int newArrayLength = Math.Max(_chars.Length * 2, _charsUsed + charsRequired + 1); // increase the size of the buffer char[] dst = new char[newArrayLength]; BlockCopyChars(_chars, 0, dst, 0, _chars.Length); _chars = dst; } else { int remainingCharCount = _charsUsed - _charPos; if (remainingCharCount + charsRequired + 1 >= _chars.Length) { // the remaining count plus the required is bigger than the current buffer size char[] dst = new char[remainingCharCount + charsRequired + 1]; if (remainingCharCount > 0) BlockCopyChars(_chars, _charPos, dst, 0, remainingCharCount); _chars = dst; } else { // copy any remaining data to the beginning of the buffer if needed and reset positions if (remainingCharCount > 0) BlockCopyChars(_chars, _charPos, _chars, 0, remainingCharCount); } _lineStartPos -= _charPos; _charPos = 0; _charsUsed = remainingCharCount; } } int attemptCharReadCount = _chars.Length - _charsUsed - 1; int charsRead = _reader.Read(_chars, _charsUsed, attemptCharReadCount); _charsUsed += charsRead; if (charsRead == 0) _isEndOfFile = true; _chars[_charsUsed] = '\0'; return charsRead; } private bool EnsureChars(int relativePosition, bool append) { if (_charPos + relativePosition >= _charsUsed) return ReadChars(relativePosition, append); return true; } private bool ReadChars(int relativePosition, bool append) { if (_isEndOfFile) return false; int charsRequired = _charPos + relativePosition - _charsUsed + 1; int totalCharsRead = 0; // it is possible that the TextReader doesn't return all data at once // repeat read until the required text is returned or the reader is out of content do { int charsRead = ReadData(append, charsRequired - totalCharsRead); // no more content if (charsRead == 0) break; totalCharsRead += charsRead; } while (totalCharsRead < charsRequired); if (totalCharsRead < charsRequired) return false; return true; } /// <summary> /// Reads the next JSON token from the stream. /// </summary> /// <returns> /// true if the next token was read successfully; false if there are no more tokens to read. /// </returns> [DebuggerStepThrough] public override bool Read() { _readType = ReadType.Read; if (!ReadInternal()) { SetToken(JsonToken.None); return false; } return true; } /// <summary> /// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>. /// </summary> /// <returns> /// A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array. /// </returns> public override byte[] ReadAsBytes() { return ReadAsBytesInternal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns> public override decimal? ReadAsDecimal() { return ReadAsDecimalInternal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>. /// </summary> /// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns> public override int? ReadAsInt32() { return ReadAsInt32Internal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="String"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public override string ReadAsString() { return ReadAsStringInternal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public override DateTime? ReadAsDateTime() { return ReadAsDateTimeInternal(); } #if !NET20 /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>. /// </summary> /// <returns>A <see cref="DateTimeOffset"/>. This method will return <c>null</c> at the end of an array.</returns> public override DateTimeOffset? ReadAsDateTimeOffset() { return ReadAsDateTimeOffsetInternal(); } #endif internal override bool ReadInternal() { while (true) { switch (_currentState) { case State.Start: case State.Property: case State.Array: case State.ArrayStart: case State.Constructor: case State.ConstructorStart: return ParseValue(); case State.Complete: break; case State.Object: case State.ObjectStart: return ParseObject(); case State.PostValue: // returns true if it hits // end of object or array if (ParsePostValue()) return true; break; case State.Finished: if (EnsureChars(0, false)) { EatWhitespace(false); if (_isEndOfFile) { return false; } if (_chars[_charPos] == '/') { ParseComment(); return true; } else { throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } } return false; case State.Closed: break; case State.Error: break; default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState)); } } } private void ReadStringIntoBuffer(char quote) { int charPos = _charPos; int initialPosition = _charPos; int lastWritePosition = _charPos; StringBuffer buffer = null; while (true) { switch (_chars[charPos++]) { case '\0': if (_charsUsed == charPos - 1) { charPos--; if (ReadData(true) == 0) { _charPos = charPos; throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); } } break; case '\\': _charPos = charPos; if (!EnsureChars(0, true)) { _charPos = charPos; throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); } // start of escape sequence int escapeStartPos = charPos - 1; char currentChar = _chars[charPos]; char writeChar; switch (currentChar) { case 'b': charPos++; writeChar = '\b'; break; case 't': charPos++; writeChar = '\t'; break; case 'n': charPos++; writeChar = '\n'; break; case 'f': charPos++; writeChar = '\f'; break; case 'r': charPos++; writeChar = '\r'; break; case '\\': charPos++; writeChar = '\\'; break; case '"': case '\'': case '/': writeChar = currentChar; charPos++; break; case 'u': charPos++; _charPos = charPos; writeChar = ParseUnicode(); if (StringUtils.IsLowSurrogate(writeChar)) { // low surrogate with no preceding high surrogate; this char is replaced writeChar = UnicodeReplacementChar; } else if (StringUtils.IsHighSurrogate(writeChar)) { bool anotherHighSurrogate; // loop for handling situations where there are multiple consecutive high surrogates do { anotherHighSurrogate = false; // potential start of a surrogate pair if (EnsureChars(2, true) && _chars[_charPos] == '\\' && _chars[_charPos + 1] == 'u') { char highSurrogate = writeChar; _charPos += 2; writeChar = ParseUnicode(); if (StringUtils.IsLowSurrogate(writeChar)) { // a valid surrogate pair! } else if (StringUtils.IsHighSurrogate(writeChar)) { // another high surrogate; replace current and start check over highSurrogate = UnicodeReplacementChar; anotherHighSurrogate = true; } else { // high surrogate not followed by low surrogate; original char is replaced highSurrogate = UnicodeReplacementChar; } if (buffer == null) buffer = GetBuffer(); WriteCharToBuffer(buffer, highSurrogate, lastWritePosition, escapeStartPos); lastWritePosition = _charPos; } else { // there are not enough remaining chars for the low surrogate or is not follow by unicode sequence // replace high surrogate and continue on as usual writeChar = UnicodeReplacementChar; } } while (anotherHighSurrogate); } charPos = _charPos; break; default: charPos++; _charPos = charPos; throw JsonReaderException.Create(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar)); } if (buffer == null) buffer = GetBuffer(); WriteCharToBuffer(buffer, writeChar, lastWritePosition, escapeStartPos); lastWritePosition = charPos; break; case StringUtils.CarriageReturn: _charPos = charPos - 1; ProcessCarriageReturn(true); charPos = _charPos; break; case StringUtils.LineFeed: _charPos = charPos - 1; ProcessLineFeed(); charPos = _charPos; break; case '"': case '\'': if (_chars[charPos - 1] == quote) { charPos--; if (initialPosition == lastWritePosition) { _stringReference = new StringReference(_chars, initialPosition, charPos - initialPosition); } else { if (buffer == null) buffer = GetBuffer(); if (charPos > lastWritePosition) buffer.Append(_chars, lastWritePosition, charPos - lastWritePosition); _stringReference = new StringReference(buffer.GetInternalBuffer(), 0, buffer.Position); } charPos++; _charPos = charPos; return; } break; } } } private void WriteCharToBuffer(StringBuffer buffer, char writeChar, int lastWritePosition, int writeToPosition) { if (writeToPosition > lastWritePosition) { buffer.Append(_chars, lastWritePosition, writeToPosition - lastWritePosition); } buffer.Append(writeChar); } private char ParseUnicode() { char writeChar; if (EnsureChars(4, true)) { string hexValues = new string(_chars, _charPos, 4); char hexChar = Convert.ToChar(int.Parse(hexValues, NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo)); writeChar = hexChar; _charPos += 4; } else { throw JsonReaderException.Create(this, "Unexpected end while parsing unicode character."); } return writeChar; } private void ReadNumberIntoBuffer() { int charPos = _charPos; while (true) { switch (_chars[charPos++]) { case '\0': if (_charsUsed == charPos - 1) { charPos--; _charPos = charPos; if (ReadData(true) == 0) return; } else { _charPos = charPos - 1; return; } break; case '-': case '+': case 'a': case 'A': case 'b': case 'B': case 'c': case 'C': case 'd': case 'D': case 'e': case 'E': case 'f': case 'F': case 'x': case 'X': case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': break; default: _charPos = charPos - 1; return; } } } private void ClearRecentString() { if (_buffer != null) _buffer.Position = 0; _stringReference = new StringReference(); } private bool ParsePostValue() { while (true) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (_charsUsed == _charPos) { if (ReadData(false) == 0) { _currentState = State.Finished; return false; } } else { _charPos++; } break; case '}': _charPos++; SetToken(JsonToken.EndObject); return true; case ']': _charPos++; SetToken(JsonToken.EndArray); return true; case ')': _charPos++; SetToken(JsonToken.EndConstructor); return true; case '/': ParseComment(); return true; case ',': _charPos++; // finished parsing SetStateBasedOnCurrent(); return false; case ' ': case StringUtils.Tab: // eat _charPos++; break; case StringUtils.CarriageReturn: ProcessCarriageReturn(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; default: if (char.IsWhiteSpace(currentChar)) { // eat _charPos++; } else { throw JsonReaderException.Create(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } break; } } } private bool ParseObject() { while (true) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (_charsUsed == _charPos) { if (ReadData(false) == 0) return false; } else { _charPos++; } break; case '}': SetToken(JsonToken.EndObject); _charPos++; return true; case '/': ParseComment(); return true; case StringUtils.CarriageReturn: ProcessCarriageReturn(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; case ' ': case StringUtils.Tab: // eat _charPos++; break; default: if (char.IsWhiteSpace(currentChar)) { // eat _charPos++; } else { return ParseProperty(); } break; } } } private bool ParseProperty() { char firstChar = _chars[_charPos]; char quoteChar; if (firstChar == '"' || firstChar == '\'') { _charPos++; quoteChar = firstChar; ShiftBufferIfNeeded(); ReadStringIntoBuffer(quoteChar); } else if (ValidIdentifierChar(firstChar)) { quoteChar = '\0'; ShiftBufferIfNeeded(); ParseUnquotedProperty(); } else { throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } string propertyName = _stringReference.ToString(); EatWhitespace(false); if (_chars[_charPos] != ':') throw JsonReaderException.Create(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); _charPos++; SetToken(JsonToken.PropertyName, propertyName); _quoteChar = quoteChar; ClearRecentString(); return true; } private bool ValidIdentifierChar(char value) { return (char.IsLetterOrDigit(value) || value == '_' || value == '$'); } private void ParseUnquotedProperty() { int initialPosition = _charPos; // parse unquoted property name until whitespace or colon while (true) { switch (_chars[_charPos]) { case '\0': if (_charsUsed == _charPos) { if (ReadData(true) == 0) throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name."); break; } _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition); return; default: char currentChar = _chars[_charPos]; if (ValidIdentifierChar(currentChar)) { _charPos++; break; } else if (char.IsWhiteSpace(currentChar) || currentChar == ':') { _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition); return; } throw JsonReaderException.Create(this, "Invalid JavaScript property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } } private bool ParseValue() { while (true) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (_charsUsed == _charPos) { if (ReadData(false) == 0) return false; } else { _charPos++; } break; case '"': case '\'': ParseString(currentChar); return true; case 't': ParseTrue(); return true; case 'f': ParseFalse(); return true; case 'n': if (EnsureChars(1, true)) { char next = _chars[_charPos + 1]; if (next == 'u') ParseNull(); else if (next == 'e') ParseConstructor(); else throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } else { throw JsonReaderException.Create(this, "Unexpected end."); } return true; case 'N': ParseNumberNaN(); return true; case 'I': ParseNumberPositiveInfinity(); return true; case '-': if (EnsureChars(1, true) && _chars[_charPos + 1] == 'I') ParseNumberNegativeInfinity(); else ParseNumber(); return true; case '/': ParseComment(); return true; case 'u': ParseUndefined(); return true; case '{': _charPos++; SetToken(JsonToken.StartObject); return true; case '[': _charPos++; SetToken(JsonToken.StartArray); return true; case ']': _charPos++; SetToken(JsonToken.EndArray); return true; case ',': // don't increment position, the next call to read will handle comma // this is done to handle multiple empty comma values SetToken(JsonToken.Undefined); return true; case ')': _charPos++; SetToken(JsonToken.EndConstructor); return true; case StringUtils.CarriageReturn: ProcessCarriageReturn(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; case ' ': case StringUtils.Tab: // eat _charPos++; break; default: if (char.IsWhiteSpace(currentChar)) { // eat _charPos++; break; } else if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.') { ParseNumber(); return true; } else { throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } } } private void ProcessLineFeed() { _charPos++; OnNewLine(_charPos); } private void ProcessCarriageReturn(bool append) { _charPos++; if (EnsureChars(1, append) && _chars[_charPos] == StringUtils.LineFeed) _charPos++; OnNewLine(_charPos); } private bool EatWhitespace(bool oneOrMore) { bool finished = false; bool ateWhitespace = false; while (!finished) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (_charsUsed == _charPos) { if (ReadData(false) == 0) finished = true; } else { _charPos++; } break; case StringUtils.CarriageReturn: ProcessCarriageReturn(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; default: if (currentChar == ' ' || char.IsWhiteSpace(currentChar)) { ateWhitespace = true; _charPos++; } else { finished = true; } break; } } return (!oneOrMore || ateWhitespace); } private void ParseConstructor() { if (MatchValueWithTrailingSeperator("new")) { EatWhitespace(false); int initialPosition = _charPos; int endPosition; while (true) { char currentChar = _chars[_charPos]; if (currentChar == '\0') { if (_charsUsed == _charPos) { if (ReadData(true) == 0) throw JsonReaderException.Create(this, "Unexpected end while parsing constructor."); } else { endPosition = _charPos; _charPos++; break; } } else if (char.IsLetterOrDigit(currentChar)) { _charPos++; } else if (currentChar == StringUtils.CarriageReturn) { endPosition = _charPos; ProcessCarriageReturn(true); break; } else if (currentChar == StringUtils.LineFeed) { endPosition = _charPos; ProcessLineFeed(); break; } else if (char.IsWhiteSpace(currentChar)) { endPosition = _charPos; _charPos++; break; } else if (currentChar == '(') { endPosition = _charPos; break; } else { throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } _stringReference = new StringReference(_chars, initialPosition, endPosition - initialPosition); string constructorName = _stringReference.ToString(); EatWhitespace(false); if (_chars[_charPos] != '(') throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); _charPos++; ClearRecentString(); SetToken(JsonToken.StartConstructor, constructorName); } else { throw JsonReaderException.Create(this, "Unexpected content while parsing JSON."); } } private void ParseNumber() { ShiftBufferIfNeeded(); char firstChar = _chars[_charPos]; int initialPosition = _charPos; ReadNumberIntoBuffer(); _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition); object numberValue; JsonToken numberType; bool singleDigit = (char.IsDigit(firstChar) && _stringReference.Length == 1); bool nonBase10 = (firstChar == '0' && _stringReference.Length > 1 && _stringReference.Chars[_stringReference.StartIndex + 1] != '.' && _stringReference.Chars[_stringReference.StartIndex + 1] != 'e' && _stringReference.Chars[_stringReference.StartIndex + 1] != 'E'); if (_readType == ReadType.ReadAsInt32) { if (singleDigit) { // digit char values start at 48 numberValue = firstChar - 48; } else if (nonBase10) { string number = _stringReference.ToString(); // decimal.Parse doesn't support parsing hexadecimal values int integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt32(number, 16) : Convert.ToInt32(number, 8); numberValue = integer; } else { numberValue = ConvertUtils.Int32Parse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length); } numberType = JsonToken.Integer; } else if (_readType == ReadType.ReadAsDecimal) { if (singleDigit) { // digit char values start at 48 numberValue = (decimal)firstChar - 48; } else if (nonBase10) { string number = _stringReference.ToString(); // decimal.Parse doesn't support parsing hexadecimal values long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); numberValue = Convert.ToDecimal(integer); } else { string number = _stringReference.ToString(); numberValue = decimal.Parse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture); } numberType = JsonToken.Float; } else { if (singleDigit) { // digit char values start at 48 numberValue = (long)firstChar - 48; numberType = JsonToken.Integer; } else if (nonBase10) { string number = _stringReference.ToString(); numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); numberType = JsonToken.Integer; } else { long value; ParseResult parseResult = ConvertUtils.Int64TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value); if (parseResult == ParseResult.Success) { numberValue = value; numberType = JsonToken.Integer; } else if (parseResult == ParseResult.Invalid) { string number = _stringReference.ToString(); if (_floatParseHandling == FloatParseHandling.Decimal) numberValue = decimal.Parse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture); else numberValue = Convert.ToDouble(number, CultureInfo.InvariantCulture); numberType = JsonToken.Float; } else if (parseResult == ParseResult.Overflow) { #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40 || PORTABLE) string number = _stringReference.ToString(); numberValue = BigInteger.Parse(number, CultureInfo.InvariantCulture); numberType = JsonToken.Integer; #else // todo - validate number was a valid integer to make sure overflow was the reason for failure throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString())); #endif } else { throw JsonReaderException.Create(this, "Unknown error parsing integer."); } } } ClearRecentString(); SetToken(numberType, numberValue); } private void ParseComment() { // should have already parsed / character before reaching this method _charPos++; if (!EnsureChars(1, false) || _chars[_charPos] != '*') throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); else _charPos++; int initialPosition = _charPos; bool commentFinished = false; while (!commentFinished) { switch (_chars[_charPos]) { case '\0': if (_charsUsed == _charPos) { if (ReadData(true) == 0) throw JsonReaderException.Create(this, "Unexpected end while parsing comment."); } else { _charPos++; } break; case '*': _charPos++; if (EnsureChars(0, true)) { if (_chars[_charPos] == '/') { _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition - 1); _charPos++; commentFinished = true; } } break; case StringUtils.CarriageReturn: ProcessCarriageReturn(true); break; case StringUtils.LineFeed: ProcessLineFeed(); break; default: _charPos++; break; } } SetToken(JsonToken.Comment, _stringReference.ToString()); ClearRecentString(); } private bool MatchValue(string value) { if (!EnsureChars(value.Length - 1, true)) return false; for (int i = 0; i < value.Length; i++) { if (_chars[_charPos + i] != value[i]) { return false; } } _charPos += value.Length; return true; } private bool MatchValueWithTrailingSeperator(string value) { // will match value and then move to the next character, checking that it is a seperator character bool match = MatchValue(value); if (!match) return false; if (!EnsureChars(0, false)) return true; return IsSeperator(_chars[_charPos]) || _chars[_charPos] == '\0'; } private bool IsSeperator(char c) { switch (c) { case '}': case ']': case ',': return true; case '/': // check next character to see if start of a comment if (!EnsureChars(1, false)) return false; return (_chars[_charPos + 1] == '*'); case ')': if (CurrentState == State.Constructor || CurrentState == State.ConstructorStart) return true; break; case ' ': case StringUtils.Tab: case StringUtils.LineFeed: case StringUtils.CarriageReturn: return true; default: if (char.IsWhiteSpace(c)) return true; break; } return false; } private void ParseTrue() { // check characters equal 'true' // and that it is followed by either a seperator character // or the text ends if (MatchValueWithTrailingSeperator(JsonConvert.True)) { SetToken(JsonToken.Boolean, true); } else { throw JsonReaderException.Create(this, "Error parsing boolean value."); } } private void ParseNull() { if (MatchValueWithTrailingSeperator(JsonConvert.Null)) { SetToken(JsonToken.Null); } else { throw JsonReaderException.Create(this, "Error parsing null value."); } } private void ParseUndefined() { if (MatchValueWithTrailingSeperator(JsonConvert.Undefined)) { SetToken(JsonToken.Undefined); } else { throw JsonReaderException.Create(this, "Error parsing undefined value."); } } private void ParseFalse() { if (MatchValueWithTrailingSeperator(JsonConvert.False)) { SetToken(JsonToken.Boolean, false); } else { throw JsonReaderException.Create(this, "Error parsing boolean value."); } } private void ParseNumberNegativeInfinity() { if (MatchValueWithTrailingSeperator(JsonConvert.NegativeInfinity)) { if (_floatParseHandling == FloatParseHandling.Decimal) throw new JsonReaderException("Cannot read -Infinity as a decimal."); SetToken(JsonToken.Float, double.NegativeInfinity); } else { throw JsonReaderException.Create(this, "Error parsing negative infinity value."); } } private void ParseNumberPositiveInfinity() { if (MatchValueWithTrailingSeperator(JsonConvert.PositiveInfinity)) { if (_floatParseHandling == FloatParseHandling.Decimal) throw new JsonReaderException("Cannot read Infinity as a decimal."); SetToken(JsonToken.Float, double.PositiveInfinity); } else { throw JsonReaderException.Create(this, "Error parsing positive infinity value."); } } private void ParseNumberNaN() { if (MatchValueWithTrailingSeperator(JsonConvert.NaN)) { if (_floatParseHandling == FloatParseHandling.Decimal) throw new JsonReaderException("Cannot read NaN as a decimal."); SetToken(JsonToken.Float, double.NaN); } else { throw JsonReaderException.Create(this, "Error parsing NaN value."); } } /// <summary> /// Changes the state to closed. /// </summary> public override void Close() { base.Close(); if (CloseInput && _reader != null) #if !(NETFX_CORE || PORTABLE40 || PORTABLE) _reader.Close(); #else _reader.Dispose(); #endif if (_buffer != null) _buffer.Clear(); } /// <summary> /// Gets a value indicating whether the class can return line information. /// </summary> /// <returns> /// <c>true</c> if LineNumber and LinePosition can be provided; otherwise, <c>false</c>. /// </returns> public bool HasLineInfo() { return true; } /// <summary> /// Gets the current line number. /// </summary> /// <value> /// The current line number or 0 if no line information is available (for example, HasLineInfo returns false). /// </value> public int LineNumber { get { if (CurrentState == State.Start && LinePosition == 0) return 0; return _lineNumber; } } /// <summary> /// Gets the current line position. /// </summary> /// <value> /// The current line position or 0 if no line information is available (for example, HasLineInfo returns false). /// </value> public int LinePosition { get { return _charPos - _lineStartPos; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using Microsoft.Extensions.Primitives; namespace Microsoft.Net.Http.Headers { /// <summary> /// Represents the <c>Set-Cookie</c> header. /// <para> /// See http://tools.ietf.org/html/rfc6265 for the Set-Cookie header specification. /// </para> /// </summary> public class SetCookieHeaderValue { private const string ExpiresToken = "expires"; private const string MaxAgeToken = "max-age"; private const string DomainToken = "domain"; private const string PathToken = "path"; private const string SecureToken = "secure"; // RFC Draft: https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 private const string SameSiteToken = "samesite"; private static readonly string SameSiteNoneToken = SameSiteMode.None.ToString().ToLowerInvariant(); private static readonly string SameSiteLaxToken = SameSiteMode.Lax.ToString().ToLowerInvariant(); private static readonly string SameSiteStrictToken = SameSiteMode.Strict.ToString().ToLowerInvariant(); private const string HttpOnlyToken = "httponly"; private const string SeparatorToken = "; "; private const string EqualsToken = "="; private const int ExpiresDateLength = 29; private const string ExpiresDateFormat = "r"; private static readonly HttpHeaderParser<SetCookieHeaderValue> SingleValueParser = new GenericHeaderParser<SetCookieHeaderValue>(false, GetSetCookieLength); private static readonly HttpHeaderParser<SetCookieHeaderValue> MultipleValueParser = new GenericHeaderParser<SetCookieHeaderValue>(true, GetSetCookieLength); private StringSegment _name; private StringSegment _value; private SetCookieHeaderValue() { // Used by the parser to create a new instance of this type. } /// <summary> /// Initializes a new instance of <see cref="SetCookieHeaderValue"/>. /// </summary> /// <param name="name">The cookie name.</param> public SetCookieHeaderValue(StringSegment name) : this(name, StringSegment.Empty) { } /// <summary> /// Initializes a new instance of <see cref="SetCookieHeaderValue"/>. /// </summary> /// <param name="name">The cookie name.</param> /// <param name="value">The cookie value.</param> public SetCookieHeaderValue(StringSegment name, StringSegment value) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } Name = name; Value = value; } /// <summary> /// Gets or sets the cookie name. /// </summary> public StringSegment Name { get { return _name; } set { CookieHeaderValue.CheckNameFormat(value, nameof(value)); _name = value; } } /// <summary> /// Gets or sets the cookie value. /// </summary> public StringSegment Value { get { return _value; } set { CookieHeaderValue.CheckValueFormat(value, nameof(value)); _value = value; } } /// <summary> /// Gets or sets a value for the <c>Expires</c> cookie attribute. /// <para> /// The Expires attribute indicates the maximum lifetime of the cookie, /// represented as the date and time at which the cookie expires. /// </para> /// </summary> /// <remarks>See https://tools.ietf.org/html/rfc6265#section-4.1.2.1</remarks> public DateTimeOffset? Expires { get; set; } /// <summary> /// Gets or sets a value for the <c>Max-Age</c> cookie attribute. /// <para> /// The Max-Age attribute indicates the maximum lifetime of the cookie, /// represented as the number of seconds until the cookie expires. /// </para> /// </summary> /// <remarks>See https://tools.ietf.org/html/rfc6265#section-4.1.2.2</remarks> public TimeSpan? MaxAge { get; set; } /// <summary> /// Gets or sets a value for the <c>Domain</c> cookie attribute. /// <para> /// The Domain attribute specifies those hosts to which the cookie will /// be sent. /// </para> /// </summary> /// <remarks>See https://tools.ietf.org/html/rfc6265#section-4.1.2.3</remarks> public StringSegment Domain { get; set; } /// <summary> /// Gets or sets a value for the <c>Path</c> cookie attribute. /// <para> /// The path attribute specifies those hosts to which the cookie will /// be sent. /// </para> /// </summary> /// <remarks>See https://tools.ietf.org/html/rfc6265#section-4.1.2.4</remarks> public StringSegment Path { get; set; } /// <summary> /// Gets or sets a value for the <c>Secure</c> cookie attribute. /// <para> /// The Secure attribute limits the scope of the cookie to "secure" /// channels. /// </para> /// </summary> /// <remarks>See https://tools.ietf.org/html/rfc6265#section-4.1.2.5</remarks> public bool Secure { get; set; } /// <summary> /// Gets or sets a value for the <c>SameSite</c> cookie attribute. /// <para> /// "SameSite" cookies offer a robust defense against CSRF attack when /// deployed in strict mode, and when supported by the client. /// </para> /// </summary> /// <remarks>See https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-05#section-8.8</remarks> public SameSiteMode SameSite { get; set; } = SameSiteMode.Unspecified; /// <summary> /// Gets or sets a value for the <c>HttpOnly</c> cookie attribute. /// <para> /// HttpOnly instructs the user agent to /// omit the cookie when providing access to cookies via "non-HTTP" APIs /// (such as a web browser API that exposes cookies to scripts). /// </para> /// </summary> /// <remarks>See https://tools.ietf.org/html/rfc6265#section-4.1.2.6</remarks> public bool HttpOnly { get; set; } /// <summary> /// Gets a collection of additional values to append to the cookie. /// </summary> public IList<StringSegment> Extensions { get; } = new List<StringSegment>(); // name="value"; expires=Sun, 06 Nov 1994 08:49:37 GMT; max-age=86400; domain=domain1; path=path1; secure; samesite={strict|lax|none}; httponly /// <inheritdoc /> public override string ToString() { var length = _name.Length + EqualsToken.Length + _value.Length; string? maxAge = null; string? sameSite = null; if (Expires.HasValue) { length += SeparatorToken.Length + ExpiresToken.Length + EqualsToken.Length + ExpiresDateLength; } if (MaxAge.HasValue) { maxAge = HeaderUtilities.FormatNonNegativeInt64((long)MaxAge.GetValueOrDefault().TotalSeconds); length += SeparatorToken.Length + MaxAgeToken.Length + EqualsToken.Length + maxAge.Length; } if (Domain != null) { length += SeparatorToken.Length + DomainToken.Length + EqualsToken.Length + Domain.Length; } if (Path != null) { length += SeparatorToken.Length + PathToken.Length + EqualsToken.Length + Path.Length; } if (Secure) { length += SeparatorToken.Length + SecureToken.Length; } // Allow for Unspecified (-1) to skip SameSite if (SameSite == SameSiteMode.None) { sameSite = SameSiteNoneToken; length += SeparatorToken.Length + SameSiteToken.Length + EqualsToken.Length + sameSite.Length; } else if (SameSite == SameSiteMode.Lax) { sameSite = SameSiteLaxToken; length += SeparatorToken.Length + SameSiteToken.Length + EqualsToken.Length + sameSite.Length; } else if (SameSite == SameSiteMode.Strict) { sameSite = SameSiteStrictToken; length += SeparatorToken.Length + SameSiteToken.Length + EqualsToken.Length + sameSite.Length; } if (HttpOnly) { length += SeparatorToken.Length + HttpOnlyToken.Length; } foreach (var extension in Extensions) { length += SeparatorToken.Length + extension.Length; } return string.Create(length, (this, maxAge, sameSite), (span, tuple) => { var (headerValue, maxAgeValue, sameSite) = tuple; Append(ref span, headerValue._name); Append(ref span, EqualsToken); Append(ref span, headerValue._value); if (headerValue.Expires is DateTimeOffset expiresValue) { Append(ref span, SeparatorToken); Append(ref span, ExpiresToken); Append(ref span, EqualsToken); var formatted = expiresValue.TryFormat(span, out var charsWritten, ExpiresDateFormat); span = span.Slice(charsWritten); Debug.Assert(formatted); } if (maxAgeValue != null) { AppendSegment(ref span, MaxAgeToken, maxAgeValue); } if (headerValue.Domain != null) { AppendSegment(ref span, DomainToken, headerValue.Domain); } if (headerValue.Path != null) { AppendSegment(ref span, PathToken, headerValue.Path); } if (headerValue.Secure) { AppendSegment(ref span, SecureToken, null); } if (sameSite != null) { AppendSegment(ref span, SameSiteToken, sameSite); } if (headerValue.HttpOnly) { AppendSegment(ref span, HttpOnlyToken, null); } foreach (var extension in Extensions) { AppendSegment(ref span, extension, null); } }); } private static void AppendSegment(ref Span<char> span, StringSegment name, StringSegment value) { Append(ref span, SeparatorToken); Append(ref span, name.AsSpan()); if (value != null) { Append(ref span, EqualsToken); Append(ref span, value.AsSpan()); } } private static void Append(ref Span<char> span, ReadOnlySpan<char> other) { other.CopyTo(span); span = span.Slice(other.Length); } /// <summary> /// Append string representation of this <see cref="SetCookieHeaderValue"/> to given /// <paramref name="builder"/>. /// </summary> /// <param name="builder"> /// The <see cref="StringBuilder"/> to receive the string representation of this /// <see cref="SetCookieHeaderValue"/>. /// </param> public void AppendToStringBuilder(StringBuilder builder) { builder.Append(_name.AsSpan()); builder.Append('='); builder.Append(_value.AsSpan()); if (Expires.HasValue) { AppendSegment(builder, ExpiresToken, HeaderUtilities.FormatDate(Expires.GetValueOrDefault())); } if (MaxAge.HasValue) { AppendSegment(builder, MaxAgeToken, HeaderUtilities.FormatNonNegativeInt64((long)MaxAge.GetValueOrDefault().TotalSeconds)); } if (Domain != null) { AppendSegment(builder, DomainToken, Domain); } if (Path != null) { AppendSegment(builder, PathToken, Path); } if (Secure) { AppendSegment(builder, SecureToken, null); } // Allow for Unspecified (-1) to skip SameSite if (SameSite == SameSiteMode.None) { AppendSegment(builder, SameSiteToken, SameSiteNoneToken); } else if (SameSite == SameSiteMode.Lax) { AppendSegment(builder, SameSiteToken, SameSiteLaxToken); } else if (SameSite == SameSiteMode.Strict) { AppendSegment(builder, SameSiteToken, SameSiteStrictToken); } if (HttpOnly) { AppendSegment(builder, HttpOnlyToken, null); } foreach (var extension in Extensions) { AppendSegment(builder, extension, null); } } private static void AppendSegment(StringBuilder builder, StringSegment name, StringSegment value) { builder.Append("; "); builder.Append(name.AsSpan()); if (value != null) { builder.Append('='); builder.Append(value.AsSpan()); } } /// <summary> /// Parses <paramref name="input"/> as a <see cref="SetCookieHeaderValue"/> value. /// </summary> /// <param name="input">The values to parse.</param> /// <returns>The parsed values.</returns> public static SetCookieHeaderValue Parse(StringSegment input) { var index = 0; return SingleValueParser.ParseValue(input, ref index)!; } /// <summary> /// Attempts to parse the specified <paramref name="input"/> as a <see cref="SetCookieHeaderValue"/>. /// </summary> /// <param name="input">The value to parse.</param> /// <param name="parsedValue">The parsed value.</param> /// <returns><see langword="true"/> if input is a valid <see cref="SetCookieHeaderValue"/>, otherwise <see langword="false"/>.</returns> public static bool TryParse(StringSegment input, [NotNullWhen(true)] out SetCookieHeaderValue? parsedValue) { var index = 0; return SingleValueParser.TryParseValue(input, ref index, out parsedValue!); } /// <summary> /// Parses a sequence of inputs as a sequence of <see cref="SetCookieHeaderValue"/> values. /// </summary> /// <param name="inputs">The values to parse.</param> /// <returns>The parsed values.</returns> public static IList<SetCookieHeaderValue> ParseList(IList<string>? inputs) { return MultipleValueParser.ParseValues(inputs); } /// <summary> /// Parses a sequence of inputs as a sequence of <see cref="SetCookieHeaderValue"/> values using string parsing rules. /// </summary> /// <param name="inputs">The values to parse.</param> /// <returns>The parsed values.</returns> public static IList<SetCookieHeaderValue> ParseStrictList(IList<string>? inputs) { return MultipleValueParser.ParseStrictValues(inputs); } /// <summary> /// Attempts to parse the sequence of values as a sequence of <see cref="SetCookieHeaderValue"/>. /// </summary> /// <param name="inputs">The values to parse.</param> /// <param name="parsedValues">The parsed values.</param> /// <returns><see langword="true"/> if all inputs are valid <see cref="SetCookieHeaderValue"/>, otherwise <see langword="false"/>.</returns> public static bool TryParseList(IList<string>? inputs, [NotNullWhen(true)] out IList<SetCookieHeaderValue>? parsedValues) { return MultipleValueParser.TryParseValues(inputs, out parsedValues); } /// <summary> /// Attempts to parse the sequence of values as a sequence of <see cref="SetCookieHeaderValue"/> using string parsing rules. /// </summary> /// <param name="inputs">The values to parse.</param> /// <param name="parsedValues">The parsed values.</param> /// <returns><see langword="true"/> if all inputs are valid <see cref="StringWithQualityHeaderValue"/>, otherwise <see langword="false"/>.</returns> public static bool TryParseStrictList(IList<string>? inputs, [NotNullWhen(true)] out IList<SetCookieHeaderValue>? parsedValues) { return MultipleValueParser.TryParseStrictValues(inputs, out parsedValues); } // name=value; expires=Sun, 06 Nov 1994 08:49:37 GMT; max-age=86400; domain=domain1; path=path1; secure; samesite={Strict|Lax|None}; httponly private static int GetSetCookieLength(StringSegment input, int startIndex, out SetCookieHeaderValue? parsedValue) { Contract.Requires(startIndex >= 0); var offset = startIndex; parsedValue = null; if (StringSegment.IsNullOrEmpty(input) || (offset >= input.Length)) { return 0; } var result = new SetCookieHeaderValue(); // The caller should have already consumed any leading whitespace, commas, etc.. // Name=value; // Name var itemLength = HttpRuleParser.GetTokenLength(input, offset); if (itemLength == 0) { return 0; } result._name = input.Subsegment(offset, itemLength); offset += itemLength; // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return 0; } // value or "quoted value" // The value may be empty result._value = CookieHeaderParserShared.GetCookieValue(input, ref offset); // *(';' SP cookie-av) while (offset < input.Length) { if (input[offset] == ',') { // Divider between headers break; } if (input[offset] != ';') { // Expecting a ';' between parameters return 0; } offset++; offset += HttpRuleParser.GetWhitespaceLength(input, offset); // cookie-av = expires-av / max-age-av / domain-av / path-av / secure-av / samesite-av / httponly-av / extension-av itemLength = HttpRuleParser.GetTokenLength(input, offset); if (itemLength == 0) { // Trailing ';' or leading into garbage. Let the next parser fail. break; } var token = input.Subsegment(offset, itemLength); offset += itemLength; // expires-av = "Expires=" sane-cookie-date if (StringSegment.Equals(token, ExpiresToken, StringComparison.OrdinalIgnoreCase)) { // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return 0; } // We don't want to include comma, becouse date may contain it (eg. Sun, 06 Nov...) var dateString = ReadToSemicolonOrEnd(input, ref offset, includeComma: false); DateTimeOffset expirationDate; if (!HttpRuleParser.TryStringToDate(dateString, out expirationDate)) { // Invalid expiration date, abort return 0; } result.Expires = expirationDate; } // max-age-av = "Max-Age=" non-zero-digit *DIGIT else if (StringSegment.Equals(token, MaxAgeToken, StringComparison.OrdinalIgnoreCase)) { // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return 0; } itemLength = HttpRuleParser.GetNumberLength(input, offset, allowDecimal: false); if (itemLength == 0) { return 0; } var numberString = input.Subsegment(offset, itemLength); long maxAge; if (!HeaderUtilities.TryParseNonNegativeInt64(numberString, out maxAge)) { // Invalid expiration date, abort return 0; } result.MaxAge = TimeSpan.FromSeconds(maxAge); offset += itemLength; } // domain-av = "Domain=" domain-value // domain-value = <subdomain> ; defined in [RFC1034], Section 3.5, as enhanced by [RFC1123], Section 2.1 else if (StringSegment.Equals(token, DomainToken, StringComparison.OrdinalIgnoreCase)) { // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return 0; } // We don't do any detailed validation on the domain. result.Domain = ReadToSemicolonOrEnd(input, ref offset); } // path-av = "Path=" path-value // path-value = <any CHAR except CTLs or ";"> else if (StringSegment.Equals(token, PathToken, StringComparison.OrdinalIgnoreCase)) { // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return 0; } // We don't do any detailed validation on the path. result.Path = ReadToSemicolonOrEnd(input, ref offset); } // secure-av = "Secure" else if (StringSegment.Equals(token, SecureToken, StringComparison.OrdinalIgnoreCase)) { result.Secure = true; } // samesite-av = "SameSite=" samesite-value // samesite-value = "Strict" / "Lax" / "None" else if (StringSegment.Equals(token, SameSiteToken, StringComparison.OrdinalIgnoreCase)) { if (!ReadEqualsSign(input, ref offset)) { result.SameSite = SameSiteMode.Unspecified; } else { var enforcementMode = ReadToSemicolonOrEnd(input, ref offset); if (StringSegment.Equals(enforcementMode, SameSiteStrictToken, StringComparison.OrdinalIgnoreCase)) { result.SameSite = SameSiteMode.Strict; } else if (StringSegment.Equals(enforcementMode, SameSiteLaxToken, StringComparison.OrdinalIgnoreCase)) { result.SameSite = SameSiteMode.Lax; } else if (StringSegment.Equals(enforcementMode, SameSiteNoneToken, StringComparison.OrdinalIgnoreCase)) { result.SameSite = SameSiteMode.None; } else { result.SameSite = SameSiteMode.Unspecified; } } } // httponly-av = "HttpOnly" else if (StringSegment.Equals(token, HttpOnlyToken, StringComparison.OrdinalIgnoreCase)) { result.HttpOnly = true; } // extension-av = <any CHAR except CTLs or ";"> else { var tokenStart = offset - itemLength; ReadToSemicolonOrEnd(input, ref offset, includeComma: true); result.Extensions.Add(input.Subsegment(tokenStart, offset - tokenStart)); } } parsedValue = result; return offset - startIndex; } private static bool ReadEqualsSign(StringSegment input, ref int offset) { // = (no spaces) if (offset >= input.Length || input[offset] != '=') { return false; } offset++; return true; } private static StringSegment ReadToSemicolonOrEnd(StringSegment input, ref int offset, bool includeComma = true) { var end = input.IndexOf(';', offset); if (end < 0) { // Also valid end of cookie if (includeComma) { end = input.IndexOf(',', offset); } } else if (includeComma) { var commaPosition = input.IndexOf(',', offset); if (commaPosition >= 0 && commaPosition < end) { end = commaPosition; } } if (end < 0) { // Remainder of the string end = input.Length; } var itemLength = end - offset; var result = input.Subsegment(offset, itemLength); offset += itemLength; return result; } /// <inheritdoc /> public override bool Equals(object? obj) { var other = obj as SetCookieHeaderValue; if (other == null) { return false; } return StringSegment.Equals(_name, other._name, StringComparison.OrdinalIgnoreCase) && StringSegment.Equals(_value, other._value, StringComparison.OrdinalIgnoreCase) && Expires.Equals(other.Expires) && MaxAge.Equals(other.MaxAge) && StringSegment.Equals(Domain, other.Domain, StringComparison.OrdinalIgnoreCase) && StringSegment.Equals(Path, other.Path, StringComparison.OrdinalIgnoreCase) && Secure == other.Secure && SameSite == other.SameSite && HttpOnly == other.HttpOnly && HeaderUtilities.AreEqualCollections(Extensions, other.Extensions, StringSegmentComparer.OrdinalIgnoreCase); } /// <inheritdoc /> public override int GetHashCode() { var hash = StringSegmentComparer.OrdinalIgnoreCase.GetHashCode(_name) ^ StringSegmentComparer.OrdinalIgnoreCase.GetHashCode(_value) ^ (Expires.HasValue ? Expires.GetHashCode() : 0) ^ (MaxAge.HasValue ? MaxAge.GetHashCode() : 0) ^ (Domain != null ? StringSegmentComparer.OrdinalIgnoreCase.GetHashCode(Domain) : 0) ^ (Path != null ? StringSegmentComparer.OrdinalIgnoreCase.GetHashCode(Path) : 0) ^ Secure.GetHashCode() ^ SameSite.GetHashCode() ^ HttpOnly.GetHashCode(); foreach (var extension in Extensions) { hash ^= extension.GetHashCode(); } return hash; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; /// <summary> /// System.Collections.Generic.IEnumerator<T>.Current /// </summary> public class IEnumeratorCurrent { private int c_MINI_STRING_LENGTH = 8; private int c_MAX_STRING_LENGTH = 20; public static int Main() { IEnumeratorCurrent testObj = new IEnumeratorCurrent(); TestLibrary.TestFramework.BeginTestCase("Testing for Property: System.Collections.Generic.IEnumerator<T>.Current"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region PositiveTests public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Using customer class which implemented the GetEnumerator method in IEnumerator<T> and Type is int..."; const string c_TEST_ID = "P001"; int[] intList = new int[2]; int x = TestLibrary.Generator.GetInt32(-55); int y = TestLibrary.Generator.GetInt32(-55); intList[0] = x; intList[1] = y; MyEnumerator<int> myEnumerator = new MyEnumerator<int>(intList); ((IEnumerator<int>)myEnumerator).MoveNext(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (((IEnumerator<int>)myEnumerator).Current != x) { string errorDesc = "Value is not " + x + " as expected: Actual(" + ((IEnumerator<int>)myEnumerator).Current + ")"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } ((IEnumerator<int>)myEnumerator).MoveNext(); if (((IEnumerator<int>)myEnumerator).Current != y) { string errorDesc = "Value is not " + y + " as expected: Actual(" + ((IEnumerator<int>)myEnumerator).Current + ")"; TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Using List<T> which implemented the GetEnumerator method in IComparer<T> and Type is String..."; const string c_TEST_ID = "P002"; String[] strList = new String[2]; String x = TestLibrary.Generator.GetString(-55, false,c_MINI_STRING_LENGTH,c_MAX_STRING_LENGTH); String y = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); strList[0] = x; strList[1] = y; MyEnumerator<String> myEnumerator = new MyEnumerator<String>(strList); ((IEnumerator<String>)myEnumerator).MoveNext(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (((IEnumerator<String>)myEnumerator).Current != x) { string errorDesc = "Value is not " + x + " as expected: Actual(" + ((IEnumerator<String>)myEnumerator).Current + ")"; TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } ((IEnumerator<String>)myEnumerator).MoveNext(); if (((IEnumerator<String>)myEnumerator).Current != y) { string errorDesc = "Value is not " + y + " as expected: Actual(" + ((IEnumerator<String>)myEnumerator).Current + ")"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region NegativeTests public bool NegTest1() { bool retVal = true; int[] intList = new int[0]; MyEnumerator<int> myEnumerator = new MyEnumerator<int>(intList); ((IEnumerator<int>)myEnumerator).MoveNext(); TestLibrary.TestFramework.BeginScenario("NegTest1: Using user-defined type which is empty"); try { int i = ((IEnumerator<int>)myEnumerator).Current; TestLibrary.TestFramework.LogError("007", "The InvalidOperationException was not thrown as expected"); retVal = false; } catch (InvalidOperationException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Help Class public class MyEnumerator<T> : IEnumerator<T> { public T[] _item; // Enumerators are positioned before the first element // until the first MoveNext() call. int position = -1; public MyEnumerator(T[] list) { _item = list; } public bool MoveNext() { position++; return (position < _item.Length); } public void Reset() { position = -1; } public object Current { get { try { return _item[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } #region IEnumerator<T> Members T IEnumerator<T>.Current { get { try { return _item[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } #endregion #region IDisposable Members public void Dispose() { throw new Exception("The method or operation is not implemented."); } #endregion #region IDisposable Members void IDisposable.Dispose() { throw new Exception("The method or operation is not implemented."); } #endregion #region IEnumerator Members object System.Collections.IEnumerator.Current { get { try { return _item[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } bool System.Collections.IEnumerator.MoveNext() { position++; return (position < _item.Length); } void System.Collections.IEnumerator.Reset() { position = -1; } #endregion } #endregion }
// // Digest Authentication implementation // // Authors: // Greg Reinacker (gregr@rassoc.com) // Sebastien Pouliot (spouliot@motus.com) // // Copyright 2002-2003 Greg Reinacker, Reinacker & Associates, Inc. All rights reserved. // Portions (C) 2003 Motus Technologies Inc. (http://www.motus.com) // // Original source code available at // http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Specialized; using System.Configuration; using System.IO; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using System.Web; using System.Xml; namespace Mono.Http.Modules { public class DigestAuthenticationModule : AuthenticationModule { // TODO: Digest.Nonce.Lifetime="0" Never expires static int nonceLifetime = 60; static char[] trim = {'='}; public DigestAuthenticationModule () : base ("Digest") {} protected virtual bool IsValidNonce (string nonce) { DateTime expireTime; // pad nonce on the right with '=' until length is a multiple of 4 int numPadChars = nonce.Length % 4; if (numPadChars > 0) numPadChars = 4 - numPadChars; string newNonce = nonce.PadRight(nonce.Length + numPadChars, '='); try { byte[] decodedBytes = Convert.FromBase64String(newNonce); string expireStr = new ASCIIEncoding().GetString(decodedBytes); expireTime = DateTime.Parse(expireStr); } catch (FormatException e) { return false; } return (DateTime.Now <= expireTime); } protected virtual bool GetUserByName (HttpApplication app, string username, out string password, out string[] roles) { password = String.Empty; roles = new string[0]; string userFileName = app.Request.MapPath (ConfigurationSettings.AppSettings ["Digest.Users"]); if (userFileName == null || !File.Exists (userFileName)) return false; XmlDocument userDoc = new XmlDocument (); userDoc.Load (userFileName); string xPath = String.Format ("/users/user[@name='{0}']", username); XmlNode user = userDoc.SelectSingleNode (xPath); if (user == null) return false; password = user.Attributes ["password"].Value; XmlNodeList roleNodes = user.SelectNodes ("role"); roles = new string [roleNodes.Count]; int i = 0; foreach (XmlNode xn in roleNodes) roles [i++] = xn.Attributes ["name"].Value; return true; } protected override bool AcceptCredentials (HttpApplication app, string authentication) { // digest ListDictionary reqInfo = new ListDictionary (); string[] elems = authentication.Split( new char[] {','}); foreach (string elem in elems) { // form key="value" string[] parts = elem.Split (new char[] {'='}, 2); string key = parts [0].Trim (new char[] {' ','\"'}); string val = parts [1].Trim (new char[] {' ','\"'}); reqInfo.Add (key,val); } string username = (string) reqInfo ["username"]; string password; string[] roles; if (!GetUserByName (app, username, out password, out roles)) return false; string realm = ConfigurationSettings.AppSettings ["Digest.Realm"]; // calculate the Digest hashes // A1 = unq(username-value) ":" unq(realm-value) ":" passwd string A1 = String.Format ("{0}:{1}:{2}", username, realm, password); // H(A1) = MD5(A1) string HA1 = GetMD5HashBinHex (A1); // A2 = Method ":" digest-uri-value string A2 = String.Format ("{0}:{1}", app.Request.HttpMethod, (string)reqInfo["uri"]); // H(A2) string HA2 = GetMD5HashBinHex(A2); // KD(secret, data) = H(concat(secret, ":", data)) // if qop == auth: // request-digest = <"> < KD ( H(A1), unq(nonce-value) // ":" nc-value // ":" unq(cnonce-value) // ":" unq(qop-value) // ":" H(A2) // ) <"> // if qop is missing, // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <"> string unhashedDigest; if (reqInfo["qop"] != null) { unhashedDigest = String.Format("{0}:{1}:{2}:{3}:{4}:{5}", HA1, (string)reqInfo["nonce"], (string)reqInfo["nc"], (string)reqInfo["cnonce"], (string)reqInfo["qop"], HA2); } else { unhashedDigest = String.Format("{0}:{1}:{2}", HA1, (string)reqInfo["nonce"], HA2); } string hashedDigest = GetMD5HashBinHex (unhashedDigest); bool isNonceStale = !IsValidNonce((string)reqInfo["nonce"]); app.Context.Items["staleNonce"] = isNonceStale; bool result = (((string)reqInfo["response"] == hashedDigest) && (!isNonceStale)); if (result) { IIdentity id = new GenericIdentity (username, AuthenticationMethod); app.Context.User = new GenericPrincipal (id, roles); } return result; } #region Event Handlers public override void OnEndRequest(object source, EventArgs eventArgs) { // We add the WWW-Authenticate header here, so if an authorization // fails elsewhere than in this module, we can still request authentication // from the client. HttpApplication app = (HttpApplication) source; if (app.Response.StatusCode != 401 || !AuthenticationRequired) return; string realm = ConfigurationSettings.AppSettings ["Digest.Realm"]; string nonce = GetCurrentNonce (); bool isNonceStale = false; object staleObj = app.Context.Items ["staleNonce"]; if (staleObj != null) isNonceStale = (bool)staleObj; StringBuilder challenge = new StringBuilder ("Digest realm=\""); challenge.Append(realm); challenge.Append("\""); challenge.Append(", nonce=\""); challenge.Append(nonce); challenge.Append("\""); challenge.Append(", opaque=\"0000000000000000\""); challenge.Append(", stale="); challenge.Append(isNonceStale ? "true" : "false"); challenge.Append(", algorithm=MD5"); challenge.Append(", qop=\"auth\""); app.Response.AppendHeader("WWW-Authenticate", challenge.ToString()); app.Response.StatusCode = 401; } #endregion private string GetMD5HashBinHex (string toBeHashed) { MD5 hash = MD5.Create (); byte[] result = hash.ComputeHash (Encoding.ASCII.GetBytes (toBeHashed)); StringBuilder sb = new StringBuilder (); foreach (byte b in result) sb.Append (b.ToString ("x2")); return sb.ToString (); } protected virtual string GetCurrentNonce () { DateTime nonceTime = DateTime.Now.AddSeconds (nonceLifetime); byte[] expireBytes = Encoding.ASCII.GetBytes (nonceTime.ToString ("G")); string nonce = Convert.ToBase64String (expireBytes); // nonce can't end in '=', so trim them from the end nonce = nonce.TrimEnd (trim); return nonce; } } }
using System; using System.ComponentModel; using System.Linq; using Eto.Drawing; using Eto.Forms; using Eto.Mac.Forms.Controls; using System.Threading; #if XAMMAC2 using AppKit; using Foundation; using CoreGraphics; using ObjCRuntime; using CoreAnimation; using CoreImage; #else using MonoMac.AppKit; using MonoMac.Foundation; using MonoMac.CoreGraphics; using MonoMac.ObjCRuntime; using MonoMac.CoreAnimation; using MonoMac.CoreImage; #if Mac64 using CGSize = MonoMac.Foundation.NSSize; using CGRect = MonoMac.Foundation.NSRect; using CGPoint = MonoMac.Foundation.NSPoint; using nfloat = System.Double; using nint = System.Int64; using nuint = System.UInt64; #else using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using nfloat = System.Single; using nint = System.Int32; using nuint = System.UInt32; #endif #endif namespace Eto.Mac.Forms { public class MyWindow : NSWindow, IMacControl { CGRect oldFrame; bool zoom; public WeakReference WeakHandler { get; set; } public IMacWindow Handler { get { return (IMacWindow)WeakHandler.Target; } set { WeakHandler = new WeakReference(value); } } public MyWindow(CGRect rect, NSWindowStyle style, NSBackingStore store, bool flag) : base(rect, style, store, flag) { } public bool DisableCenterParent { get; set; } public override void Center() { if (DisableCenterParent) return; // implement centering to parent if there is a parent window for this one.. if (ParentWindow != null) { var parentFrame = ParentWindow.Frame; var frame = Frame; var location = new CGPoint((parentFrame.Width - frame.Width) / 2 + parentFrame.X, (parentFrame.Height - frame.Height) / 2 + parentFrame.Y); SetFrameOrigin(location); } else base.Center(); } public override void Zoom(NSObject sender) { if (zoom) { SetFrame(oldFrame, true, true); zoom = false; } else { oldFrame = Frame; base.Zoom(sender ?? this); // null when double clicking the title bar, but xammac/monomac doesn't allow it zoom = true; } Handler.Callback.OnWindowStateChanged(Handler.Widget, EventArgs.Empty); } } public interface IMacWindow { Rectangle? RestoreBounds { get; set; } Window Widget { get; } NSMenu MenuBar { get; } NSObject FieldEditorObject { get; set; } Size MinimumSize { get; } bool CloseWindow(Action<CancelEventArgs> closing = null); NSWindow Control { get; } Window.ICallback Callback { get; } } public class CustomFieldEditor : NSTextView { public CustomFieldEditor() { FieldEditor = true; } public CustomFieldEditor(IntPtr handle) : base(handle) { } public override void KeyDown(NSEvent theEvent) { var macControl = WeakDelegate as IMacControl; if (macControl != null) { var macViewHandler = macControl.WeakHandler.Target as IMacViewHandler; if (macViewHandler != null && MacEventView.KeyDown(macViewHandler.Widget, theEvent)) return; } base.KeyDown(theEvent); } } public abstract class MacWindow<TControl, TWidget, TCallback> : MacPanel<TControl, TWidget, TCallback>, Window.IHandler, IMacContainer, IMacWindow where TControl: NSWindow where TWidget: Window where TCallback: Window.ICallback { CustomFieldEditor fieldEditor; MenuBar menuBar; Icon icon; Eto.Forms.ToolBar toolBar; Rectangle? restoreBounds; bool setInitialSize; WindowState? initialState; bool maximizable = true; bool topmost; Point? oldLocation; Window.ICallback IMacWindow.Callback { get { return Callback; } } public override NSView ContainerControl { get { return Control.ContentView; } } public override object EventObject { get { return Control; } } static readonly Selector selSetStyleMask = new Selector("setStyleMask:"); public NSObject FieldEditorObject { get; set; } protected override SizeF GetNaturalSize(SizeF availableSize) { if (Content != null && Content.Visible) { var contentControl = Content.GetMacControl(); if (contentControl != null) { return contentControl.GetPreferredSize(availableSize) + Padding.Size; } } return new Size(200, 200); } public override Size MinimumSize { get { return base.MinimumSize; } set { base.MinimumSize = value; if (value != Size.Empty) { Control.WillResize = (sender, frameSize) => { if (value != Size.Empty) { return new CGSize((float)Math.Max(frameSize.Width, value.Width), (float)Math.Max(frameSize.Height, value.Height)); } return frameSize; }; } else Control.WillResize = null; } } public NSMenu MenuBar { get { return menuBar == null ? null : menuBar.ControlObject as NSMenu; } } protected override void Initialize() { base.Initialize(); Control.DidBecomeKey += HandleDidBecomeKey; Control.DidResignKey += HandleDidResignKey; Control.ShouldZoom = HandleShouldZoom; Control.WillMiniaturize += HandleWillMiniaturize; } IntPtr oldMenu; static IntPtr selMainMenu = Selector.GetHandle("mainMenu"); static IntPtr selSetMainMenu = Selector.GetHandle("setMainMenu:"); static void HandleDidBecomeKey(object sender, EventArgs e) { var handler = GetHandler(sender) as MacWindow<TControl,TWidget,TCallback>; if (handler == null) return; if (handler.MenuBar != null) { var ptr = Messaging.IntPtr_objc_msgSend(NSApplication.SharedApplication.Handle, selMainMenu); if (Runtime.TryGetNSObject(ptr) == null) { // it's a native menu, so let's hold on to it till we resign key of the form MacExtensions.Retain(ptr); handler.oldMenu = ptr; } NSApplication.SharedApplication.MainMenu = handler.MenuBar; } else handler.oldMenu = IntPtr.Zero; } static void HandleDidResignKey(object sender, EventArgs e) { var handler = GetHandler(sender) as MacWindow<TControl,TWidget,TCallback>; if (handler == null) return; if (handler.oldMenu != IntPtr.Zero) { // restore old native menu Messaging.void_objc_msgSend_IntPtr(NSApplication.SharedApplication.Handle, selSetMainMenu, handler.oldMenu); MacExtensions.Release(handler.oldMenu); handler.oldMenu = IntPtr.Zero; } } static bool HandleShouldZoom(NSWindow window, CGRect newFrame) { var handler = GetHandler(window) as MacWindow<TControl,TWidget,TCallback>; if (handler == null) return true; if (!handler.Maximizable) return false; if (!window.IsZoomed && window.Screen != null) { handler.RestoreBounds = handler.Widget.Bounds; } return true; } static void HandleWillMiniaturize(object sender, EventArgs e) { var handler = GetHandler(sender) as MacWindow<TControl,TWidget,TCallback>; if (handler == null) return; handler.RestoreBounds = handler.Widget.Bounds; } static void HandleWillClose(object sender, EventArgs e) { var handler = GetHandler(sender) as MacWindow<TControl,TWidget,TCallback>; if (handler == null) return; if (ApplicationHandler.Instance.ShouldCloseForm(handler.Widget, true)) handler.Callback.OnClosed(handler.Widget, EventArgs.Empty); } static bool HandleWindowShouldClose(NSObject sender) { var handler = GetHandler(sender) as MacWindow<TControl,TWidget,TCallback>; if (handler == null) return true; var args = new CancelEventArgs(); if (ApplicationHandler.Instance.ShouldCloseForm(handler.Widget, false)) handler.Callback.OnClosing(handler.Widget, args); return !args.Cancel; } static void HandleWindowStateChanged(object sender, EventArgs e) { var handler = GetHandler(sender) as MacWindow<TControl,TWidget,TCallback>; if (handler == null) return; handler.Callback.OnWindowStateChanged(handler.Widget, EventArgs.Empty); } static void HandleGotFocus(object sender, EventArgs e) { var handler = GetHandler(sender) as MacWindow<TControl,TWidget,TCallback>; if (handler == null) return; handler.Callback.OnGotFocus(handler.Widget, EventArgs.Empty); } static void HandleLostFocus(object sender, EventArgs e) { var handler = GetHandler(sender) as MacWindow<TControl,TWidget,TCallback>; if (handler == null) return; handler.Callback.OnLostFocus(handler.Widget, EventArgs.Empty); } public override void AttachEvent(string id) { switch (id) { case Window.ClosedEvent: Control.WillClose += HandleWillClose; break; case Window.ClosingEvent: Control.WindowShouldClose = HandleWindowShouldClose; break; case Window.WindowStateChangedEvent: Control.DidMiniaturize += HandleWindowStateChanged; Control.DidDeminiaturize += HandleWindowStateChanged; break; case Eto.Forms.Control.ShownEvent: // handled when shown break; case Eto.Forms.Control.GotFocusEvent: Control.DidBecomeKey += HandleGotFocus; break; case Eto.Forms.Control.LostFocusEvent: Control.DidResignKey += HandleLostFocus; break; case Eto.Forms.Control.SizeChangedEvent: { Size? oldSize = null; AddObserver(NSWindow.DidResizeNotification, e => { var handler = (MacWindow<TControl,TWidget,TCallback>)e.Handler; var newSize = handler.Size; if (oldSize != newSize) { handler.Callback.OnSizeChanged(handler.Widget, EventArgs.Empty); oldSize = newSize; } }); } break; case Window.LocationChangedEvent: { AddObserver(NSWindow.DidMoveNotification, e => { var handler = e.Handler as MacWindow<TControl,TWidget,TCallback>; if (handler != null) { var old = handler.oldLocation; handler.oldLocation = null; var newLocation = handler.Location; if (old != newLocation) { handler.oldLocation = newLocation; handler.Callback.OnLocationChanged(handler.Widget, EventArgs.Empty); } } }); // WillMove is only called when the user moves the window via the mouse Control.WillMove += HandleWillMove; } break; default: base.AttachEvent(id); break; } } void CreateCursorRect() { if (Cursor != null) { Control.ContentView.DiscardCursorRects(); Control.ContentView.AddCursorRect(new CGRect(CGPoint.Empty, Control.Frame.Size), Cursor.ControlObject as NSCursor); } else Control.ContentView.DiscardCursorRects(); } /// <summary> /// Tracks movement of the window until the mouse up button is found /// </summary> static void HandleWillMove(object sender, EventArgs e) { var handler = GetHandler(sender) as MacWindow<TControl,TWidget,TCallback>; if (handler == null) return; handler.oldLocation = null; // find offset of mouse cursor to location of window var moveOffset = Size.Round((SizeF)(Mouse.Position - handler.Location)); ThreadPool.QueueUserWorkItem(a => { bool tracking = true; while (tracking) { NSApplication.SharedApplication.InvokeOnMainThread(() => { var newLocation = Point.Round(Mouse.Position - moveOffset); if (handler.oldLocation != newLocation) { handler.Callback.OnLocationChanged(handler.Widget, EventArgs.Empty); handler.oldLocation = newLocation; } // check for mouse up event tracking = NSApplication.SharedApplication.NextEventEx(NSEventMask.LeftMouseUp, null, NSRunLoop.NSRunLoopEventTracking, false) == null; }); } handler.oldLocation = null; NSApplication.SharedApplication.InvokeOnMainThread(() => handler.Callback.OnLocationChanged(handler.Widget, EventArgs.Empty)); }); } protected void ConfigureWindow() { var myWindow = Control as MyWindow; if (myWindow != null) myWindow.Handler = this; Control.ContentView = new NSView(); //Control.ContentMinSize = new System.Drawing.SizeF(0, 0); Control.ContentView.AutoresizingMask = NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable; Control.ReleasedWhenClosed = false; Control.HasShadow = true; Control.ShowsResizeIndicator = true; Control.AutorecalculatesKeyViewLoop = true; //Control.Delegate = new MacWindowDelegate{ Handler = this }; Control.WillReturnFieldEditor = HandleWillReturnFieldEditor; } static NSObject HandleWillReturnFieldEditor(NSWindow sender, NSObject client) { var handler = GetHandler(sender) as MacWindow<TControl, TWidget, TCallback>; if (handler == null) return null; handler.FieldEditorObject = client; var control = client as IMacControl; if (control != null) { var childHandler = control.WeakHandler.Target as IMacViewHandler; if (childHandler != null) { var fieldEditor = childHandler.CustomFieldEditor; if (fieldEditor != null) return fieldEditor; } } return handler.fieldEditor ?? (handler.fieldEditor = new CustomFieldEditor());; } public override NSView ContentControl { get { return Control.ContentView; } } public virtual string Title { get { return Control.Title; } set { Control.Title = value ?? ""; } } // Control.Title throws an exception if value is null void SetButtonStates() { var button = Control.StandardWindowButton(NSWindowButton.ZoomButton); if (button != null) button.Enabled = Maximizable && Resizable; } public bool Resizable { get { return Control.StyleMask.HasFlag(NSWindowStyle.Resizable); } set { if (Control.RespondsToSelector(selSetStyleMask)) { if (value) Control.StyleMask |= NSWindowStyle.Resizable; else Control.StyleMask &= ~NSWindowStyle.Resizable; SetButtonStates(); } } } public bool Minimizable { get { return Control.StyleMask.HasFlag(NSWindowStyle.Miniaturizable); } set { if (Control.RespondsToSelector(selSetStyleMask)) { if (value) Control.StyleMask |= NSWindowStyle.Miniaturizable; else Control.StyleMask &= ~NSWindowStyle.Miniaturizable; SetButtonStates(); } } } public bool Maximizable { get { return maximizable; } set { if (maximizable != value) { maximizable = value; SetButtonStates(); } } } public bool ShowInTaskbar { get; set; } public bool Topmost { get { return topmost; } set { if (topmost != value) { topmost = value; Control.Level = value ? NSWindowLevel.PopUpMenu : NSWindowLevel.Normal; } } } public override Size Size { get { return Control.Frame.Size.ToEtoSize(); } set { var oldFrame = Control.Frame; var newFrame = oldFrame.SetSize(value); newFrame.Y = (nfloat)Math.Max(0, oldFrame.Y - (value.Height - oldFrame.Height)); Control.SetFrame(newFrame, true); AutoSize = false; } } public MenuBar Menu { get { return menuBar; } set { menuBar = value; if (Control.IsKeyWindow) { NSApplication.SharedApplication.MainMenu = (NSMenu)value.ControlObject; } } } public bool CloseWindow(Action<CancelEventArgs> closing = null) { var args = new CancelEventArgs(); Callback.OnClosing(Widget, args); if (!args.Cancel && closing != null) closing(args); if (!args.Cancel) { Callback.OnClosed(Widget, EventArgs.Empty); } return !args.Cancel; } public virtual void Close() { var args = new CancelEventArgs(); Callback.OnClosing(Widget, args); if (!args.Cancel) Control.Close(); } public Eto.Forms.ToolBar ToolBar { get { return toolBar; } set { toolBar = value; Control.Toolbar = (NSToolbar)toolBar.ControlObject; } } public Icon Icon { get { return icon; } set { icon = value; // don't really do anything here.. no where to put it } } public override void Focus() { Control.BecomeFirstResponder(); } public string Id { get; set; } public override Size ClientSize { get { return Control.ContentView.Frame.Size.ToEtoSize(); } set { var oldFrame = Control.Frame; var oldSize = Control.ContentView.Frame; Control.SetFrameOrigin(new CGPoint(oldFrame.X, (nfloat)Math.Max(0, oldFrame.Y - (value.Height - oldSize.Height)))); Control.SetContentSize(value.ToNS()); AutoSize = false; } } public override bool HasFocus { get { return Control.IsKeyWindow; } } public override bool Visible { get { return Control.IsVisible; } set { if (value && !Control.IsVisible) Control.MakeKeyAndOrderFront(NSApplication.SharedApplication); if (!value && Control.IsVisible) Control.PerformClose(NSApplication.SharedApplication); // huh? } } public override Cursor Cursor { get { return base.Cursor; } set { base.Cursor = value; CreateCursorRect(); } } public virtual Point Location { get { if (oldLocation != null) return oldLocation.Value; // translate location relative to the top left corner of main screen var mainFrame = NSScreen.Screens[0].Frame; var frame = Control.Frame; return new Point((int)frame.X, (int)(mainFrame.Height - frame.Y - frame.Height)); } set { // location is relative to the main screen, translate to bottom left, inversed var mainFrame = NSScreen.Screens[0].Frame; var frame = Control.Frame; var point = new CGPoint((nfloat)value.X, (nfloat)(mainFrame.Height - value.Y - frame.Height)); Control.SetFrameOrigin(point); if (Control.Screen == null) { // ensure that the control lands on a screen point.X = (nfloat)Math.Min(Math.Max(mainFrame.X, point.X), mainFrame.Right - frame.Width); point.Y = (nfloat)Math.Min(Math.Max(mainFrame.Y, point.Y), mainFrame.Bottom - frame.Height); Control.SetFrameOrigin(point); } var etoWindow = Control as MyWindow; if (etoWindow != null) etoWindow.DisableCenterParent = true; } } public WindowState WindowState { get { if (initialState != null) return initialState.Value; if (Control.IsMiniaturized) return WindowState.Minimized; if (Control.IsZoomed) return WindowState.Maximized; return WindowState.Normal; } set { if (!Widget.Loaded) { initialState = value; return; } switch (value) { case WindowState.Maximized: if (Control.IsMiniaturized) Control.Deminiaturize(Control); if (!Control.IsZoomed) Control.PerformZoom(Control); break; case WindowState.Minimized: if (!Control.IsMiniaturized) Control.Miniaturize(Control); break; case WindowState.Normal: if (Control.IsZoomed) Control.Zoom(Control); if (Control.IsMiniaturized) Control.Deminiaturize(Control); break; } } } public Rectangle RestoreBounds { get { return WindowState == WindowState.Normal ? Widget.Bounds : restoreBounds ?? Widget.Bounds; } set { restoreBounds = value; } } public double Opacity { get { return Control.IsOpaque ? 1.0 : Control.AlphaValue; } set { Control.IsOpaque = Math.Abs(value - 1.0) < 0.01f; Control.AlphaValue = (float)value; } } public override void OnLoad(EventArgs e) { base.OnLoad(e); if (AutoSize) { var size = GetPreferredSize(Size.MaxValue); SetContentSize(size.ToNS()); setInitialSize = true; } PositionWindow(); } public override void OnLoadComplete(EventArgs e) { base.OnLoadComplete(e); if (initialState != null) { WindowState = initialState.Value; initialState = null; } } protected virtual void PositionWindow() { Control.Center(); } #region IMacContainer implementation public override void SetContentSize(CGSize contentSize) { if (MinimumSize != Size.Empty) { contentSize.Width = (nfloat)Math.Max(contentSize.Width, MinimumSize.Width); contentSize.Height = (nfloat)Math.Max(contentSize.Height, MinimumSize.Height); } if (Widget.Loaded) { var diffy = ClientSize.Height - (int)contentSize.Height; var diffx = ClientSize.Width - (int)contentSize.Width; var frame = Control.Frame; if (diffx < 0 || !setInitialSize) { frame.Width -= diffx; } if (diffy < 0 || !setInitialSize) { frame.Y += diffy; frame.Height -= diffy; } Control.SetFrame(frame, false, false); } else Control.SetContentSize(contentSize); } #endregion #region IMacWindow implementation Rectangle? IMacWindow.RestoreBounds { get { return restoreBounds; } set { restoreBounds = value; } } Window IMacWindow.Widget { get { return Widget; } } NSWindow IMacWindow.Control { get { return Control; } } #endregion public Screen Screen { get { return new Screen(new ScreenHandler(Control.Screen)); } } public override PointF PointFromScreen(PointF point) { var sdpoint = point.ToNS(); sdpoint = Control.ConvertBaseToScreen(sdpoint); sdpoint.Y = Control.Screen.Frame.Height - sdpoint.Y; return sdpoint.ToEto(); } public override PointF PointToScreen(PointF point) { var sdpoint = point.ToNS(); sdpoint = Control.ConvertBaseToScreen(sdpoint); sdpoint.Y = Control.Screen.Frame.Height - sdpoint.Y; return sdpoint.ToEto(); } public WindowStyle WindowStyle { get { return Control.StyleMask.ToEtoWindowStyle(); } set { if (Control.RespondsToSelector(selSetStyleMask)) { Control.StyleMask = value.ToNS(Control.StyleMask); } } } public void BringToFront() { Control.OrderFront(Control); Control.MakeKeyWindow(); } public void SendToBack() { Control.OrderBack(Control); var window = NSApplication.SharedApplication.Windows.FirstOrDefault(r => r != Control); if (window != null) window.MakeKeyWindow(); Control.ResignKeyWindow(); } public virtual void SetOwner(Window owner) { } } }
using System; using Nancy; using SWPCCBilling2.Infrastructure; using SWPCCBilling2.Models; using System.Collections.Generic; using System.Linq; using System.Text; namespace SWPCCBilling2.Modules { public class ReportModule : NancyModule { public ReportModule(PaymentStore paymentStore, InvoiceStore invoiceStore, ParentStore parentStore, DepositStore depositStore, DepositSummaryFactory depositSummaryFactory, FeeStore feeStore, InvoiceReportRenderer invoiceReportRenderer) { Get["/report/deposit/pending"] = _ => { IList<Payment> undeposited = paymentStore.LoadUndeposited().ToList(); decimal depositAmount = undeposited.Sum(x => (decimal)x.Amount); return View["DepositPending", new { Checks = undeposited .OrderBy(p => p.Id) .Select(p => new { p.Id, p.FamilyName, p.CheckNum, p.Amount, AmountText = p.Amount.ToString("C") }), Count = undeposited.Count, Amount = depositAmount, AmountText = depositAmount.ToString("C") }]; }; Get["/report/deposit/{id}"] = _ => { long depositId = _.id; Deposit deposit = depositStore.Load(depositId); string depositDateText = deposit != null ? deposit.Date.ToString("dddd MMMM d, yyyy") : "Not Found"; IList<Payment> deposited = paymentStore.LoadForDepositId(depositId).ToList(); decimal depositAmount = deposited.Sum(x => (decimal)x.Amount); return View["Deposit", new { DepositId = depositId, Checks = deposited .OrderBy(p => p.Id) .Select(p => new { p.Id, p.FamilyName, p.CheckNum, p.Amount, AmountText = p.Amount.ToString("C") }), Count = deposited.Count, Amount = depositAmount, AmountText = depositAmount.ToString("C"), DepositDateText = depositDateText }]; }; Get["/report/unpaid/{date}"] = _ => { IList<Invoice> unpaidInvoices = invoiceStore.LoadOpenInvoicesAfter(_.date); IEnumerable<string> unpaidEmails = unpaidInvoices .SelectMany(i => parentStore .LoadForFamilyName(i.FamilyName) .Select(p => p.Email) .Where(e => e != null)); return View["Unpaid", unpaidEmails]; }; Get["/report/invoices/{deposit}"] = _ => { string depositArg = _.deposit; IList<long> depositIds; if (depositArg == "all") depositIds = depositStore.LoadAll() .Select(d => d.Id) .OrderBy(id => id) .ToList(); else depositIds = new List<long>(new[]{ Int64.Parse(depositArg)}); IDictionary<string, Fee> cachedFees = feeStore.LoadAll().ToDictionary(f => f.Code, f => f); var models = new List<DepositInvoiceData>(); foreach (long depositId in depositIds) { Deposit deposit = depositStore.Load(depositId); var depositInvoiceData = new DepositInvoiceData { DepositId = depositId, DepositDateText = deposit.Date.ToShortDateString(), DepositAmountText = deposit.Amount.ToString("C") }; IList<Payment> payments = paymentStore .LoadForDepositId(depositId) .OrderBy(p => p.Received) .ToList(); IList<long> invoiceIds = payments .Select(p => p.InvoiceId) .Distinct() .OrderBy(id => id) .ToList(); foreach (long invoiceId in invoiceIds) { var invoice = invoiceStore.Load(invoiceId); var invoiceData = new InvoiceData { InvoiceId = invoiceId, FamilyName = invoice.FamilyName, ClosedDateText = invoice.Closed.Value.ToShortDateString() }; decimal amountDue = 0.0m; var feeTotals = new Dictionary<string, decimal>(); foreach (InvoiceLine invoiceLine in invoice.Lines) { Fee fee = cachedFees[invoiceLine.FeeCode]; if (fee.Category == "Payment") continue; amountDue += invoiceLine.Amount(); decimal feeTotal = feeTotals.ContainsKey(fee.Category) ? feeTotals[fee.Category] : 0.0m; feeTotal += invoiceLine.Amount(); feeTotals[fee.Category] = feeTotal; } invoiceData.AmountDueText = amountDue.ToString("C"); foreach (Payment payment in payments.Where(p => p.InvoiceId == invoiceId)) { var paymentData = new PaymentData { PaymentId = payment.Id, CheckNumber = payment.CheckNum, AmountText = payment.Amount.ToString("C"), ReceivedDateText = payment.Received.ToShortDateString() }; invoiceData.PaymentData.Add(paymentData); } invoiceData.FeePayments = feeTotals.ToList() .Select(fp => new FeePayment { FeeCategory = fp.Key, TotalPaidText = fp.Value.ToHtmlCurrency() }).ToList(); depositInvoiceData.InvoiceData.Add(invoiceData); } models.Add(depositInvoiceData); } return View["Invoices", new { Html = invoiceReportRenderer.Render(models)}]; }; Get["/report/monthly/{date}"] = _ => { DateTime month = _.date; IList<Invoice> monthlyInvoices = invoiceStore.LoadInvoicesForMonth(month); var model = new MonthlyData(); model.Month = month.ToString("MMMM yyyy"); model.InvoiceSummaries = monthlyInvoices .OrderBy(i => i.Closed) .Select(i => new MonthlyInvoiceSummary(i, paymentStore.LoadPaymentsForInvoice(i))) .ToList(); model.TotalDue = model.InvoiceSummaries.Sum(mis => mis.Due); model.TotalDueText = model.TotalDue.ToHtmlCurrency(); model.TotalCreditUsed = model.InvoiceSummaries.Sum(mis => mis.CreditUsed); model.TotalCreditUsedText = model.TotalCreditUsed.ToHtmlCurrency(); model.TotalPaid = model.InvoiceSummaries.Sum(mis => mis.Paid); model.TotalPaidText = model.TotalPaid.ToHtmlCurrency(); model.TotalCreditDue = model.InvoiceSummaries.Sum(mis => mis.CreditDue); model.TotalCreditDueText = model.TotalCreditDue.ToHtmlCurrency(); model.TotalDonated = model.InvoiceSummaries.Sum(mis => mis.Donated); model.TotalDonatedText = model.TotalDonated.ToHtmlCurrency(); model.TotalBalance = model.InvoiceSummaries.Sum(mis => mis.Balance); model.TotalBalanceText = model.TotalBalance.ToHtmlCurrency(); depositSummaryFactory.Clear(); IDictionary<long, IList<long>> invoicesForDeposits; invoicesForDeposits = depositStore.InvoicesForDeposits(month); foreach (long depositId in invoicesForDeposits.Keys) { Deposit deposit = depositStore.Load(depositId); IList<long> invoiceIds = invoicesForDeposits[depositId]; IDictionary<string, double> categoryTotals = invoiceStore.CategoryTotals(invoiceIds); depositSummaryFactory.AddDeposit(deposit, categoryTotals); } model.DepositHeaderHtml = depositSummaryFactory.BuildHeaderRow().ToList(); model.DepositRowsHtml = depositSummaryFactory.BuildDepositRows().ToList(); return View["Monthly", model]; }; } } public class DepositInvoiceData { public long DepositId { get; set; } public string DepositDateText { get; set; } public string DepositAmountText { get; set; } public IList<InvoiceData> InvoiceData { get; set; } public DepositInvoiceData() { InvoiceData = new List<InvoiceData>(); } } public class InvoiceData { public long InvoiceId { get; set; } public string FamilyName { get; set; } public string AmountDueText { get; set; } public string ClosedDateText { get; set; } public IList<PaymentData> PaymentData { get; set; } public IList<FeePayment> FeePayments { get; set; } public InvoiceData() { PaymentData = new List<PaymentData>(); } } public class PaymentData { public long PaymentId { get; set; } public string CheckNumber { get; set; } public string AmountText { get; set; } public string ReceivedDateText { get; set; } } public class FeePayment { public string FeeCategory { get; set; } public string TotalPaidText { get; set; } } public class MonthlyData { public string Month { get; set; } public IList<MonthlyInvoiceSummary> InvoiceSummaries { get; set; } public decimal TotalDue { get; set; } public decimal TotalCreditUsed { get; set; } public decimal TotalPaid { get; set; } public decimal TotalCreditDue { get; set; } public decimal TotalDonated { get; set; } public decimal TotalBalance { get; set; } public string TotalDueText { get; set; } public string TotalCreditUsedText { get; set; } public string TotalPaidText { get; set; } public string TotalCreditDueText { get; set; } public string TotalDonatedText { get; set; } public string TotalBalanceText { get; set; } public IList<string> DepositHeaderHtml { get; set; } public IList<string> DepositRowsHtml { get; set; } public MonthlyData() { InvoiceSummaries = new List<MonthlyInvoiceSummary>(); DepositHeaderHtml = new List<string>(); DepositRowsHtml = new List<string>(); } } public class MonthlyInvoiceSummary { public string FamilyName { get; set; } public decimal Due { get; set; } public decimal CreditUsed { get; set; } public decimal Paid { get; set; } public decimal CreditDue { get; set; } public decimal Donated { get; set; } public decimal Balance { get; set; } public string DueText { get; set; } public string CreditUsedText { get; set; } public string PaidText { get; set; } public string CreditDueText { get; set; } public string DonatedText { get; set; } public string BalanceText { get; set ; } public string CheckNumbers { get; set; } public string Closed { get; set; } public MonthlyInvoiceSummary(Invoice invoice, IEnumerable<Payment> payments) { FamilyName = invoice.FamilyName; Due = AmountDue(invoice); DueText = Due.ToHtmlCurrency(); CreditUsed = AmountCreditUsed(invoice); CreditUsedText = CreditUsed.ToHtmlCurrency(); Paid = -AmountPaid(invoice); PaidText = Paid.ToHtmlCurrency(); CreditDue = AmountCreditDue(invoice); CreditDueText = CreditDue.ToHtmlCurrency(); Donated = AmountDonated(invoice); DonatedText = Donated.ToHtmlCurrency(); Balance = invoice.BalanceDue(); BalanceText = Balance.ToHtmlCurrency(); var checkNumbers = new StringBuilder(); foreach (Payment payment in payments) { if (checkNumbers.Length > 0) checkNumbers.Append(','); checkNumbers.Append(payment.CheckNum); } CheckNumbers = checkNumbers.ToString(); if (invoice.Closed != null) Closed = invoice.Closed.Value.ToString("MM/dd"); } private decimal AmountDue(Invoice invoice) { decimal amount = 0; foreach (InvoiceLine line in invoice.Lines.Where(l => l.FeeCode != "Payment" && l.FeeCode != "CreditNext")) amount += line.Amount(); return amount; } private decimal AmountCreditUsed(Invoice invoice) { decimal amount = 0; foreach (InvoiceLine line in invoice.Lines.Where(l => l.FeeCode == "CreditPrev")) amount += line.Amount(); return amount; } private decimal AmountPaid(Invoice invoice) { decimal amount = 0; foreach (InvoiceLine line in invoice.Lines.Where(l => l.FeeCode == "Payment")) amount += line.Amount(); return amount; } private decimal AmountCreditDue(Invoice invoice) { decimal amount = 0; foreach (InvoiceLine line in invoice.Lines.Where(l => l.FeeCode == "CreditNext")) amount += line.Amount(); return amount; } private decimal AmountDonated(Invoice invoice) { decimal amount = 0; foreach (InvoiceLine line in invoice.Lines.Where(l => l.FeeCode == "Donation")) amount += line.Amount(); return amount; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Internal; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; namespace System.Reflection.Metadata { /// <summary> /// Reads metadata as defined byte the ECMA 335 CLI specification. /// </summary> public sealed partial class MetadataReader { private readonly MetadataReaderOptions _options; internal readonly MetadataStringDecoder utf8Decoder; internal readonly NamespaceCache namespaceCache; private Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>> _lazyNestedTypesMap; internal readonly MemoryBlock Block; // A row id of "mscorlib" AssemblyRef in a WinMD file (each WinMD file must have such a reference). internal readonly int WinMDMscorlibRef; #region Constructors /// <summary> /// Creates a metadata reader from the metadata stored at the given memory location. /// </summary> /// <remarks> /// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>. /// </remarks> public unsafe MetadataReader(byte* metadata, int length) : this(metadata, length, MetadataReaderOptions.Default, null) { } /// <summary> /// Creates a metadata reader from the metadata stored at the given memory location. /// </summary> /// <remarks> /// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>. /// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions)"/> to obtain /// metadata from a PE image. /// </remarks> public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options) : this(metadata, length, options, null) { } /// <summary> /// Creates a metadata reader from the metadata stored at the given memory location. /// </summary> /// <remarks> /// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>. /// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions, MetadataStringDecoder)"/> to obtain /// metadata from a PE image. /// </remarks> public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options, MetadataStringDecoder utf8Decoder) { if (length <= 0) { throw new ArgumentOutOfRangeException(nameof(length)); } if (metadata == null) { throw new ArgumentNullException(nameof(metadata)); } if (utf8Decoder == null) { utf8Decoder = MetadataStringDecoder.DefaultUTF8; } if (!(utf8Decoder.Encoding is UTF8Encoding)) { throw new ArgumentException(SR.MetadataStringDecoderEncodingMustBeUtf8, nameof(utf8Decoder)); } if (!BitConverter.IsLittleEndian) { throw new PlatformNotSupportedException(SR.LitteEndianArchitectureRequired); } this.Block = new MemoryBlock(metadata, length); _options = options; this.utf8Decoder = utf8Decoder; var headerReader = new BlobReader(this.Block); this.ReadMetadataHeader(ref headerReader, out _versionString); _metadataKind = GetMetadataKind(_versionString); var streamHeaders = this.ReadStreamHeaders(ref headerReader); // storage header and stream headers: MemoryBlock metadataTableStream; MemoryBlock standalonePdbStream; this.InitializeStreamReaders(ref this.Block, streamHeaders, out _metadataStreamKind, out metadataTableStream, out standalonePdbStream); int[] externalTableRowCountsOpt; if (standalonePdbStream.Length > 0) { ReadStandalonePortablePdbStream(standalonePdbStream, out _debugMetadataHeader, out externalTableRowCountsOpt); } else { externalTableRowCountsOpt = null; } var tableReader = new BlobReader(metadataTableStream); HeapSizes heapSizes; int[] metadataTableRowCounts; this.ReadMetadataTableHeader(ref tableReader, out heapSizes, out metadataTableRowCounts, out _sortedTables); this.InitializeTableReaders(tableReader.GetMemoryBlockAt(0, tableReader.RemainingBytes), heapSizes, metadataTableRowCounts, externalTableRowCountsOpt); // This previously could occur in obfuscated assemblies but a check was added to prevent // it getting to this point Debug.Assert(this.AssemblyTable.NumberOfRows <= 1); // Although the specification states that the module table will have exactly one row, // the native metadata reader would successfully read files containing more than one row. // Such files exist in the wild and may be produced by obfuscators. if (standalonePdbStream.Length == 0 && this.ModuleTable.NumberOfRows < 1) { throw new BadImageFormatException(SR.Format(SR.ModuleTableInvalidNumberOfRows, this.ModuleTable.NumberOfRows)); } // read this.namespaceCache = new NamespaceCache(this); if (_metadataKind != MetadataKind.Ecma335) { this.WinMDMscorlibRef = FindMscorlibAssemblyRefNoProjection(); } } #endregion #region Metadata Headers private readonly string _versionString; private readonly MetadataKind _metadataKind; private readonly MetadataStreamKind _metadataStreamKind; private readonly DebugMetadataHeader _debugMetadataHeader; internal StringStreamReader StringStream; internal BlobStreamReader BlobStream; internal GuidStreamReader GuidStream; internal UserStringStreamReader UserStringStream; /// <summary> /// True if the metadata stream has minimal delta format. Used for EnC. /// </summary> /// <remarks> /// The metadata stream has minimal delta format if "#JTD" stream is present. /// Minimal delta format uses large size (4B) when encoding table/heap references. /// The heaps in minimal delta only contain data of the delta, /// there is no padding at the beginning of the heaps that would align them /// with the original full metadata heaps. /// </remarks> internal bool IsMinimalDelta; /// <summary> /// Looks like this function reads beginning of the header described in /// Ecma-335 24.2.1 Metadata root /// </summary> private void ReadMetadataHeader(ref BlobReader memReader, out string versionString) { if (memReader.RemainingBytes < COR20Constants.MinimumSizeofMetadataHeader) { throw new BadImageFormatException(SR.MetadataHeaderTooSmall); } uint signature = memReader.ReadUInt32(); if (signature != COR20Constants.COR20MetadataSignature) { throw new BadImageFormatException(SR.MetadataSignature); } // major version memReader.ReadUInt16(); // minor version memReader.ReadUInt16(); // reserved: memReader.ReadUInt32(); int versionStringSize = memReader.ReadInt32(); if (memReader.RemainingBytes < versionStringSize) { throw new BadImageFormatException(SR.NotEnoughSpaceForVersionString); } int numberOfBytesRead; versionString = memReader.GetMemoryBlockAt(0, versionStringSize).PeekUtf8NullTerminated(0, null, utf8Decoder, out numberOfBytesRead, '\0'); memReader.SkipBytes(versionStringSize); } private MetadataKind GetMetadataKind(string versionString) { // Treat metadata as CLI raw metadata if the client doesn't want to see projections. if ((_options & MetadataReaderOptions.ApplyWindowsRuntimeProjections) == 0) { return MetadataKind.Ecma335; } if (!versionString.Contains("WindowsRuntime")) { return MetadataKind.Ecma335; } else if (versionString.Contains("CLR")) { return MetadataKind.ManagedWindowsMetadata; } else { return MetadataKind.WindowsMetadata; } } /// <summary> /// Reads stream headers described in Ecma-335 24.2.2 Stream header /// </summary> private StreamHeader[] ReadStreamHeaders(ref BlobReader memReader) { // storage header: memReader.ReadUInt16(); int streamCount = memReader.ReadInt16(); var streamHeaders = new StreamHeader[streamCount]; for (int i = 0; i < streamHeaders.Length; i++) { if (memReader.RemainingBytes < COR20Constants.MinimumSizeofStreamHeader) { throw new BadImageFormatException(SR.StreamHeaderTooSmall); } streamHeaders[i].Offset = memReader.ReadUInt32(); streamHeaders[i].Size = memReader.ReadInt32(); streamHeaders[i].Name = memReader.ReadUtf8NullTerminated(); bool aligned = memReader.TryAlign(4); if (!aligned || memReader.RemainingBytes == 0) { throw new BadImageFormatException(SR.NotEnoughSpaceForStreamHeaderName); } } return streamHeaders; } private void InitializeStreamReaders( ref MemoryBlock metadataRoot, StreamHeader[] streamHeaders, out MetadataStreamKind metadataStreamKind, out MemoryBlock metadataTableStream, out MemoryBlock standalonePdbStream) { metadataTableStream = default(MemoryBlock); standalonePdbStream = default(MemoryBlock); metadataStreamKind = MetadataStreamKind.Illegal; foreach (StreamHeader streamHeader in streamHeaders) { switch (streamHeader.Name) { case COR20Constants.StringStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForStringStream); } this.StringStream = new StringStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), _metadataKind); break; case COR20Constants.BlobStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForBlobStream); } this.BlobStream = new BlobStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), _metadataKind); break; case COR20Constants.GUIDStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForGUIDStream); } this.GuidStream = new GuidStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size)); break; case COR20Constants.UserStringStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForBlobStream); } this.UserStringStream = new UserStringStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size)); break; case COR20Constants.CompressedMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } metadataStreamKind = MetadataStreamKind.Compressed; metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); break; case COR20Constants.UncompressedMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } metadataStreamKind = MetadataStreamKind.Uncompressed; metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); break; case COR20Constants.MinimalDeltaMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } // the content of the stream is ignored this.IsMinimalDelta = true; break; case COR20Constants.StandalonePdbStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } standalonePdbStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); break; default: // Skip unknown streams. Some obfuscators insert invalid streams. continue; } } if (IsMinimalDelta && metadataStreamKind != MetadataStreamKind.Uncompressed) { throw new BadImageFormatException(SR.InvalidMetadataStreamFormat); } } #endregion #region Tables and Heaps private readonly TableMask _sortedTables; /// <summary> /// A row count for each possible table. May be indexed by <see cref="TableIndex"/>. /// </summary> internal int[] TableRowCounts; internal ModuleTableReader ModuleTable; internal TypeRefTableReader TypeRefTable; internal TypeDefTableReader TypeDefTable; internal FieldPtrTableReader FieldPtrTable; internal FieldTableReader FieldTable; internal MethodPtrTableReader MethodPtrTable; internal MethodTableReader MethodDefTable; internal ParamPtrTableReader ParamPtrTable; internal ParamTableReader ParamTable; internal InterfaceImplTableReader InterfaceImplTable; internal MemberRefTableReader MemberRefTable; internal ConstantTableReader ConstantTable; internal CustomAttributeTableReader CustomAttributeTable; internal FieldMarshalTableReader FieldMarshalTable; internal DeclSecurityTableReader DeclSecurityTable; internal ClassLayoutTableReader ClassLayoutTable; internal FieldLayoutTableReader FieldLayoutTable; internal StandAloneSigTableReader StandAloneSigTable; internal EventMapTableReader EventMapTable; internal EventPtrTableReader EventPtrTable; internal EventTableReader EventTable; internal PropertyMapTableReader PropertyMapTable; internal PropertyPtrTableReader PropertyPtrTable; internal PropertyTableReader PropertyTable; internal MethodSemanticsTableReader MethodSemanticsTable; internal MethodImplTableReader MethodImplTable; internal ModuleRefTableReader ModuleRefTable; internal TypeSpecTableReader TypeSpecTable; internal ImplMapTableReader ImplMapTable; internal FieldRVATableReader FieldRvaTable; internal EnCLogTableReader EncLogTable; internal EnCMapTableReader EncMapTable; internal AssemblyTableReader AssemblyTable; internal AssemblyProcessorTableReader AssemblyProcessorTable; // unused internal AssemblyOSTableReader AssemblyOSTable; // unused internal AssemblyRefTableReader AssemblyRefTable; internal AssemblyRefProcessorTableReader AssemblyRefProcessorTable; // unused internal AssemblyRefOSTableReader AssemblyRefOSTable; // unused internal FileTableReader FileTable; internal ExportedTypeTableReader ExportedTypeTable; internal ManifestResourceTableReader ManifestResourceTable; internal NestedClassTableReader NestedClassTable; internal GenericParamTableReader GenericParamTable; internal MethodSpecTableReader MethodSpecTable; internal GenericParamConstraintTableReader GenericParamConstraintTable; // debug tables internal DocumentTableReader DocumentTable; internal MethodDebugInformationTableReader MethodDebugInformationTable; internal LocalScopeTableReader LocalScopeTable; internal LocalVariableTableReader LocalVariableTable; internal LocalConstantTableReader LocalConstantTable; internal ImportScopeTableReader ImportScopeTable; internal StateMachineMethodTableReader StateMachineMethodTable; internal CustomDebugInformationTableReader CustomDebugInformationTable; private void ReadMetadataTableHeader(ref BlobReader reader, out HeapSizes heapSizes, out int[] metadataTableRowCounts, out TableMask sortedTables) { if (reader.RemainingBytes < MetadataStreamConstants.SizeOfMetadataTableHeader) { throw new BadImageFormatException(SR.MetadataTableHeaderTooSmall); } // reserved (shall be ignored): reader.ReadUInt32(); // major version (shall be ignored): reader.ReadByte(); // minor version (shall be ignored): reader.ReadByte(); // heap sizes: heapSizes = (HeapSizes)reader.ReadByte(); // reserved (shall be ignored): reader.ReadByte(); ulong presentTables = reader.ReadUInt64(); sortedTables = (TableMask)reader.ReadUInt64(); // According to ECMA-335, MajorVersion and MinorVersion have fixed values and, // based on recommendation in 24.1 Fixed fields: When writing these fields it // is best that they be set to the value indicated, on reading they should be ignored. // We will not be checking version values. We will continue checking that the set of // present tables is within the set we understand. ulong validTables = (ulong)TableMask.V3_0_TablesMask; if ((presentTables & ~validTables) != 0) { throw new BadImageFormatException(SR.Format(SR.UnknownTables, presentTables)); } if (_metadataStreamKind == MetadataStreamKind.Compressed) { // In general Ptr tables and EnC tables are not allowed in a compressed stream. // However when asked for a snapshot of the current metadata after an EnC change has been applied // the CLR includes the EnCLog table into the snapshot. We need to be able to read the image, // so we'll allow the table here but pretend it's empty later. if ((presentTables & (ulong)(TableMask.PtrTables | TableMask.EnCMap)) != 0) { throw new BadImageFormatException(SR.IllegalTablesInCompressedMetadataStream); } } metadataTableRowCounts = ReadMetadataTableRowCounts(ref reader, presentTables); if ((heapSizes & HeapSizes.ExtraData) == HeapSizes.ExtraData) { // Skip "extra data" used by some obfuscators. Although it is not mentioned in the CLI spec, // it is honored by the native metadata reader. reader.ReadUInt32(); } } private static int[] ReadMetadataTableRowCounts(ref BlobReader memReader, ulong presentTableMask) { ulong currentTableBit = 1; var rowCounts = new int[TableIndexExtensions.Count]; for (int i = 0; i < rowCounts.Length; i++) { if ((presentTableMask & currentTableBit) != 0) { if (memReader.RemainingBytes < sizeof(uint)) { throw new BadImageFormatException(SR.TableRowCountSpaceTooSmall); } uint rowCount = memReader.ReadUInt32(); if (rowCount > TokenTypeIds.RIDMask) { throw new BadImageFormatException(SR.Format(SR.InvalidRowCount, rowCount)); } rowCounts[i] = (int)rowCount; } currentTableBit <<= 1; } return rowCounts; } // internal for testing internal static void ReadStandalonePortablePdbStream(MemoryBlock block, out DebugMetadataHeader debugMetadataHeader, out int[] externalTableRowCounts) { var reader = new BlobReader(block); const int PdbIdSize = 20; byte[] pdbId = reader.ReadBytes(PdbIdSize); // ECMA-335 15.4.1.2: // The entry point to an application shall be static. // This entry point method can be a global method or it can appear inside a type. // The entry point method shall either accept no arguments or a vector of strings. // The return type of the entry point method shall be void, int32, or unsigned int32. // The entry point method cannot be defined in a generic class. uint entryPointToken = reader.ReadUInt32(); int entryPointRowId = (int)(entryPointToken & TokenTypeIds.RIDMask); if (entryPointToken != 0 && ((entryPointToken & TokenTypeIds.TypeMask) != TokenTypeIds.MethodDef || entryPointRowId == 0)) { throw new BadImageFormatException(string.Format(SR.InvalidEntryPointToken, entryPointToken)); } ulong externalTableMask = reader.ReadUInt64(); // EnC & Ptr tables can't be referenced from standalone PDB metadata: const ulong validTables = (ulong)(TableMask.V2_0_TablesMask & ~TableMask.PtrTables & ~TableMask.EnCLog & ~TableMask.EnCMap); if ((externalTableMask & ~validTables) != 0) { throw new BadImageFormatException(string.Format(SR.UnknownTables, (TableMask)externalTableMask)); } externalTableRowCounts = ReadMetadataTableRowCounts(ref reader, externalTableMask); debugMetadataHeader = new DebugMetadataHeader( ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref pdbId), MethodDefinitionHandle.FromRowId(entryPointRowId)); } private const int SmallIndexSize = 2; private const int LargeIndexSize = 4; private int GetReferenceSize(int[] rowCounts, TableIndex index) { return (rowCounts[(int)index] < MetadataStreamConstants.LargeTableRowCount && !IsMinimalDelta) ? SmallIndexSize : LargeIndexSize; } private void InitializeTableReaders(MemoryBlock metadataTablesMemoryBlock, HeapSizes heapSizes, int[] rowCounts, int[] externalRowCountsOpt) { // Size of reference tags in each table. this.TableRowCounts = rowCounts; // TODO (https://github.com/dotnet/corefx/issues/2061): // Shouldn't XxxPtr table be always the same size or smaller than the corresponding Xxx table? // Compute ref sizes for tables that can have pointer tables int fieldRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.FieldPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Field); int methodRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.MethodPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.MethodDef); int paramRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.ParamPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Param); int eventRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.EventPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Event); int propertyRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.PropertyPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Property); // Compute the coded token ref sizes int typeDefOrRefRefSize = ComputeCodedTokenSize(TypeDefOrRefTag.LargeRowSize, rowCounts, TypeDefOrRefTag.TablesReferenced); int hasConstantRefSize = ComputeCodedTokenSize(HasConstantTag.LargeRowSize, rowCounts, HasConstantTag.TablesReferenced); int hasCustomAttributeRefSize = ComputeCodedTokenSize(HasCustomAttributeTag.LargeRowSize, rowCounts, HasCustomAttributeTag.TablesReferenced); int hasFieldMarshalRefSize = ComputeCodedTokenSize(HasFieldMarshalTag.LargeRowSize, rowCounts, HasFieldMarshalTag.TablesReferenced); int hasDeclSecurityRefSize = ComputeCodedTokenSize(HasDeclSecurityTag.LargeRowSize, rowCounts, HasDeclSecurityTag.TablesReferenced); int memberRefParentRefSize = ComputeCodedTokenSize(MemberRefParentTag.LargeRowSize, rowCounts, MemberRefParentTag.TablesReferenced); int hasSemanticsRefSize = ComputeCodedTokenSize(HasSemanticsTag.LargeRowSize, rowCounts, HasSemanticsTag.TablesReferenced); int methodDefOrRefRefSize = ComputeCodedTokenSize(MethodDefOrRefTag.LargeRowSize, rowCounts, MethodDefOrRefTag.TablesReferenced); int memberForwardedRefSize = ComputeCodedTokenSize(MemberForwardedTag.LargeRowSize, rowCounts, MemberForwardedTag.TablesReferenced); int implementationRefSize = ComputeCodedTokenSize(ImplementationTag.LargeRowSize, rowCounts, ImplementationTag.TablesReferenced); int customAttributeTypeRefSize = ComputeCodedTokenSize(CustomAttributeTypeTag.LargeRowSize, rowCounts, CustomAttributeTypeTag.TablesReferenced); int resolutionScopeRefSize = ComputeCodedTokenSize(ResolutionScopeTag.LargeRowSize, rowCounts, ResolutionScopeTag.TablesReferenced); int typeOrMethodDefRefSize = ComputeCodedTokenSize(TypeOrMethodDefTag.LargeRowSize, rowCounts, TypeOrMethodDefTag.TablesReferenced); // Compute HeapRef Sizes int stringHeapRefSize = (heapSizes & HeapSizes.StringHeapLarge) == HeapSizes.StringHeapLarge ? LargeIndexSize : SmallIndexSize; int guidHeapRefSize = (heapSizes & HeapSizes.GuidHeapLarge) == HeapSizes.GuidHeapLarge ? LargeIndexSize : SmallIndexSize; int blobHeapRefSize = (heapSizes & HeapSizes.BlobHeapLarge) == HeapSizes.BlobHeapLarge ? LargeIndexSize : SmallIndexSize; // Populate the Table blocks int totalRequiredSize = 0; this.ModuleTable = new ModuleTableReader(rowCounts[(int)TableIndex.Module], stringHeapRefSize, guidHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ModuleTable.Block.Length; this.TypeRefTable = new TypeRefTableReader(rowCounts[(int)TableIndex.TypeRef], resolutionScopeRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.TypeRefTable.Block.Length; this.TypeDefTable = new TypeDefTableReader(rowCounts[(int)TableIndex.TypeDef], fieldRefSizeSorted, methodRefSizeSorted, typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.TypeDefTable.Block.Length; this.FieldPtrTable = new FieldPtrTableReader(rowCounts[(int)TableIndex.FieldPtr], GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldPtrTable.Block.Length; this.FieldTable = new FieldTableReader(rowCounts[(int)TableIndex.Field], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldTable.Block.Length; this.MethodPtrTable = new MethodPtrTableReader(rowCounts[(int)TableIndex.MethodPtr], GetReferenceSize(rowCounts, TableIndex.MethodDef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodPtrTable.Block.Length; this.MethodDefTable = new MethodTableReader(rowCounts[(int)TableIndex.MethodDef], paramRefSizeSorted, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodDefTable.Block.Length; this.ParamPtrTable = new ParamPtrTableReader(rowCounts[(int)TableIndex.ParamPtr], GetReferenceSize(rowCounts, TableIndex.Param), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ParamPtrTable.Block.Length; this.ParamTable = new ParamTableReader(rowCounts[(int)TableIndex.Param], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ParamTable.Block.Length; this.InterfaceImplTable = new InterfaceImplTableReader(rowCounts[(int)TableIndex.InterfaceImpl], IsDeclaredSorted(TableMask.InterfaceImpl), GetReferenceSize(rowCounts, TableIndex.TypeDef), typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.InterfaceImplTable.Block.Length; this.MemberRefTable = new MemberRefTableReader(rowCounts[(int)TableIndex.MemberRef], memberRefParentRefSize, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MemberRefTable.Block.Length; this.ConstantTable = new ConstantTableReader(rowCounts[(int)TableIndex.Constant], IsDeclaredSorted(TableMask.Constant), hasConstantRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ConstantTable.Block.Length; this.CustomAttributeTable = new CustomAttributeTableReader(rowCounts[(int)TableIndex.CustomAttribute], IsDeclaredSorted(TableMask.CustomAttribute), hasCustomAttributeRefSize, customAttributeTypeRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.CustomAttributeTable.Block.Length; this.FieldMarshalTable = new FieldMarshalTableReader(rowCounts[(int)TableIndex.FieldMarshal], IsDeclaredSorted(TableMask.FieldMarshal), hasFieldMarshalRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldMarshalTable.Block.Length; this.DeclSecurityTable = new DeclSecurityTableReader(rowCounts[(int)TableIndex.DeclSecurity], IsDeclaredSorted(TableMask.DeclSecurity), hasDeclSecurityRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.DeclSecurityTable.Block.Length; this.ClassLayoutTable = new ClassLayoutTableReader(rowCounts[(int)TableIndex.ClassLayout], IsDeclaredSorted(TableMask.ClassLayout), GetReferenceSize(rowCounts, TableIndex.TypeDef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ClassLayoutTable.Block.Length; this.FieldLayoutTable = new FieldLayoutTableReader(rowCounts[(int)TableIndex.FieldLayout], IsDeclaredSorted(TableMask.FieldLayout), GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldLayoutTable.Block.Length; this.StandAloneSigTable = new StandAloneSigTableReader(rowCounts[(int)TableIndex.StandAloneSig], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.StandAloneSigTable.Block.Length; this.EventMapTable = new EventMapTableReader(rowCounts[(int)TableIndex.EventMap], GetReferenceSize(rowCounts, TableIndex.TypeDef), eventRefSizeSorted, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EventMapTable.Block.Length; this.EventPtrTable = new EventPtrTableReader(rowCounts[(int)TableIndex.EventPtr], GetReferenceSize(rowCounts, TableIndex.Event), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EventPtrTable.Block.Length; this.EventTable = new EventTableReader(rowCounts[(int)TableIndex.Event], typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EventTable.Block.Length; this.PropertyMapTable = new PropertyMapTableReader(rowCounts[(int)TableIndex.PropertyMap], GetReferenceSize(rowCounts, TableIndex.TypeDef), propertyRefSizeSorted, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.PropertyMapTable.Block.Length; this.PropertyPtrTable = new PropertyPtrTableReader(rowCounts[(int)TableIndex.PropertyPtr], GetReferenceSize(rowCounts, TableIndex.Property), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.PropertyPtrTable.Block.Length; this.PropertyTable = new PropertyTableReader(rowCounts[(int)TableIndex.Property], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.PropertyTable.Block.Length; this.MethodSemanticsTable = new MethodSemanticsTableReader(rowCounts[(int)TableIndex.MethodSemantics], IsDeclaredSorted(TableMask.MethodSemantics), GetReferenceSize(rowCounts, TableIndex.MethodDef), hasSemanticsRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodSemanticsTable.Block.Length; this.MethodImplTable = new MethodImplTableReader(rowCounts[(int)TableIndex.MethodImpl], IsDeclaredSorted(TableMask.MethodImpl), GetReferenceSize(rowCounts, TableIndex.TypeDef), methodDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodImplTable.Block.Length; this.ModuleRefTable = new ModuleRefTableReader(rowCounts[(int)TableIndex.ModuleRef], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ModuleRefTable.Block.Length; this.TypeSpecTable = new TypeSpecTableReader(rowCounts[(int)TableIndex.TypeSpec], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.TypeSpecTable.Block.Length; this.ImplMapTable = new ImplMapTableReader(rowCounts[(int)TableIndex.ImplMap], IsDeclaredSorted(TableMask.ImplMap), GetReferenceSize(rowCounts, TableIndex.ModuleRef), memberForwardedRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ImplMapTable.Block.Length; this.FieldRvaTable = new FieldRVATableReader(rowCounts[(int)TableIndex.FieldRva], IsDeclaredSorted(TableMask.FieldRva), GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldRvaTable.Block.Length; this.EncLogTable = new EnCLogTableReader(rowCounts[(int)TableIndex.EncLog], metadataTablesMemoryBlock, totalRequiredSize, _metadataStreamKind); totalRequiredSize += this.EncLogTable.Block.Length; this.EncMapTable = new EnCMapTableReader(rowCounts[(int)TableIndex.EncMap], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EncMapTable.Block.Length; this.AssemblyTable = new AssemblyTableReader(rowCounts[(int)TableIndex.Assembly], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyTable.Block.Length; this.AssemblyProcessorTable = new AssemblyProcessorTableReader(rowCounts[(int)TableIndex.AssemblyProcessor], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyProcessorTable.Block.Length; this.AssemblyOSTable = new AssemblyOSTableReader(rowCounts[(int)TableIndex.AssemblyOS], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyOSTable.Block.Length; this.AssemblyRefTable = new AssemblyRefTableReader(rowCounts[(int)TableIndex.AssemblyRef], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize, _metadataKind); totalRequiredSize += this.AssemblyRefTable.Block.Length; this.AssemblyRefProcessorTable = new AssemblyRefProcessorTableReader(rowCounts[(int)TableIndex.AssemblyRefProcessor], GetReferenceSize(rowCounts, TableIndex.AssemblyRef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyRefProcessorTable.Block.Length; this.AssemblyRefOSTable = new AssemblyRefOSTableReader(rowCounts[(int)TableIndex.AssemblyRefOS], GetReferenceSize(rowCounts, TableIndex.AssemblyRef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyRefOSTable.Block.Length; this.FileTable = new FileTableReader(rowCounts[(int)TableIndex.File], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FileTable.Block.Length; this.ExportedTypeTable = new ExportedTypeTableReader(rowCounts[(int)TableIndex.ExportedType], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ExportedTypeTable.Block.Length; this.ManifestResourceTable = new ManifestResourceTableReader(rowCounts[(int)TableIndex.ManifestResource], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ManifestResourceTable.Block.Length; this.NestedClassTable = new NestedClassTableReader(rowCounts[(int)TableIndex.NestedClass], IsDeclaredSorted(TableMask.NestedClass), GetReferenceSize(rowCounts, TableIndex.TypeDef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.NestedClassTable.Block.Length; this.GenericParamTable = new GenericParamTableReader(rowCounts[(int)TableIndex.GenericParam], IsDeclaredSorted(TableMask.GenericParam), typeOrMethodDefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.GenericParamTable.Block.Length; this.MethodSpecTable = new MethodSpecTableReader(rowCounts[(int)TableIndex.MethodSpec], methodDefOrRefRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodSpecTable.Block.Length; this.GenericParamConstraintTable = new GenericParamConstraintTableReader(rowCounts[(int)TableIndex.GenericParamConstraint], IsDeclaredSorted(TableMask.GenericParamConstraint), GetReferenceSize(rowCounts, TableIndex.GenericParam), typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.GenericParamConstraintTable.Block.Length; // debug tables: // Type-system metadata tables may be stored in a separate (external) metadata file. // We need to use the row counts of the external tables when referencing them. var combinedRowCounts = (externalRowCountsOpt != null) ? CombineRowCounts(rowCounts, externalRowCountsOpt, TableIndex.Document) : rowCounts; int methodRefSizeCombined = GetReferenceSize(combinedRowCounts, TableIndex.MethodDef); int hasCustomDebugInformationRefSizeCombined = ComputeCodedTokenSize(HasCustomDebugInformationTag.LargeRowSize, combinedRowCounts, HasCustomDebugInformationTag.TablesReferenced); this.DocumentTable = new DocumentTableReader(rowCounts[(int)TableIndex.Document], guidHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.DocumentTable.Block.Length; this.MethodDebugInformationTable = new MethodDebugInformationTableReader(rowCounts[(int)TableIndex.MethodDebugInformation], GetReferenceSize(rowCounts, TableIndex.Document), blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodDebugInformationTable.Block.Length; this.LocalScopeTable = new LocalScopeTableReader(rowCounts[(int)TableIndex.LocalScope], IsDeclaredSorted(TableMask.LocalScope), methodRefSizeCombined, GetReferenceSize(rowCounts, TableIndex.ImportScope), GetReferenceSize(rowCounts, TableIndex.LocalVariable), GetReferenceSize(rowCounts, TableIndex.LocalConstant), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.LocalScopeTable.Block.Length; this.LocalVariableTable = new LocalVariableTableReader(rowCounts[(int)TableIndex.LocalVariable], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.LocalVariableTable.Block.Length; this.LocalConstantTable = new LocalConstantTableReader(rowCounts[(int)TableIndex.LocalConstant], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.LocalConstantTable.Block.Length; this.ImportScopeTable = new ImportScopeTableReader(rowCounts[(int)TableIndex.ImportScope], GetReferenceSize(rowCounts, TableIndex.ImportScope), blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ImportScopeTable.Block.Length; this.StateMachineMethodTable = new StateMachineMethodTableReader(rowCounts[(int)TableIndex.StateMachineMethod], IsDeclaredSorted(TableMask.StateMachineMethod), methodRefSizeCombined, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.StateMachineMethodTable.Block.Length; this.CustomDebugInformationTable = new CustomDebugInformationTableReader(rowCounts[(int)TableIndex.CustomDebugInformation], IsDeclaredSorted(TableMask.CustomDebugInformation), hasCustomDebugInformationRefSizeCombined, guidHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.CustomDebugInformationTable.Block.Length; if (totalRequiredSize > metadataTablesMemoryBlock.Length) { throw new BadImageFormatException(SR.MetadataTablesTooSmall); } } private static int[] CombineRowCounts(int[] local, int[] external, TableIndex firstExternalTableIndex) { Debug.Assert(local.Length == external.Length); var rowCounts = new int[local.Length]; for (int i = 0; i < (int)firstExternalTableIndex; i++) { rowCounts[i] = local[i]; } for (int i = (int)firstExternalTableIndex; i < rowCounts.Length; i++) { rowCounts[i] = external[i]; } return rowCounts; } private int ComputeCodedTokenSize(int largeRowSize, int[] rowCounts, TableMask tablesReferenced) { if (IsMinimalDelta) { return LargeIndexSize; } bool isAllReferencedTablesSmall = true; ulong tablesReferencedMask = (ulong)tablesReferenced; for (int tableIndex = 0; tableIndex < TableIndexExtensions.Count; tableIndex++) { if ((tablesReferencedMask & 1) != 0) { isAllReferencedTablesSmall = isAllReferencedTablesSmall && (rowCounts[tableIndex] < largeRowSize); } tablesReferencedMask >>= 1; } return isAllReferencedTablesSmall ? SmallIndexSize : LargeIndexSize; } private bool IsDeclaredSorted(TableMask index) { return (_sortedTables & index) != 0; } #endregion #region Helpers // internal for testing internal NamespaceCache NamespaceCache { get { return namespaceCache; } } internal bool UseFieldPtrTable { get { return this.FieldPtrTable.NumberOfRows > 0; } } internal bool UseMethodPtrTable { get { return this.MethodPtrTable.NumberOfRows > 0; } } internal bool UseParamPtrTable { get { return this.ParamPtrTable.NumberOfRows > 0; } } internal bool UseEventPtrTable { get { return this.EventPtrTable.NumberOfRows > 0; } } internal bool UsePropertyPtrTable { get { return this.PropertyPtrTable.NumberOfRows > 0; } } internal void GetFieldRange(TypeDefinitionHandle typeDef, out int firstFieldRowId, out int lastFieldRowId) { int typeDefRowId = typeDef.RowId; firstFieldRowId = this.TypeDefTable.GetFieldStart(typeDefRowId); if (firstFieldRowId == 0) { firstFieldRowId = 1; lastFieldRowId = 0; } else if (typeDefRowId == this.TypeDefTable.NumberOfRows) { lastFieldRowId = (this.UseFieldPtrTable) ? this.FieldPtrTable.NumberOfRows : this.FieldTable.NumberOfRows; } else { lastFieldRowId = this.TypeDefTable.GetFieldStart(typeDefRowId + 1) - 1; } } internal void GetMethodRange(TypeDefinitionHandle typeDef, out int firstMethodRowId, out int lastMethodRowId) { int typeDefRowId = typeDef.RowId; firstMethodRowId = this.TypeDefTable.GetMethodStart(typeDefRowId); if (firstMethodRowId == 0) { firstMethodRowId = 1; lastMethodRowId = 0; } else if (typeDefRowId == this.TypeDefTable.NumberOfRows) { lastMethodRowId = (this.UseMethodPtrTable) ? this.MethodPtrTable.NumberOfRows : this.MethodDefTable.NumberOfRows; } else { lastMethodRowId = this.TypeDefTable.GetMethodStart(typeDefRowId + 1) - 1; } } internal void GetEventRange(TypeDefinitionHandle typeDef, out int firstEventRowId, out int lastEventRowId) { int eventMapRowId = this.EventMapTable.FindEventMapRowIdFor(typeDef); if (eventMapRowId == 0) { firstEventRowId = 1; lastEventRowId = 0; return; } firstEventRowId = this.EventMapTable.GetEventListStartFor(eventMapRowId); if (eventMapRowId == this.EventMapTable.NumberOfRows) { lastEventRowId = this.UseEventPtrTable ? this.EventPtrTable.NumberOfRows : this.EventTable.NumberOfRows; } else { lastEventRowId = this.EventMapTable.GetEventListStartFor(eventMapRowId + 1) - 1; } } internal void GetPropertyRange(TypeDefinitionHandle typeDef, out int firstPropertyRowId, out int lastPropertyRowId) { int propertyMapRowId = this.PropertyMapTable.FindPropertyMapRowIdFor(typeDef); if (propertyMapRowId == 0) { firstPropertyRowId = 1; lastPropertyRowId = 0; return; } firstPropertyRowId = this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId); if (propertyMapRowId == this.PropertyMapTable.NumberOfRows) { lastPropertyRowId = (this.UsePropertyPtrTable) ? this.PropertyPtrTable.NumberOfRows : this.PropertyTable.NumberOfRows; } else { lastPropertyRowId = this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId + 1) - 1; } } internal void GetParameterRange(MethodDefinitionHandle methodDef, out int firstParamRowId, out int lastParamRowId) { int rid = methodDef.RowId; firstParamRowId = this.MethodDefTable.GetParamStart(rid); if (firstParamRowId == 0) { firstParamRowId = 1; lastParamRowId = 0; } else if (rid == this.MethodDefTable.NumberOfRows) { lastParamRowId = (this.UseParamPtrTable ? this.ParamPtrTable.NumberOfRows : this.ParamTable.NumberOfRows); } else { lastParamRowId = this.MethodDefTable.GetParamStart(rid + 1) - 1; } } internal void GetLocalVariableRange(LocalScopeHandle scope, out int firstVariableRowId, out int lastVariableRowId) { int scopeRowId = scope.RowId; firstVariableRowId = this.LocalScopeTable.GetVariableStart(scopeRowId); if (firstVariableRowId == 0) { firstVariableRowId = 1; lastVariableRowId = 0; } else if (scopeRowId == this.LocalScopeTable.NumberOfRows) { lastVariableRowId = this.LocalVariableTable.NumberOfRows; } else { lastVariableRowId = this.LocalScopeTable.GetVariableStart(scopeRowId + 1) - 1; } } internal void GetLocalConstantRange(LocalScopeHandle scope, out int firstConstantRowId, out int lastConstantRowId) { int scopeRowId = scope.RowId; firstConstantRowId = this.LocalScopeTable.GetConstantStart(scopeRowId); if (firstConstantRowId == 0) { firstConstantRowId = 1; lastConstantRowId = 0; } else if (scopeRowId == this.LocalScopeTable.NumberOfRows) { lastConstantRowId = this.LocalConstantTable.NumberOfRows; } else { lastConstantRowId = this.LocalScopeTable.GetConstantStart(scopeRowId + 1) - 1; } } #endregion #region Public APIs public MetadataReaderOptions Options { get { return _options; } } public string MetadataVersion { get { return _versionString; } } /// <summary> /// Information decoded from #Pdb stream, or null if the stream is not present. /// </summary> public DebugMetadataHeader DebugMetadataHeader { get { return _debugMetadataHeader; } } public MetadataKind MetadataKind { get { return _metadataKind; } } public MetadataStringComparer StringComparer { get { return new MetadataStringComparer(this); } } public bool IsAssembly { get { return this.AssemblyTable.NumberOfRows == 1; } } public AssemblyReferenceHandleCollection AssemblyReferences { get { return new AssemblyReferenceHandleCollection(this); } } public TypeDefinitionHandleCollection TypeDefinitions { get { return new TypeDefinitionHandleCollection(TypeDefTable.NumberOfRows); } } public TypeReferenceHandleCollection TypeReferences { get { return new TypeReferenceHandleCollection(TypeRefTable.NumberOfRows); } } public CustomAttributeHandleCollection CustomAttributes { get { return new CustomAttributeHandleCollection(this); } } public DeclarativeSecurityAttributeHandleCollection DeclarativeSecurityAttributes { get { return new DeclarativeSecurityAttributeHandleCollection(this); } } public MemberReferenceHandleCollection MemberReferences { get { return new MemberReferenceHandleCollection(MemberRefTable.NumberOfRows); } } public ManifestResourceHandleCollection ManifestResources { get { return new ManifestResourceHandleCollection(ManifestResourceTable.NumberOfRows); } } public AssemblyFileHandleCollection AssemblyFiles { get { return new AssemblyFileHandleCollection(FileTable.NumberOfRows); } } public ExportedTypeHandleCollection ExportedTypes { get { return new ExportedTypeHandleCollection(ExportedTypeTable.NumberOfRows); } } public MethodDefinitionHandleCollection MethodDefinitions { get { return new MethodDefinitionHandleCollection(this); } } public FieldDefinitionHandleCollection FieldDefinitions { get { return new FieldDefinitionHandleCollection(this); } } public EventDefinitionHandleCollection EventDefinitions { get { return new EventDefinitionHandleCollection(this); } } public PropertyDefinitionHandleCollection PropertyDefinitions { get { return new PropertyDefinitionHandleCollection(this); } } public DocumentHandleCollection Documents { get { return new DocumentHandleCollection(this); } } public MethodDebugInformationHandleCollection MethodDebugInformation { get { return new MethodDebugInformationHandleCollection(this); } } public LocalScopeHandleCollection LocalScopes { get { return new LocalScopeHandleCollection(this, 0); } } public LocalVariableHandleCollection LocalVariables { get { return new LocalVariableHandleCollection(this, default(LocalScopeHandle)); } } public LocalConstantHandleCollection LocalConstants { get { return new LocalConstantHandleCollection(this, default(LocalScopeHandle)); } } public ImportScopeCollection ImportScopes { get { return new ImportScopeCollection(this); } } public CustomDebugInformationHandleCollection CustomDebugInformation { get { return new CustomDebugInformationHandleCollection(this); } } public AssemblyDefinition GetAssemblyDefinition() { if (!IsAssembly) { throw new InvalidOperationException(SR.MetadataImageDoesNotRepresentAnAssembly); } return new AssemblyDefinition(this); } public string GetString(StringHandle handle) { return StringStream.GetString(handle, utf8Decoder); } public string GetString(NamespaceDefinitionHandle handle) { if (handle.HasFullName) { return StringStream.GetString(handle.GetFullName(), utf8Decoder); } return namespaceCache.GetFullName(handle); } public byte[] GetBlobBytes(BlobHandle handle) { return BlobStream.GetBytes(handle); } public ImmutableArray<byte> GetBlobContent(BlobHandle handle) { // TODO: We can skip a copy for virtual blobs. byte[] bytes = GetBlobBytes(handle); return ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref bytes); } public BlobReader GetBlobReader(BlobHandle handle) { return BlobStream.GetBlobReader(handle); } public string GetUserString(UserStringHandle handle) { return UserStringStream.GetString(handle); } public Guid GetGuid(GuidHandle handle) { return GuidStream.GetGuid(handle); } public ModuleDefinition GetModuleDefinition() { if (_debugMetadataHeader != null) { throw new InvalidOperationException(SR.StandaloneDebugMetadataImageDoesNotContainModuleTable); } return new ModuleDefinition(this); } public AssemblyReference GetAssemblyReference(AssemblyReferenceHandle handle) { return new AssemblyReference(this, handle.Value); } public TypeDefinition GetTypeDefinition(TypeDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new TypeDefinition(this, GetTypeDefTreatmentAndRowId(handle)); } public NamespaceDefinition GetNamespaceDefinitionRoot() { NamespaceData data = namespaceCache.GetRootNamespace(); return new NamespaceDefinition(data); } public NamespaceDefinition GetNamespaceDefinition(NamespaceDefinitionHandle handle) { NamespaceData data = namespaceCache.GetNamespaceData(handle); return new NamespaceDefinition(data); } private uint GetTypeDefTreatmentAndRowId(TypeDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateTypeDefTreatmentAndRowId(handle); } public TypeReference GetTypeReference(TypeReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new TypeReference(this, GetTypeRefTreatmentAndRowId(handle)); } private uint GetTypeRefTreatmentAndRowId(TypeReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateTypeRefTreatmentAndRowId(handle); } public ExportedType GetExportedType(ExportedTypeHandle handle) { return new ExportedType(this, handle.RowId); } public CustomAttributeHandleCollection GetCustomAttributes(EntityHandle handle) { Debug.Assert(!handle.IsNil); return new CustomAttributeHandleCollection(this, handle); } public CustomAttribute GetCustomAttribute(CustomAttributeHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new CustomAttribute(this, GetCustomAttributeTreatmentAndRowId(handle)); } private uint GetCustomAttributeTreatmentAndRowId(CustomAttributeHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return TreatmentAndRowId((byte)CustomAttributeTreatment.WinMD, handle.RowId); } public DeclarativeSecurityAttribute GetDeclarativeSecurityAttribute(DeclarativeSecurityAttributeHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new DeclarativeSecurityAttribute(this, handle.RowId); } public Constant GetConstant(ConstantHandle handle) { return new Constant(this, handle.RowId); } public MethodDefinition GetMethodDefinition(MethodDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new MethodDefinition(this, GetMethodDefTreatmentAndRowId(handle)); } private uint GetMethodDefTreatmentAndRowId(MethodDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateMethodDefTreatmentAndRowId(handle); } public FieldDefinition GetFieldDefinition(FieldDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new FieldDefinition(this, GetFieldDefTreatmentAndRowId(handle)); } private uint GetFieldDefTreatmentAndRowId(FieldDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateFieldDefTreatmentAndRowId(handle); } public PropertyDefinition GetPropertyDefinition(PropertyDefinitionHandle handle) { return new PropertyDefinition(this, handle); } public EventDefinition GetEventDefinition(EventDefinitionHandle handle) { return new EventDefinition(this, handle); } public MethodImplementation GetMethodImplementation(MethodImplementationHandle handle) { return new MethodImplementation(this, handle); } public MemberReference GetMemberReference(MemberReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new MemberReference(this, GetMemberRefTreatmentAndRowId(handle)); } private uint GetMemberRefTreatmentAndRowId(MemberReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateMemberRefTreatmentAndRowId(handle); } public MethodSpecification GetMethodSpecification(MethodSpecificationHandle handle) { return new MethodSpecification(this, handle); } public Parameter GetParameter(ParameterHandle handle) { return new Parameter(this, handle); } public GenericParameter GetGenericParameter(GenericParameterHandle handle) { return new GenericParameter(this, handle); } public GenericParameterConstraint GetGenericParameterConstraint(GenericParameterConstraintHandle handle) { return new GenericParameterConstraint(this, handle); } public ManifestResource GetManifestResource(ManifestResourceHandle handle) { return new ManifestResource(this, handle); } public AssemblyFile GetAssemblyFile(AssemblyFileHandle handle) { return new AssemblyFile(this, handle); } public StandaloneSignature GetStandaloneSignature(StandaloneSignatureHandle handle) { return new StandaloneSignature(this, handle); } public TypeSpecification GetTypeSpecification(TypeSpecificationHandle handle) { return new TypeSpecification(this, handle); } public ModuleReference GetModuleReference(ModuleReferenceHandle handle) { return new ModuleReference(this, handle); } public InterfaceImplementation GetInterfaceImplementation(InterfaceImplementationHandle handle) { return new InterfaceImplementation(this, handle); } internal TypeDefinitionHandle GetDeclaringType(MethodDefinitionHandle methodDef) { int methodRowId; if (UseMethodPtrTable) { methodRowId = MethodPtrTable.GetRowIdForMethodDefRow(methodDef.RowId); } else { methodRowId = methodDef.RowId; } return TypeDefTable.FindTypeContainingMethod(methodRowId, MethodDefTable.NumberOfRows); } internal TypeDefinitionHandle GetDeclaringType(FieldDefinitionHandle fieldDef) { int fieldRowId; if (UseFieldPtrTable) { fieldRowId = FieldPtrTable.GetRowIdForFieldDefRow(fieldDef.RowId); } else { fieldRowId = fieldDef.RowId; } return TypeDefTable.FindTypeContainingField(fieldRowId, FieldTable.NumberOfRows); } private static readonly ObjectPool<StringBuilder> s_stringBuilderPool = new ObjectPool<StringBuilder>(() => new StringBuilder()); public string GetString(DocumentNameBlobHandle handle) { return BlobStream.GetDocumentName(handle); } public Document GetDocument(DocumentHandle handle) { return new Document(this, handle); } public MethodDebugInformation GetMethodDebugInformation(MethodDebugInformationHandle handle) { return new MethodDebugInformation(this, handle); } public MethodDebugInformation GetMethodDebugInformation(MethodDefinitionHandle handle) { return new MethodDebugInformation(this, MethodDebugInformationHandle.FromRowId(handle.RowId)); } public LocalScope GetLocalScope(LocalScopeHandle handle) { return new LocalScope(this, handle); } public LocalVariable GetLocalVariable(LocalVariableHandle handle) { return new LocalVariable(this, handle); } public LocalConstant GetLocalConstant(LocalConstantHandle handle) { return new LocalConstant(this, handle); } public ImportScope GetImportScope(ImportScopeHandle handle) { return new ImportScope(this, handle); } public CustomDebugInformation GetCustomDebugInformation(CustomDebugInformationHandle handle) { return new CustomDebugInformation(this, handle); } public CustomDebugInformationHandleCollection GetCustomDebugInformation(EntityHandle handle) { Debug.Assert(!handle.IsNil); return new CustomDebugInformationHandleCollection(this, handle); } public LocalScopeHandleCollection GetLocalScopes(MethodDefinitionHandle handle) { return new LocalScopeHandleCollection(this, handle.RowId); } public LocalScopeHandleCollection GetLocalScopes(MethodDebugInformationHandle handle) { return new LocalScopeHandleCollection(this, handle.RowId); } #endregion #region Nested Types private void InitializeNestedTypesMap() { var groupedNestedTypes = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>.Builder>(); int numberOfNestedTypes = NestedClassTable.NumberOfRows; ImmutableArray<TypeDefinitionHandle>.Builder builder = null; TypeDefinitionHandle previousEnclosingClass = default(TypeDefinitionHandle); for (int i = 1; i <= numberOfNestedTypes; i++) { TypeDefinitionHandle enclosingClass = NestedClassTable.GetEnclosingClass(i); Debug.Assert(!enclosingClass.IsNil); if (enclosingClass != previousEnclosingClass) { if (!groupedNestedTypes.TryGetValue(enclosingClass, out builder)) { builder = ImmutableArray.CreateBuilder<TypeDefinitionHandle>(); groupedNestedTypes.Add(enclosingClass, builder); } previousEnclosingClass = enclosingClass; } else { Debug.Assert(builder == groupedNestedTypes[enclosingClass]); } builder.Add(NestedClassTable.GetNestedClass(i)); } var nestedTypesMap = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>>(); foreach (var group in groupedNestedTypes) { nestedTypesMap.Add(group.Key, group.Value.ToImmutable()); } _lazyNestedTypesMap = nestedTypesMap; } /// <summary> /// Returns an array of types nested in the specified type. /// </summary> internal ImmutableArray<TypeDefinitionHandle> GetNestedTypes(TypeDefinitionHandle typeDef) { if (_lazyNestedTypesMap == null) { InitializeNestedTypesMap(); } ImmutableArray<TypeDefinitionHandle> nestedTypes; if (_lazyNestedTypesMap.TryGetValue(typeDef, out nestedTypes)) { return nestedTypes; } return ImmutableArray<TypeDefinitionHandle>.Empty; } #endregion } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using Microsoft.Win32; namespace NUnit.Engine { /// <summary> /// Enumeration identifying a common language /// runtime implementation. /// </summary> public enum RuntimeType { /// <summary>Any supported runtime framework</summary> Any, /// <summary>Microsoft .NET Framework</summary> Net, /// <summary>Microsoft .NET Compact Framework</summary> NetCF, /// <summary>Microsoft Shared Source CLI</summary> SSCLI, /// <summary>Mono</summary> Mono, /// <summary>Silverlight</summary> Silverlight, /// <summary>MonoTouch</summary> MonoTouch } /// <summary> /// RuntimeFramework represents a particular version /// of a common language runtime implementation. /// </summary> [Serializable] public sealed class RuntimeFramework { #region Static and Instance Fields /// <summary> /// DefaultVersion is an empty Version, used to indicate that /// NUnit should select the CLR version to use for the test. /// </summary> public static readonly Version DefaultVersion = new Version(0, 0); private static RuntimeFramework currentFramework; private static RuntimeFramework[] availableFrameworks; #endregion #region Constructor /// <summary> /// Construct from a runtime type and version. If the version has /// two parts, it is taken as a framework version. If it has three /// or more, it is taken as a CLR version. In either case, the other /// version is deduced based on the runtime type and provided version. /// </summary> /// <param name="runtime">The runtime type of the framework</param> /// <param name="version">The version of the framework</param> public RuntimeFramework(RuntimeType runtime, Version version) { Runtime = runtime; if (version.Build < 0) InitFromFrameworkVersion(version); else InitFromClrVersion(version); DisplayName = GetDefaultDisplayName(runtime, version); } private void InitFromFrameworkVersion(Version version) { this.FrameworkVersion = this.ClrVersion = version; if (version.Major > 0) // 0 means any version switch (Runtime) { case RuntimeType.Net: case RuntimeType.Mono: case RuntimeType.Any: switch (version.Major) { case 1: switch (version.Minor) { case 0: this.ClrVersion = Runtime == RuntimeType.Mono ? new Version(1, 1, 4322) : new Version(1, 0, 3705); break; case 1: if (Runtime == RuntimeType.Mono) this.FrameworkVersion = new Version(1, 0); this.ClrVersion = new Version(1, 1, 4322); break; default: ThrowInvalidFrameworkVersion(version); break; } break; case 2: case 3: this.ClrVersion = new Version(2, 0, 50727); break; case 4: this.ClrVersion = new Version(4, 0, 30319); break; default: ThrowInvalidFrameworkVersion(version); break; } break; case RuntimeType.Silverlight: this.ClrVersion = version.Major >= 4 ? new Version(4, 0, 60310) : new Version(2, 0, 50727); break; } } private static void ThrowInvalidFrameworkVersion(Version version) { throw new ArgumentException("Unknown framework version " + version.ToString(), "version"); } private void InitFromClrVersion(Version version) { this.FrameworkVersion = new Version(version.Major, version.Minor); this.ClrVersion = version; if (Runtime == RuntimeType.Mono && version.Major == 1) this.FrameworkVersion = new Version(1, 0); } #endregion #region Properties /// <summary> /// Static method to return a RuntimeFramework object /// for the framework that is currently in use. /// </summary> public static RuntimeFramework CurrentFramework { get { if (currentFramework == null) { Type monoRuntimeType = Type.GetType("Mono.Runtime", false); bool isMono = monoRuntimeType != null; RuntimeType runtime = isMono ? RuntimeType.Mono : Environment.OSVersion.Platform == PlatformID.WinCE ? RuntimeType.NetCF : RuntimeType.Net; int major = Environment.Version.Major; int minor = Environment.Version.Minor; if (isMono) { switch (major) { case 1: minor = 0; break; case 2: major = 3; minor = 5; break; } } else /* It's windows */ if (major == 2) { RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework"); if (key != null) { string installRoot = key.GetValue("InstallRoot") as string; if (installRoot != null) { if (Directory.Exists(Path.Combine(installRoot, "v3.5"))) { major = 3; minor = 5; } else if (Directory.Exists(Path.Combine(installRoot, "v3.0"))) { major = 3; minor = 0; } } } } else if (major == 4 && Type.GetType("System.Reflection.AssemblyMetadataAttribute") != null) { minor = 5; } currentFramework = new RuntimeFramework(runtime, new Version(major, minor)); currentFramework.ClrVersion = Environment.Version; if (isMono) { MethodInfo getDisplayNameMethod = monoRuntimeType.GetMethod( "GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding); if (getDisplayNameMethod != null) currentFramework.DisplayName = (string)getDisplayNameMethod.Invoke(null, new object[0]); } } return currentFramework; } } /// <summary> /// Gets an array of all available frameworks /// </summary> // TODO: Special handling for netcf public static RuntimeFramework[] AvailableFrameworks { get { if (availableFrameworks == null) { List<RuntimeFramework> frameworks = new List<RuntimeFramework>(); AppendDotNetFrameworks(frameworks); AppendDefaultMonoFramework(frameworks); // NYI //AppendMonoFrameworks(frameworks); availableFrameworks = frameworks.ToArray(); } return availableFrameworks; } } /// <summary> /// Returns true if the current RuntimeFramework is available. /// In the current implementation, only Mono and Microsoft .NET /// are supported. /// </summary> /// <returns>True if it's available, false if not</returns> public bool IsAvailable { get { foreach (RuntimeFramework framework in AvailableFrameworks) if (framework.Supports(this)) return true; return false; } } /// <summary> /// The type of this runtime framework /// </summary> public RuntimeType Runtime { get; private set; } /// <summary> /// The framework version for this runtime framework /// </summary> public Version FrameworkVersion { get; private set; } /// <summary> /// The CLR version for this runtime framework /// </summary> public Version ClrVersion { get; private set; } /// <summary> /// Return true if any CLR version may be used in /// matching this RuntimeFramework object. /// </summary> public bool AllowAnyVersion { get { return this.ClrVersion == DefaultVersion; } } /// <summary> /// Returns the Display name for this framework /// </summary> public string DisplayName { get; private set; } #endregion #region Public Methods /// <summary> /// Parses a string representing a RuntimeFramework. /// The string may be just a RuntimeType name or just /// a Version or a hyphenated RuntimeType-Version or /// a Version prefixed by 'v'. /// </summary> /// <param name="s"></param> /// <returns></returns> public static RuntimeFramework Parse(string s) { RuntimeType runtime = RuntimeType.Any; Version version = DefaultVersion; string[] parts = s.Split(new char[] { '-' }); if (parts.Length == 2) { runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), parts[0], true); string vstring = parts[1]; if (vstring != "") version = new Version(vstring); } else if (char.ToLower(s[0]) == 'v') { version = new Version(s.Substring(1)); } else if (IsRuntimeTypeName(s)) { runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), s, true); } else { version = new Version(s); } return new RuntimeFramework(runtime, version); } /// <summary> /// Returns the best available framework that matches a target framework. /// If the target framework has a build number specified, then an exact /// match is needed. Otherwise, the matching framework with the highest /// build number is used. /// </summary> /// <param name="target"></param> /// <returns></returns> public static RuntimeFramework GetBestAvailableFramework(RuntimeFramework target) { RuntimeFramework result = target; if (target.ClrVersion.Build < 0) { foreach (RuntimeFramework framework in AvailableFrameworks) if (framework.Supports(target) && framework.ClrVersion.Build > result.ClrVersion.Build) { result = framework; } } return result; } /// <summary> /// Overridden to return the short name of the framework /// </summary> /// <returns></returns> public override string ToString() { if (this.AllowAnyVersion) { return Runtime.ToString().ToLower(); } else { string vstring = FrameworkVersion.ToString(); if (Runtime == RuntimeType.Any) return "v" + vstring; else return Runtime.ToString().ToLower() + "-" + vstring; } } /// <summary> /// Returns true if the current framework matches the /// one supplied as an argument. Two frameworks match /// if their runtime types are the same or either one /// is RuntimeType.Any and all specified version components /// are equal. Negative (i.e. unspecified) version /// components are ignored. /// </summary> /// <param name="target">The RuntimeFramework to be matched.</param> /// <returns><c>true</c> on match, otherwise <c>false</c></returns> public bool Supports(RuntimeFramework target) { if (this.Runtime != RuntimeType.Any && target.Runtime != RuntimeType.Any && this.Runtime != target.Runtime) return false; if (this.AllowAnyVersion || target.AllowAnyVersion) return true; return VersionsMatch(this.ClrVersion, target.ClrVersion) && this.FrameworkVersion.Major >= target.FrameworkVersion.Major && this.FrameworkVersion.Minor >= target.FrameworkVersion.Minor; } #endregion #region Helper Methods private static bool IsRuntimeTypeName(string name) { foreach (string item in Enum.GetNames(typeof(RuntimeType))) if (item.ToLower() == name.ToLower()) return true; return false; } private static string GetDefaultDisplayName(RuntimeType runtime, Version version) { if (version == DefaultVersion) return runtime.ToString(); else if (runtime == RuntimeType.Any) return "v" + version.ToString(); else return runtime.ToString() + " " + version.ToString(); } private static bool VersionsMatch(Version v1, Version v2) { return v1.Major == v2.Major && v1.Minor == v2.Minor && (v1.Build < 0 || v2.Build < 0 || v1.Build == v2.Build) && (v1.Revision < 0 || v2.Revision < 0 || v1.Revision == v2.Revision); } private static void AppendMonoFrameworks(List<RuntimeFramework> frameworks) { if (Environment.OSVersion.Platform == PlatformID.Win32NT) AppendAllMonoFrameworks(frameworks); else AppendDefaultMonoFramework(frameworks); } private static void AppendAllMonoFrameworks(List<RuntimeFramework> frameworks) { // TODO: Find multiple installed Mono versions under Linux if (Environment.OSVersion.Platform == PlatformID.Win32NT) { // Use registry to find alternate versions RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Novell\Mono"); if (key == null) return; foreach (string version in key.GetSubKeyNames()) { RegistryKey subKey = key.OpenSubKey(version); if (subKey == null) continue; string monoPrefix = subKey.GetValue("SdkInstallRoot") as string; AppendMonoFramework(frameworks, monoPrefix, version); } } else AppendDefaultMonoFramework(frameworks); } // This method works for Windows and Linux but currently // is only called under Linux. private static void AppendDefaultMonoFramework(List<RuntimeFramework> frameworks) { string monoPrefix = null; string version = null; if (Environment.OSVersion.Platform == PlatformID.Win32NT) { RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Novell\Mono"); if (key != null) { version = key.GetValue("DefaultCLR") as string; if (version != null && version != "") { key = key.OpenSubKey(version); if (key != null) monoPrefix = key.GetValue("SdkInstallRoot") as string; } } } else // Assuming we're currently running Mono - change if more runtimes are added { string libMonoDir = Path.GetDirectoryName(typeof(object).Assembly.Location); monoPrefix = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(libMonoDir))); } AppendMonoFramework(frameworks, monoPrefix, version); } private static void AppendMonoFramework(List<RuntimeFramework> frameworks, string monoPrefix, string version) { if (monoPrefix != null) { string displayFmt = version != null ? "Mono " + version + " - {0} Profile" : "Mono {0} Profile"; if (File.Exists(Path.Combine(monoPrefix, "lib/mono/1.0/mscorlib.dll"))) { RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(1, 1, 4322)); framework.DisplayName = string.Format(displayFmt, "1.0"); frameworks.Add(framework); } if (File.Exists(Path.Combine(monoPrefix, "lib/mono/2.0/mscorlib.dll"))) { RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(2, 0, 50727)); framework.DisplayName = string.Format(displayFmt, "2.0"); frameworks.Add(framework); } if (Directory.Exists(Path.Combine(monoPrefix, "lib/mono/3.5"))) { RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(2, 0, 50727)); framework.FrameworkVersion = new Version(3,5); framework.DisplayName = string.Format(displayFmt, "3.5"); frameworks.Add(framework); } if (File.Exists(Path.Combine(monoPrefix, "lib/mono/4.0/mscorlib.dll"))) { RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319)); framework.DisplayName = string.Format(displayFmt, "4.0"); frameworks.Add(framework); } if (File.Exists(Path.Combine(monoPrefix, "lib/mono/4.5/mscorlib.dll"))) { RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319)); framework.FrameworkVersion = new Version(4,5); framework.DisplayName = string.Format(displayFmt, "4.5"); frameworks.Add(framework); } } } private static void AppendDotNetFrameworks(List<RuntimeFramework> frameworks) { if (Environment.OSVersion.Platform == PlatformID.Win32NT) { // Handle Version 1.0, using a different registry key AppendExtremelyOldDotNetFrameworkVersions(frameworks); RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\NET Framework Setup\NDP"); if (key != null) { foreach (string name in key.GetSubKeyNames()) { if (name.StartsWith("v") && name != "v4.0") // v4.0 is a duplicate, legacy key { var versionKey = key.OpenSubKey(name); if (versionKey == null) continue; if (name.StartsWith("v4", StringComparison.Ordinal)) // Version 4 and 4.5 AppendDotNetFourFrameworkVersions(frameworks, versionKey); else // Versions 1.1 through 3.5 AppendOlderDotNetFrameworkVersion(frameworks, versionKey, new Version(name.Substring(1))); } } } } } private static void AppendExtremelyOldDotNetFrameworkVersions(List<RuntimeFramework> frameworks) { RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\.NETFramework\policy\v1.0"); if (key != null) foreach (string build in key.GetValueNames()) frameworks.Add(new RuntimeFramework(RuntimeType.Net, new Version("1.0." + build))); } private static void AppendOlderDotNetFrameworkVersion(List<RuntimeFramework> frameworks, RegistryKey versionKey, Version version) { if (CheckInstallDword(versionKey)) frameworks.Add(new RuntimeFramework(RuntimeType.Net, version)); } // Note: this method cannot be generalized past V4, because (a) it has // specific code for detecting .NET 4.5 and (b) we don't know what // microsoft will do in the future private static void AppendDotNetFourFrameworkVersions(List<RuntimeFramework> frameworks, RegistryKey versionKey) { foreach (string profile in new string[] { "Full", "Client" }) { var profileKey = versionKey.OpenSubKey(profile); if (profileKey == null) continue; if (CheckInstallDword(profileKey)) { var framework = new RuntimeFramework(RuntimeType.Net, new Version(4, 0)); framework.DisplayName += " - " + profile; frameworks.Add(framework); var release = (int)profileKey.GetValue("Release", 0); if (release > 0) { framework = new RuntimeFramework(RuntimeType.Net, new Version(4, 5)); framework.DisplayName += " - " + profile; frameworks.Add(framework); } } } } private static bool CheckInstallDword(RegistryKey key) { return ((int)key.GetValue("Install", 0) == 1); } #endregion } }
/* * Process.cs - Implementation of the "System.Diagnostics.Process" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Diagnostics { #if CONFIG_EXTENDED_DIAGNOSTICS using Platform; using System.IO; using System.ComponentModel; using System.Collections; using System.Globalization; using System.Collections.Specialized; using System.Runtime.CompilerServices; using System.Security.Permissions; // This class deliberately supports only a subset of the full API, // for reasons of security and portability. The set of supported // features roughly corresponds to "Windows 98 mode" in other systems. // We need unrestricted permissions to start and manage processes. #if CONFIG_PERMISSIONS [PermissionSet(SecurityAction.LinkDemand, Unrestricted=true)] [PermissionSet(SecurityAction.InheritanceDemand, Unrestricted=true)] #endif [DefaultProperty("StartInfo")] [DefaultEvent("Exited")] [Designer("System.Diagnostics.Design.ProcessDesigner, System.Design")] public class Process #if CONFIG_COMPONENT_MODEL : Component #endif { // Internal state. private bool enableRaisingEvents; private int exitCode; private IntPtr processHandle; private int processID; private bool hasExited; private String[] argv; private ProcessStartInfo startInfo; #if CONFIG_COMPONENT_MODEL private ISynchronizeInvoke syncObject; #endif private StreamWriter stdin; private StreamReader stdout; private StreamReader stderr; private static Process currentProcess; private static ArrayList children; // Constructor. public Process() { this.processID = -1; } // Check to see if the process exists. private void Exists() { if(processID == -1) { throw new InvalidOperationException (S._("Invalid_ProcessNotStarted")); } } // Check to see if the process exists and has not exited. private void Running() { if(processID == -1) { throw new InvalidOperationException (S._("Invalid_ProcessNotStarted")); } if(hasExited) { throw new InvalidOperationException (S._("Invalid_ProcessExited")); } } // Check to see if the process has exited. private void Finished() { if(processID == -1) { throw new InvalidOperationException (S._("Invalid_ProcessNotStarted")); } if(!hasExited) { throw new InvalidOperationException (S._("Invalid_ProcessNotExited")); } } // Process properties. [MonitoringDescription("ProcessBasePriority")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int BasePriority { get { // We only use the normal priority in this implementation. Exists(); return 8; } } [DefaultValue(false)] [Browsable(false)] [MonitoringDescription("ProcessEnableRaisingEvents")] public bool EnableRaisingEvents { get { return enableRaisingEvents; } set { enableRaisingEvents = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessExitCode")] public int ExitCode { get { Finished(); return exitCode; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessExitTime")] public DateTime ExitTime { get { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessHandle")] public IntPtr Handle { get { Exists(); return processHandle; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessHandleCount")] public int HandleCount { get { Running(); int count = GetHandleCount(processHandle); if(count < 0) { // Don't know how to get the value, so assume that // stdin, stdout, and stderr are the only handles. return 3; } else { return count; } } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessTerminated")] public bool HasExited { get { Exists(); return hasExited; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessId")] public int Id { get { Exists(); return processID; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessMachineName")] public String MachineName { get { Exists(); return "."; // Only local processes are supported. } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessMainModule")] public ProcessModule MainModule { get { Running(); return new ProcessModule(argv[0], ProcessName); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessMainWindowHandle")] public IntPtr MainWindowHandle { get { Running(); return GetMainWindowHandle(processID); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessMainWindowTitle")] public String MainWindowTitle { get { IntPtr handle = MainWindowHandle; if(handle != IntPtr.Zero) { return GetMainWindowTitle(handle); } else { return String.Empty; } } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessMaxWorkingSet")] public IntPtr MaxWorkingSet { get { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } set { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessMinWorkingSet")] public IntPtr MinWorkingSet { get { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } set { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessModules")] public ProcessModuleCollection Modules { get { // In this implementation, we only report the main module. return new ProcessModuleCollection(MainModule); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessNonpagedSystemMemorySize")] public int NonpagedSystemMemorySize { get { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessPagedMemorySize")] public int PagedMemorySize { get { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessPagedSystemMemorySize")] public int PagedSystemMemorySize { get { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessPeakPagedMemorySize")] public int PeakPagedMemorySize { get { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessPeakVirtualMemorySize")] public int PeakVirtualMemorySize { get { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessPeakWorkingSet")] public int PeakWorkingSet { get { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessPriorityBoostEnabled")] public bool PriorityBoostEnabled { get { return false; } set { // Priority boosting is not supported. } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessPriorityClass")] public ProcessPriorityClass PriorityClass { get { // Everything is assumed to run at normal priority. return ProcessPriorityClass.Normal; } set { // Priority changes are not supported. } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessPrivateMemorySize")] public int PrivateMemorySize { get { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessPrivilegedProcessorTime")] public TimeSpan PrivilegedProcessorTime { get { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessProcessName")] public String ProcessName { get { // We always use "argv[0]" as the process name. Running(); String name = argv[0]; if(name != null && name.Length >= 4 && String.Compare(name, name.Length - 4, ".exe", 0, 4, true) == 0) { name = name.Substring(0, name.Length - 4); } if(name != null) { int index1, index2; index1 = name.LastIndexOf('\\'); index2 = name.LastIndexOf('/'); if(index2 > index1) { index1 = index2; } if(index1 != -1) { name = name.Substring(index1 + 1); } } return name; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessProcessorAffinity")] public IntPtr ProcessorAffinity { get { Running(); return new IntPtr(GetProcessorAffinity(processHandle)); } set { // Processor affinity cannot be changed. } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessResponding")] public bool Responding { get { IntPtr handle = MainWindowHandle; if(handle != IntPtr.Zero) { return MainWindowIsResponding(handle); } return true; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessStandardError")] public StreamReader StandardError { get { if(stderr == null) { throw new InvalidOperationException (S._("Invalid_StandardStream")); } return stderr; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessStandardInput")] public StreamWriter StandardInput { get { if(stdin == null) { throw new InvalidOperationException (S._("Invalid_StandardStream")); } return stdin; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessStandardOutput")] public StreamReader StandardOutput { get { if(stdout == null) { throw new InvalidOperationException (S._("Invalid_StandardStream")); } return stdout; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [MonitoringDescription("ProcessStartInfo")] public ProcessStartInfo StartInfo { get { if(startInfo == null) { startInfo = new ProcessStartInfo(); } return startInfo; } set { if(value == null) { throw new ArgumentNullException("value"); } startInfo = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessStartTime")] public DateTime StartTime { get { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } } #if CONFIG_COMPONENT_MODEL [Browsable(false)] [MonitoringDescription("ProcessSynchronizingObject")] public ISynchronizeInvoke SynchronizingObject { get { return syncObject; } set { syncObject = value; } } #endif [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessThreads")] public ProcessThreadCollection Threads { get { // We report a single thread corresponding to each process. // See the comments in "ProcessThread.cs" for more info. return new ProcessThreadCollection (new ProcessThread(this)); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessTotalProcessorTime")] public TimeSpan TotalProcessorTime { get { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessUserProcessorTime")] public TimeSpan UserProcessorTime { get { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessVirtualMemorySize")] public int VirtualMemorySize { get { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MonitoringDescription("ProcessWorkingSet")] public int WorkingSet { get { throw new PlatformNotSupportedException (S._("Invalid_Platform")); } } // Close all resources associated with this object. public void Close() { if(IsCurrentProcess(this)) { // We cannot close the current process. return; } if(processID != -1) { CloseProcess(processHandle, processID); processID = -1; processHandle = IntPtr.Zero; } enableRaisingEvents = false; hasExited = false; if(stdin != null) { stdin.Close(); stdin = null; } if(stdout != null) { stdout.Close(); stdout = null; } if(stderr != null) { stderr.Close(); stderr = null; } argv = null; #if CONFIG_COMPONENT_MODEL syncObject = null; #endif lock(typeof(Process)) { // Remove this process from the list of active children. if(children != null) { children.Remove(this); } } } // Close the main window for this process. public bool CloseMainWindow() { IntPtr handle = MainWindowHandle; if(handle != IntPtr.Zero) { return CloseMainWindow(handle); } else { return false; } } // Dispose this object. protected override void Dispose(bool disposing) { Close(); } // Enter debug mode. public static void EnterDebugMode() { // Nothing to do here. } // Get the current process. public static Process GetCurrentProcess() { lock(typeof(Process)) { if(currentProcess == null) { currentProcess = new Process(); int processID; IntPtr processHandle; GetCurrentProcessInfo (out processID, out processHandle); currentProcess.processID = processID; currentProcess.processHandle = processHandle; currentProcess.argv = Environment.GetCommandLineArgs(); if(currentProcess.argv != null && currentProcess.argv.Length > 0) { ProcessStartInfo info = new ProcessStartInfo(); info.FileName = currentProcess.argv[0]; info.Arguments = ProcessStartInfo.ArgVToArguments (currentProcess.argv, 1, " "); currentProcess.startInfo = info; } } return currentProcess; } } // Determine if a process is the current one. private static bool IsCurrentProcess(Process process) { lock(typeof(Process)) { return (process == currentProcess); } } // Get a particular process by identifier. Insecure, so not supported. public static Process GetProcessById(int processId) { return GetProcessById(processId, "."); } public static Process GetProcessById(int processId, String machineName) { // Get the full process list and then search it. Process[] list = GetProcesses(machineName); if(list != null) { foreach(Process process in list) { if(process.Id == processId) { return process; } } } throw new ArgumentException(S._("Arg_NoSuchProcess")); } // Get a list of all processes. public static Process[] GetProcesses() { // As far as the caller is concerned, the only processes // that exist are the current process and any children // that we have previously forked and have not yet exited. // We don't allow the application to access other processes. lock(typeof(Process)) { int count = (children != null ? children.Count : 0); Process[] list = new Process [count + 1]; list[0] = GetCurrentProcess(); if(children != null) { children.CopyTo(list, 1); } return list; } } public static Process[] GetProcesses(String machineName) { if(machineName == null) { throw new ArgumentNullException("machineName"); } else if(machineName == ".") { // Get information on the local machine. return GetProcesses(); } else { // Cannot request information about remote computers. throw new PlatformNotSupportedException (S._("Invalid_Platform")); } } // Get a list of all processes with a specific name. public static Process[] GetProcessesByName(String processName) { return GetProcessesByName(processName, "."); } public static Process[] GetProcessesByName(String processName, String machineName) { // Get the process list and then filter it by name. Process[] list = GetProcesses(machineName); int count = 0; foreach(Process p1 in list) { if(String.Compare(p1.ProcessName, processName, true) == 0) { ++count; } } Process[] newList = new Process [count]; count = 0; foreach(Process p2 in list) { if(String.Compare(p2.ProcessName, processName, true) == 0) { newList[count++] = p2; } } return newList; } // Kill the process. public void Kill() { if(IsCurrentProcess(this)) { // We cannot kill the current process. return; } Running(); KillProcess(processHandle, processID); processHandle = IntPtr.Zero; processID = -1; Close(); } // Leave debug mode. public static void LeaveDebugMode() { // Nothing to do here. } // Raise the "Exited" event. protected void OnExited() { if(enableRaisingEvents && Exited != null) { Exited(null, new EventArgs()); } } // Refresh information from the operating system. public void Refresh() { // Nothing to do here because nothing changeable is cached. } // Start a process. public bool Start() { ProcessStartInfo.ProcessStartFlags flags; // Validate the start information. if(startInfo == null || startInfo.FileName == String.Empty) { throw new InvalidOperationException (S._("Invalid_ProcessStartInfo")); } flags = startInfo.flags; if((flags & ProcessStartInfo.ProcessStartFlags.UseShellExecute) != 0) { if((flags & (ProcessStartInfo.ProcessStartFlags .RedirectStdin | ProcessStartInfo.ProcessStartFlags .RedirectStdout | ProcessStartInfo.ProcessStartFlags .RedirectStderr)) != 0) { // Cannot redirect if using shell execution. throw new InvalidOperationException (S._("Invalid_ProcessStartInfo")); } } // Close the current process information, if any. Close(); // If attempting to start using the current process, // then we want to do "execute over the top" instead, // replacing the current process with a new one. if(IsCurrentProcess(this)) { flags |= ProcessStartInfo.ProcessStartFlags.ExecOverTop; } // Get the environment to use in the new process if it // was potentially modified by the programmer. String[] env = null; if(startInfo.envVars != null) { StringCollection coll = new StringCollection(); IDictionaryEnumerator e = (IDictionaryEnumerator) (startInfo.envVars.GetEnumerator()); while(e.MoveNext()) { coll.Add(((String)(e.Key)).ToUpper(CultureInfo.InvariantCulture) + "=" + ((String)(e.Value))); } env = new String [coll.Count]; coll.CopyTo(env, 0); } // Get the pathname of the program to be executed. String program; if(startInfo.UseShellExecute && startInfo.WorkingDirectory != String.Empty && !Path.IsPathRooted(startInfo.FileName)) { program = Path.Combine(startInfo.WorkingDirectory, startInfo.FileName); } else { program = startInfo.FileName; } // Parse the arguments into a local argv array. String[] args = ProcessStartInfo.ArgumentsToArgV (startInfo.Arguments); argv = new String [args.Length + 1]; argv[0] = program; Array.Copy(args, 0, argv, 1, args.Length); // Start the process. IntPtr stdinHandle; IntPtr stdoutHandle; IntPtr stderrHandle; if(!StartProcess(program, startInfo.Arguments, startInfo.WorkingDirectory, argv, (int)flags, (int)(startInfo.WindowStyle), env, startInfo.Verb, startInfo.ErrorDialogParentHandle, out processHandle, out processID, out stdinHandle, out stdoutHandle, out stderrHandle)) { // Checking errno for error Errno errno = Process.GetErrno(); if( errno != Errno.Success ) { throw new Win32Exception(Process.GetErrnoMessage(errno)); } } // Wrap up the redirected I/O streams. if(stdinHandle != SocketMethods.GetInvalidHandle()) { stdin = new StreamWriter (new FileStream(stdinHandle, FileAccess.Write, true)); stdin.AutoFlush = true; } if(stdoutHandle != SocketMethods.GetInvalidHandle()) { stdout = new StreamReader (new FileStream(stdoutHandle, FileAccess.Read, true)); } if(stderrHandle != SocketMethods.GetInvalidHandle()) { stderr = new StreamReader (new FileStream(stderrHandle, FileAccess.Read, true)); } // Add the process to the list of active children. lock(typeof(Process)) { if(children == null) { children = new ArrayList(); } children.Add(this); } return true; } // Convenience wrappers for "Process.Start()". public static Process Start(ProcessStartInfo startInfo) { Process process = new Process(); process.StartInfo = startInfo; if(process.Start()) { return process; } else { return null; } } public static Process Start(String fileName) { Process process = new Process(); process.StartInfo = new ProcessStartInfo(fileName); if(process.Start()) { return process; } else { return null; } } public static Process Start(String fileName, String arguments) { Process process = new Process(); process.StartInfo = new ProcessStartInfo(fileName, arguments); if(process.Start()) { return process; } else { return null; } } // Convert this object into a string. public override String ToString() { return ProcessName; } // Wait for the process to exit. public void WaitForExit() { WaitForExit(Int32.MaxValue); } public bool WaitForExit(int milliseconds) { Exists(); if(hasExited) { // The process has already exited. return true; } if(IsCurrentProcess(this)) { // Cannot wait for the current process. return false; } if(!WaitForExit(processHandle, processID, milliseconds, out exitCode)) { // Timeout occurred while waiting for the process. return false; } hasExited = true; OnExited(); return true; } // Wait for the process to reach its idle state. public bool WaitForInputIdle() { return WaitForInputIdle(Int32.MaxValue); } public bool WaitForInputIdle(int milliseconds) { Exists(); if(hasExited) { return false; } else if(IsCurrentProcess(this)) { // Cannot wait for the current process. return false; } else { return WaitForInputIdle (processHandle, processID, milliseconds); } } // Event that is emitted when the process exits. [MonitoringDescription("ProcessExited")] [Category("Behavior")] public event EventHandler Exited; // Get the main window handle for a process. // Returns IntPtr.Zero if unknown. [MethodImpl(MethodImplOptions.InternalCall)] extern private static IntPtr GetMainWindowHandle(int processID); // Get the title of a main window. Returns null if unknown. [MethodImpl(MethodImplOptions.InternalCall)] extern private static String GetMainWindowTitle(IntPtr windowHandle); // Determine if the main window of a process is responding. [MethodImpl(MethodImplOptions.InternalCall)] extern private static bool MainWindowIsResponding(IntPtr windowHandle); // Get the process ID and handle of the current process. [MethodImpl(MethodImplOptions.InternalCall)] extern private static void GetCurrentProcessInfo(out int processID, out IntPtr handle); // Get the number of handles that are currently open by a process. // Returns -1 if the number cannot be determined on this platform. [MethodImpl(MethodImplOptions.InternalCall)] extern private static int GetHandleCount(IntPtr processHandle); // Get the processor mask for which processors a process may run on. // Return 1 if it is impossible to determine the affinity information // (which essentially means "runs on processor 1"). [MethodImpl(MethodImplOptions.InternalCall)] extern private static int GetProcessorAffinity(IntPtr processHandle); // Close a process, but leave the process running in the background. [MethodImpl(MethodImplOptions.InternalCall)] extern private static void CloseProcess (IntPtr processHandle, int processID); // Kill a process. [MethodImpl(MethodImplOptions.InternalCall)] extern private static void KillProcess (IntPtr processHandle, int processID); // Send a request to close a main window. [MethodImpl(MethodImplOptions.InternalCall)] extern private static bool CloseMainWindow(IntPtr windowHandle); // Wait for a particular process to exit. [MethodImpl(MethodImplOptions.InternalCall)] extern private static bool WaitForExit (IntPtr processHandle, int processID, int milliseconds, out int exitCode); // Wait for a particular process to enter the idle state after startup. [MethodImpl(MethodImplOptions.InternalCall)] extern private static bool WaitForInputIdle (IntPtr processHandle, int processID, int milliseconds); // Start a new process. Returns false if it could not be started. [MethodImpl(MethodImplOptions.InternalCall)] extern private static bool StartProcess (String filename, String arguments, String workingDir, String[] argv, int flags, int windowStyle, String[] envVars, String verb, IntPtr errorDialogParent, out IntPtr processHandle, out int processID, out IntPtr stdinHandle, out IntPtr stdoutHandle, out IntPtr stderrHandle); // Get the last-occurring system error code for the current thread. [MethodImpl(MethodImplOptions.InternalCall)] extern public static Errno GetErrno(); // Get a descriptive message for an error from the underlying platform. // Returns null if the platform doesn't have an appropriate message. [MethodImpl(MethodImplOptions.InternalCall)] extern public static String GetErrnoMessage(Errno errno); }; // class Process #endif // CONFIG_EXTENDED_DIAGNOSTICS }; // namespace System.Diagnostics
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// ItemDigitalDelivery /// </summary> [DataContract] public partial class ItemDigitalDelivery : IEquatable<ItemDigitalDelivery>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="ItemDigitalDelivery" /> class. /// </summary> /// <param name="activationCodeDescription">Description of the activation code.</param> /// <param name="activationCodeLowWarning">The number of activation codes whcih should generate a warning email.</param> /// <param name="activationCodeRealtimeUrl">The URL to retrieve activation codes from in real-time.</param> /// <param name="activationCodeSharedSecret">Shared secret used when communicating with the real-time URL.</param> /// <param name="activationCodeType">Type of activation code.</param> /// <param name="digitalItems">Digital items that customer can download when this item is purchased.</param> public ItemDigitalDelivery(string activationCodeDescription = default(string), int? activationCodeLowWarning = default(int?), string activationCodeRealtimeUrl = default(string), string activationCodeSharedSecret = default(string), string activationCodeType = default(string), List<ItemDigitalItem> digitalItems = default(List<ItemDigitalItem>)) { this.ActivationCodeDescription = activationCodeDescription; this.ActivationCodeLowWarning = activationCodeLowWarning; this.ActivationCodeRealtimeUrl = activationCodeRealtimeUrl; this.ActivationCodeSharedSecret = activationCodeSharedSecret; this.ActivationCodeType = activationCodeType; this.DigitalItems = digitalItems; } /// <summary> /// Description of the activation code /// </summary> /// <value>Description of the activation code</value> [DataMember(Name="activation_code_description", EmitDefaultValue=false)] public string ActivationCodeDescription { get; set; } /// <summary> /// The number of activation codes whcih should generate a warning email /// </summary> /// <value>The number of activation codes whcih should generate a warning email</value> [DataMember(Name="activation_code_low_warning", EmitDefaultValue=false)] public int? ActivationCodeLowWarning { get; set; } /// <summary> /// The URL to retrieve activation codes from in real-time /// </summary> /// <value>The URL to retrieve activation codes from in real-time</value> [DataMember(Name="activation_code_realtime_url", EmitDefaultValue=false)] public string ActivationCodeRealtimeUrl { get; set; } /// <summary> /// Shared secret used when communicating with the real-time URL /// </summary> /// <value>Shared secret used when communicating with the real-time URL</value> [DataMember(Name="activation_code_shared_secret", EmitDefaultValue=false)] public string ActivationCodeSharedSecret { get; set; } /// <summary> /// Type of activation code /// </summary> /// <value>Type of activation code</value> [DataMember(Name="activation_code_type", EmitDefaultValue=false)] public string ActivationCodeType { get; set; } /// <summary> /// Digital items that customer can download when this item is purchased /// </summary> /// <value>Digital items that customer can download when this item is purchased</value> [DataMember(Name="digital_items", EmitDefaultValue=false)] public List<ItemDigitalItem> DigitalItems { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ItemDigitalDelivery {\n"); sb.Append(" ActivationCodeDescription: ").Append(ActivationCodeDescription).Append("\n"); sb.Append(" ActivationCodeLowWarning: ").Append(ActivationCodeLowWarning).Append("\n"); sb.Append(" ActivationCodeRealtimeUrl: ").Append(ActivationCodeRealtimeUrl).Append("\n"); sb.Append(" ActivationCodeSharedSecret: ").Append(ActivationCodeSharedSecret).Append("\n"); sb.Append(" ActivationCodeType: ").Append(ActivationCodeType).Append("\n"); sb.Append(" DigitalItems: ").Append(DigitalItems).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as ItemDigitalDelivery); } /// <summary> /// Returns true if ItemDigitalDelivery instances are equal /// </summary> /// <param name="input">Instance of ItemDigitalDelivery to be compared</param> /// <returns>Boolean</returns> public bool Equals(ItemDigitalDelivery input) { if (input == null) return false; return ( this.ActivationCodeDescription == input.ActivationCodeDescription || (this.ActivationCodeDescription != null && this.ActivationCodeDescription.Equals(input.ActivationCodeDescription)) ) && ( this.ActivationCodeLowWarning == input.ActivationCodeLowWarning || (this.ActivationCodeLowWarning != null && this.ActivationCodeLowWarning.Equals(input.ActivationCodeLowWarning)) ) && ( this.ActivationCodeRealtimeUrl == input.ActivationCodeRealtimeUrl || (this.ActivationCodeRealtimeUrl != null && this.ActivationCodeRealtimeUrl.Equals(input.ActivationCodeRealtimeUrl)) ) && ( this.ActivationCodeSharedSecret == input.ActivationCodeSharedSecret || (this.ActivationCodeSharedSecret != null && this.ActivationCodeSharedSecret.Equals(input.ActivationCodeSharedSecret)) ) && ( this.ActivationCodeType == input.ActivationCodeType || (this.ActivationCodeType != null && this.ActivationCodeType.Equals(input.ActivationCodeType)) ) && ( this.DigitalItems == input.DigitalItems || this.DigitalItems != null && this.DigitalItems.SequenceEqual(input.DigitalItems) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.ActivationCodeDescription != null) hashCode = hashCode * 59 + this.ActivationCodeDescription.GetHashCode(); if (this.ActivationCodeLowWarning != null) hashCode = hashCode * 59 + this.ActivationCodeLowWarning.GetHashCode(); if (this.ActivationCodeRealtimeUrl != null) hashCode = hashCode * 59 + this.ActivationCodeRealtimeUrl.GetHashCode(); if (this.ActivationCodeSharedSecret != null) hashCode = hashCode * 59 + this.ActivationCodeSharedSecret.GetHashCode(); if (this.ActivationCodeType != null) hashCode = hashCode * 59 + this.ActivationCodeType.GetHashCode(); if (this.DigitalItems != null) hashCode = hashCode * 59 + this.DigitalItems.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { // ActivationCodeDescription (string) maxLength if(this.ActivationCodeDescription != null && this.ActivationCodeDescription.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for ActivationCodeDescription, length must be less than 50.", new [] { "ActivationCodeDescription" }); } // ActivationCodeRealtimeUrl (string) maxLength if(this.ActivationCodeRealtimeUrl != null && this.ActivationCodeRealtimeUrl.Length > 350) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for ActivationCodeRealtimeUrl, length must be less than 350.", new [] { "ActivationCodeRealtimeUrl" }); } // ActivationCodeSharedSecret (string) maxLength if(this.ActivationCodeSharedSecret != null && this.ActivationCodeSharedSecret.Length > 20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for ActivationCodeSharedSecret, length must be less than 20.", new [] { "ActivationCodeSharedSecret" }); } yield break; } } }
#pragma warning disable 1634, 1691 //----------------------------------------------------------------------------- // // <copyright file="ContentLocatorBase.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // ContentLocatorBase contains an ordered set of ContentLocatorParts which each identify // a piece of content within a certain context. Resolving one part // provides the context to resolve the next part. Locators are used // to refer to external data in a structured way. // // Spec: http://team/sites/ag/Specifications/Simplifying%20Store%20Cache%20Model.doc // // History: // 06/30/2004: rruiz: Introduced new concrete class to specifically represent // a list of LocatorParts (before we overloaded LocatorBase). // 02/28/2005: rruiz: Renamed class to Locator for FxCop violation. // 05/02/2005: rruiz: Renamed the class and simplified API by using collections. // //----------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Windows.Annotations.Storage; using System.Windows.Data; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using MS.Internal; using MS.Internal.Annotations; #pragma warning disable 1634, 1691 // suppressing PreSharp warnings namespace System.Windows.Annotations { /// <summary> /// ContentLocatorBase contains an ordered set of ContentLocatorParts which each identify /// a piece of content within a certain context. Resolving one part /// provides the context to resolve the next part. Locators are used /// to refer to external data in a structured way. /// </summary> [XmlRoot(Namespace = AnnotationXmlConstants.Namespaces.CoreSchemaNamespace, ElementName = AnnotationXmlConstants.Elements.ContentLocator)] public sealed class ContentLocator : ContentLocatorBase, IXmlSerializable { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors /// <summary> /// Creates an instance of ContentLocator. /// </summary> public ContentLocator() { _parts = new AnnotationObservableCollection<ContentLocatorPart>(); _parts.CollectionChanged += OnCollectionChanged; } #endregion Constructors //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Determines if this list begins with the ContentLocatorParts that /// make up matchList. All ContentLocatorParts in matchList must /// be present and in the same order in this list for /// true to be returned. /// </summary> /// <param name="locator">the list to compare with</param> /// <returns> /// true if this list begins with the ContentLocatorParts in locator; /// false otherwise. If locator is longer than this locator, will /// return false as well. /// </returns> /// <exception cref="ArgumentNullException">locator is null</exception> public bool StartsWith(ContentLocator locator) { if (locator == null) { throw new ArgumentNullException("locator"); } Invariant.Assert(locator.Parts != null, "Locator has null Parts property."); // If this locator is shorter than matchList, then this can't contain matchList. #pragma warning suppress 6506 // Invariant.Assert(locator.Parts != null) if (this.Parts.Count < locator.Parts.Count) { return false; } for (int locatorPartIndex = 0; locatorPartIndex < locator.Parts.Count; locatorPartIndex++) { ContentLocatorPart left = locator.Parts[locatorPartIndex]; ContentLocatorPart right = this.Parts[locatorPartIndex]; // ContentLocator parts can be null so check for that case here if (left == null && right != null) { return false; } if (!left.Matches(right)) { return false; } } return true; } /// <summary> /// Creates a deep copy of this list. A new list with a clone of /// every ContentLocatorPart in this list, in the same order, is returned. /// Never returns null. /// </summary> /// <returns>a deep copy of this list</returns> public override Object Clone() { ContentLocator clone = new ContentLocator(); ContentLocatorPart newPart = null; foreach (ContentLocatorPart part in this.Parts) { if (part != null) newPart = (ContentLocatorPart)part.Clone(); else newPart = null; clone.Parts.Add(newPart); } return clone; } #region IXmlSerializable Implementation /// <summary> /// Returns the null. The annotations schema can be found at /// http://schemas.microsoft.com/windows/annotations/2003/11/core. /// </summary> public XmlSchema GetSchema() { return null; } /// <summary> /// Writes the internal data for this ContentLocator to the writer. This /// method is used by an XmlSerializer to serialize a ContentLocator. Don't /// use this method directly, to serialize a ContentLocator to Xml, use an /// XmlSerializer. /// </summary> /// <param name="writer">the writer to write internal data to</param> /// <exception cref="ArgumentNullException">writer is null</exception> public void WriteXml(XmlWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } string prefix = writer.LookupPrefix(AnnotationXmlConstants.Namespaces.CoreSchemaNamespace); if (prefix == null) { writer.WriteAttributeString(AnnotationXmlConstants.Prefixes.XmlnsPrefix, AnnotationXmlConstants.Prefixes.CoreSchemaPrefix, null, AnnotationXmlConstants.Namespaces.CoreSchemaNamespace); } prefix = writer.LookupPrefix(AnnotationXmlConstants.Namespaces.BaseSchemaNamespace); if (prefix == null) { writer.WriteAttributeString(AnnotationXmlConstants.Prefixes.XmlnsPrefix, AnnotationXmlConstants.Prefixes.BaseSchemaPrefix, null, AnnotationXmlConstants.Namespaces.BaseSchemaNamespace); } // Write each ContentLocatorPart as its own element foreach (ContentLocatorPart part in _parts) { prefix = writer.LookupPrefix(part.PartType.Namespace); if (String.IsNullOrEmpty(prefix)) { prefix = "tmp"; } // ContentLocatorParts cannot write themselves out becuase the element // name is based on the part's type. The ContentLocatorPart instance // has no way (through normal serialization) to change the element // name it writes out at runtime. writer.WriteStartElement(prefix, part.PartType.Name, part.PartType.Namespace); // Each name/value pair for the ContentLocatorPart becomes an attribute foreach (KeyValuePair<string, string> pair in part.NameValuePairs) { writer.WriteStartElement(AnnotationXmlConstants.Elements.Item, AnnotationXmlConstants.Namespaces.CoreSchemaNamespace); writer.WriteAttributeString(AnnotationXmlConstants.Attributes.ItemName, pair.Key); writer.WriteAttributeString(AnnotationXmlConstants.Attributes.ItemValue, pair.Value); writer.WriteEndElement(); } writer.WriteEndElement(); } } /// <summary> /// Reads the internal data for this ContentLocator from the reader. This /// method is used by an XmlSerializer to deserialize a ContentLocator. Don't /// use this method directly, to deserialize a ContentLocator from Xml, use an /// XmlSerializer. /// </summary> /// <param name="reader">the reader to read internal data from</param> /// <exception cref="ArgumentNullException">reader is null</exception> public void ReadXml(XmlReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } // We expect no attributes on a "ContentLocator", // so throw using the name of one of the unexpected attributes Annotation.CheckForNonNamespaceAttribute(reader, AnnotationXmlConstants.Elements.ContentLocator); if (!reader.IsEmptyElement) { reader.Read(); // Reads the start of the "ContentLocator" element // ContentLocatorParts cannot write themselves out (see above). They could read // themselves in but instead of having write code in one place and read // code somewhere else - we keep it together in this class. while (!(AnnotationXmlConstants.Elements.ContentLocator == reader.LocalName && XmlNodeType.EndElement == reader.NodeType)) { if (XmlNodeType.Element != reader.NodeType) { throw new XmlException(SR.Get(SRID.InvalidXmlContent, AnnotationXmlConstants.Elements.ContentLocator)); } ContentLocatorPart part = new ContentLocatorPart(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI)); // Read each of the Item elements within the ContentLocatorPart if (!reader.IsEmptyElement) { // We expect no attributes on a locator part tag, // so throw using the name of one of the unexpected attributes Annotation.CheckForNonNamespaceAttribute(reader, part.PartType.Name); reader.Read(); // Read the start of the locator part tag while (!(XmlNodeType.EndElement == reader.NodeType && part.PartType.Name == reader.LocalName)) { if (AnnotationXmlConstants.Elements.Item == reader.LocalName && reader.NamespaceURI == AnnotationXmlConstants.Namespaces.CoreSchemaNamespace) { string name = null; string value = null; while (reader.MoveToNextAttribute()) { switch (reader.LocalName) { case AnnotationXmlConstants.Attributes.ItemName: name = reader.Value; break; case AnnotationXmlConstants.Attributes.ItemValue: value = reader.Value; break; default: if (!Annotation.IsNamespaceDeclaration(reader)) throw new XmlException(SR.Get(SRID.UnexpectedAttribute, reader.LocalName, AnnotationXmlConstants.Elements.Item)); break; } } if (name == null) { throw new XmlException(SR.Get(SRID.RequiredAttributeMissing, AnnotationXmlConstants.Attributes.ItemName, AnnotationXmlConstants.Elements.Item)); } if (value == null) { throw new XmlException(SR.Get(SRID.RequiredAttributeMissing, AnnotationXmlConstants.Attributes.ItemValue, AnnotationXmlConstants.Elements.Item)); } reader.MoveToContent(); part.NameValuePairs.Add(name, value); bool isEmpty = reader.IsEmptyElement; reader.Read(); // Read the beginning of the complete Item tag if (!isEmpty) { if (!(XmlNodeType.EndElement == reader.NodeType && AnnotationXmlConstants.Elements.Item == reader.LocalName)) { // Should not contain any content, only attributes throw new XmlException(SR.Get(SRID.InvalidXmlContent, AnnotationXmlConstants.Elements.Item)); } else { reader.Read(); // Read the end of the Item tag } } } else { // The locator part contains data other than just "Item" tags throw new XmlException(SR.Get(SRID.InvalidXmlContent, part.PartType.Name)); } } } _parts.Add(part); reader.Read(); // Read the ContentLocatorPart element } } reader.Read(); // Reads the end of the "ContentLocator" element (or whole element if empty) } #endregion IXmlSerializable Implementation #endregion Public Methods //------------------------------------------------------ // // Public Operators // //------------------------------------------------------ //------------------------------------------------------ // // Public Events // //------------------------------------------------------ //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties /// <summary> /// /// </summary> public Collection<ContentLocatorPart> Parts { get { return _parts; } } #endregion Public Properties //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region InternalMethods /// <summary> /// Creates the dot product of this ContentLocator and the list of /// ContentLocatorParts. The result is n Locators where n is the number of /// ContentLocatorParts passed in. /// One of the resulting Locators is this ContentLocator. If there are no /// additional ContentLocatorParts a list with just this ContentLocator (unmodified) /// is returned. /// </summary> /// <param name="additionalLocatorParts">array of ContentLocatorParts</param> /// <returns>array of Locators (one for each additional ContentLocatorPart)</returns> internal IList<ContentLocatorBase> DotProduct(IList<ContentLocatorPart> additionalLocatorParts) { List<ContentLocatorBase> results = null; // If there aren't any additional locator parts - this is basically a no-op if (additionalLocatorParts == null || additionalLocatorParts.Count == 0) { results = new List<ContentLocatorBase>(1); results.Add(this); } else { results = new List<ContentLocatorBase>(additionalLocatorParts.Count); for (int i = 1; i < additionalLocatorParts.Count; i++) { ContentLocator loc = (ContentLocator)this.Clone(); loc.Parts.Add(additionalLocatorParts[i]); results.Add(loc); } this.Parts.Add(additionalLocatorParts[0]); results.Insert(0, this); } return results; } /// <summary> /// Merges this ContentLocator with a ContentLocatorBase. If other is a /// ContentLocatorGroup, each of its Locators are added to clones of /// this ContentLocatorBase and are added to a new ContentLocatorGroup which is /// returned. If other is a ContentLocatorBase, its appended to this /// ContentLocatorBase and this ContentLocatorBase is returned. /// Both operation modify this ContentLocatorBase. /// </summary> /// <param name="other">the ContentLocatorBase to merge with</param> /// <returns>a ContentLocatorBase containing the final merged product</returns> internal override ContentLocatorBase Merge(ContentLocatorBase other) { if (other == null) return this; ContentLocatorGroup locatorGroup = other as ContentLocatorGroup; if (locatorGroup != null) { ContentLocatorGroup newGroup = new ContentLocatorGroup(); ContentLocator temp = null; // Create n-1 clones of this LPS and append all but one // LPSs in the set to the clones, adding the clones to a // new ContentLocatorGroup foreach (ContentLocator loc in locatorGroup.Locators) { if (temp == null) { temp = loc; } else { ContentLocator clone = (ContentLocator)this.Clone(); clone.Append(loc); newGroup.Locators.Add(clone); } } // Finally, add the remaining LPS in the set to this LPS // and add this to the new ContentLocatorGroup if (temp != null) { this.Append(temp); newGroup.Locators.Add(this); } if (newGroup.Locators.Count == 0) return this; else return newGroup; } else { // Safe cast - ContentLocator only has two subclasses this.Append((ContentLocator)other); return this; } } /// <summary> /// Appends a ContentLocator to this ContentLocator. The passed in /// ContentLocator is not modified in anyway. Its ContentLocatorParts are cloned. /// </summary> /// <param name="other">locator to append</param> internal void Append(ContentLocator other) { Invariant.Assert(other != null, "Parameter 'other' is null."); foreach(ContentLocatorPart part in other.Parts) { this.Parts.Add((ContentLocatorPart)part.Clone()); } } #endregion Internal Methods //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods /// <summary> /// Listens for change events from the list of parts. Fires a change event /// for this ContentLocator when an event is received. /// </summary> private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { FireLocatorChanged("Parts"); } #endregion Private Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields /// <summary> /// List of ContentLocatorParts in this locator. /// </summary> private AnnotationObservableCollection<ContentLocatorPart> _parts; #endregion Private Fields } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public static class LiftedBitwiseAndNullableTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedBitwiseAndNullableByteTest(bool useInterpreter) { byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyBitwiseAndNullableByte(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedBitwiseAndNullableIntTest(bool useInterpreter) { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyBitwiseAndNullableInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedBitwiseAndNullableLongTest(bool useInterpreter) { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyBitwiseAndNullableLong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedBitwiseAndNullableSByteTest(bool useInterpreter) { sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyBitwiseAndNullableSByte(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedBitwiseAndNullableShortTest(bool useInterpreter) { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyBitwiseAndNullableShort(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedBitwiseAndNullableUIntTest(bool useInterpreter) { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyBitwiseAndNullableUInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedBitwiseAndNullableULongTest(bool useInterpreter) { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyBitwiseAndNullableULong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedBitwiseAndNullableUShortTest(bool useInterpreter) { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyBitwiseAndNullableUShort(values[i], values[j], useInterpreter); } } } #endregion #region Helpers public static byte AndNullableByte(byte a, byte b) { return (byte)(a & b); } public static int AndNullableInt(int a, int b) { return (int)(a & b); } public static long AndNullableLong(long a, long b) { return (long)(a & b); } public static sbyte AndNullableSByte(sbyte a, sbyte b) { return (sbyte)(a & b); } public static short AndNullableShort(short a, short b) { return (short)(a & b); } public static uint AndNullableUInt(uint a, uint b) { return (uint)(a & b); } public static ulong AndNullableULong(ulong a, ulong b) { return (ulong)(a & b); } public static ushort AndNullableUShort(ushort a, ushort b) { return (ushort)(a & b); } #endregion #region Test verifiers private static void VerifyBitwiseAndNullableByte(byte? a, byte? b, bool useInterpreter) { Expression<Func<byte?>> e = Expression.Lambda<Func<byte?>>( Expression.And( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?)), typeof(LiftedBitwiseAndNullableTests).GetTypeInfo().GetDeclaredMethod("AndNullableByte"))); Func<byte?> f = e.Compile(useInterpreter); Assert.Equal(a & b, f()); } private static void VerifyBitwiseAndNullableInt(int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.And( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)), typeof(LiftedBitwiseAndNullableTests).GetTypeInfo().GetDeclaredMethod("AndNullableInt"))); Func<int?> f = e.Compile(useInterpreter); Assert.Equal(a & b, f()); } private static void VerifyBitwiseAndNullableLong(long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.And( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)), typeof(LiftedBitwiseAndNullableTests).GetTypeInfo().GetDeclaredMethod("AndNullableLong"))); Func<long?> f = e.Compile(useInterpreter); Assert.Equal(a & b, f()); } private static void VerifyBitwiseAndNullableSByte(sbyte? a, sbyte? b, bool useInterpreter) { Expression<Func<sbyte?>> e = Expression.Lambda<Func<sbyte?>>( Expression.And( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?)), typeof(LiftedBitwiseAndNullableTests).GetTypeInfo().GetDeclaredMethod("AndNullableSByte"))); Func<sbyte?> f = e.Compile(useInterpreter); Assert.Equal(a & b, f()); } private static void VerifyBitwiseAndNullableShort(short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.And( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)), typeof(LiftedBitwiseAndNullableTests).GetTypeInfo().GetDeclaredMethod("AndNullableShort"))); Func<short?> f = e.Compile(useInterpreter); Assert.Equal(a & b, f()); } private static void VerifyBitwiseAndNullableUInt(uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.And( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)), typeof(LiftedBitwiseAndNullableTests).GetTypeInfo().GetDeclaredMethod("AndNullableUInt"))); Func<uint?> f = e.Compile(useInterpreter); Assert.Equal(a & b, f()); } private static void VerifyBitwiseAndNullableULong(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.And( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)), typeof(LiftedBitwiseAndNullableTests).GetTypeInfo().GetDeclaredMethod("AndNullableULong"))); Func<ulong?> f = e.Compile(useInterpreter); Assert.Equal(a & b, f()); } private static void VerifyBitwiseAndNullableUShort(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.And( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)), typeof(LiftedBitwiseAndNullableTests).GetTypeInfo().GetDeclaredMethod("AndNullableUShort"))); Func<ushort?> f = e.Compile(useInterpreter); Assert.Equal(a & b, f()); } #endregion } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.VisualStudio.Services.Agent.Util; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Xunit; using System; namespace Microsoft.VisualStudio.Services.Agent.Tests { public sealed class LocStringsL0 { private static readonly Regex ValidKeyRegex = new Regex("^[_a-zA-Z0-9]+$"); [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void IsNotMissingCommonLocStrings() { ValidateLocStrings(new TestHostContext(this), project: "Microsoft.VisualStudio.Services.Agent"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public void IsNotMissingListenerLocStrings() { ValidateLocStrings(new TestHostContext(this), project: "Agent.Listener"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public void IsNotMissingWorkerLocStrings() { ValidateLocStrings(new TestHostContext(this), project: "Agent.Worker"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "LocString")] public void IsLocStringsPrettyPrint() { // Load the strings. string stringsFile = Path.Combine(TestUtil.GetSrcPath(), "Misc", "layoutbin", "en-US", "strings.json"); Assert.True(File.Exists(stringsFile), $"File does not exist: {stringsFile}"); var resourceDictionary = IOUtil.LoadObject<Dictionary<string, object>>(stringsFile); // sort the dictionary. Dictionary<string, object> sortedResourceDictionary = new Dictionary<string, object>(); foreach (var res in resourceDictionary.OrderBy(r => r.Key)) { sortedResourceDictionary[res.Key] = res.Value; } // print to file. string prettyStringsFile = Path.Combine(TestUtil.GetSrcPath(), "Misc", "layoutbin", "en-US", "strings.json.pretty"); IOUtil.SaveObject(sortedResourceDictionary, prettyStringsFile); Assert.True(string.Equals(File.ReadAllText(stringsFile), File.ReadAllText(prettyStringsFile)), $"Orginal string.json file: {stringsFile} is not pretty printed, replace it with: {prettyStringsFile}"); // delete file on succeed File.Delete(prettyStringsFile); } [Fact] [Trait("Level", "L0")] [Trait("Category", "LocString")] public void FindExtraLocStrings() { // Load the strings. string stringsFile = Path.Combine(TestUtil.GetSrcPath(), "Misc", "layoutbin", "en-US", "strings.json"); Assert.True(File.Exists(stringsFile), $"File does not exist: {stringsFile}"); var resourceDictionary = IOUtil.LoadObject<Dictionary<string, object>>(stringsFile); // Find all loc string key in source file. // // Note, narrow the search to each project folder only. Otherwise intermittent errors occur // when recursively searching due to parallel tests are deleting temp folders (DirectoryNotFoundException). var keys = new List<string>(); string[] sourceFiles = Directory.GetFiles(TestUtil.GetProjectPath("Microsoft.VisualStudio.Services.Agent"), "*.cs", SearchOption.AllDirectories) .Concat(Directory.GetFiles(TestUtil.GetProjectPath("Agent.Listener"), "*.cs", SearchOption.AllDirectories)) .Concat(Directory.GetFiles(TestUtil.GetProjectPath("Agent.Worker"), "*.cs", SearchOption.AllDirectories)) .Concat(Directory.GetFiles(TestUtil.GetProjectPath("Agent.Plugins"), "*.cs", SearchOption.AllDirectories)) .Concat(Directory.GetFiles(TestUtil.GetProjectPath("Agent.Sdk"), "*.cs", SearchOption.AllDirectories)) .ToArray(); foreach (string sourceFile in sourceFiles) { // Skip files in the obj directory. if (sourceFile.Contains(StringUtil.Format("{0}obj{0}", Path.DirectorySeparatorChar))) { continue; } foreach (string line in File.ReadAllLines(sourceFile)) { // Search for calls to the StringUtil.Loc method within the line. const string Pattern = "StringUtil.Loc("; int searchIndex = 0; int patternIndex; while (searchIndex < line.Length && (patternIndex = line.IndexOf(Pattern, searchIndex)) >= 0) { // Bump the search index in preparation for the for the next iteration within the same line. searchIndex = patternIndex + Pattern.Length; // Extract the resource key. int keyStartIndex = patternIndex + Pattern.Length; int keyEndIndex; if (keyStartIndex + 2 < line.Length && // Key should start with a ", be followed by at least line[keyStartIndex] == '"' && // one character, and end with a ". (keyEndIndex = line.IndexOf('"', keyStartIndex + 1)) > 0) { // Remove the first and last double quotes. keyStartIndex++; keyEndIndex--; string key = line.Substring( startIndex: keyStartIndex, length: keyEndIndex - keyStartIndex + 1); if (ValidKeyRegex.IsMatch(key)) { // A valid key was extracted. keys.Add(key); continue; } } } } } // find extra loc strings. var extraKeys = resourceDictionary.Keys.Where(x => !keys.Contains(x))?.ToList(); if (extraKeys != null) { Assert.True(extraKeys.Count == 0, $"Please save company's money by removing extra loc strings:{Environment.NewLine}{string.Join(Environment.NewLine, extraKeys)}"); } } private void ValidateLocStrings(TestHostContext hc, string project) { using (hc) { Tracing trace = hc.GetTrace(); var keys = new List<string>(); var badLines = new List<BadLineInfo>(); // Search for source files within the project. trace.Verbose("Searching source files:"); string[] sourceFiles = Directory.GetFiles( TestUtil.GetProjectPath(project), "*.cs", SearchOption.AllDirectories); foreach (string sourceFile in sourceFiles) { // Skip files in the obj directory. if (sourceFile.Contains(StringUtil.Format("{0}obj{0}", Path.DirectorySeparatorChar))) { continue; } trace.Verbose($" {sourceFile}"); foreach (string line in File.ReadAllLines(sourceFile)) { // Search for calls to the StringUtil.Loc method within the line. const string Pattern = "StringUtil.Loc("; int searchIndex = 0; int patternIndex; while (searchIndex < line.Length && (patternIndex = line.IndexOf(Pattern, searchIndex)) >= 0) { // Bump the search index in preparation for the for the next iteration within the same line. searchIndex = patternIndex + Pattern.Length; // Extract the resource key. int keyStartIndex = patternIndex + Pattern.Length; int keyEndIndex; if (keyStartIndex + 2 < line.Length && // Key should start with a ", be followed by at least line[keyStartIndex] == '"' && // one character, and end with a ". (keyEndIndex = line.IndexOf('"', keyStartIndex + 1)) > 0) { // Remove the first and last double quotes. keyStartIndex++; keyEndIndex--; string key = line.Substring( startIndex: keyStartIndex, length: keyEndIndex - keyStartIndex + 1); if (ValidKeyRegex.IsMatch(key)) { // A valid key was extracted. keys.Add(key); continue; } } // Something went wrong. The pattern was found, but the resource key could not be determined. badLines.Add(new BadLineInfo { File = sourceFile, Line = line }); } } } // Load the strings. string stringsFile = Path.Combine(TestUtil.GetSrcPath(), "Misc", "layoutbin", "en-US", "strings.json"); Assert.True(File.Exists(stringsFile), $"File does not exist: {stringsFile}"); var resourceDictionary = IOUtil.LoadObject<Dictionary<string, object>>(stringsFile); // Find missing keys. string[] missingKeys = keys .Where(x => !resourceDictionary.ContainsKey(x)) .OrderBy(x => x) .ToArray(); if (missingKeys.Length > 0) { trace.Error("One or more resource keys missing from resources file:"); foreach (string missingKey in missingKeys) { trace.Error($" {missingKey}"); } } // Validate whether resource keys couldn't be interpreted. if (badLines.Count > 0) { trace.Error("Bad lines detected. Unable to interpret resource key(s)."); IEnumerable<IGrouping<string, BadLineInfo>> badLineGroupings = badLines .GroupBy(x => x.File) .OrderBy(x => x.Key) .ToArray(); foreach (IGrouping<string, BadLineInfo> badLineGrouping in badLineGroupings) { trace.Error($"File: {badLineGrouping.First().File}"); foreach (BadLineInfo badLine in badLineGrouping) { trace.Error($" Line: {badLine.Line}"); } } } Assert.True(missingKeys.Length == 0, $"One or more resource keys missing from resources files. Consult the trace log: {hc.TraceFileName}"); Assert.True(badLines.Count == 0, $"Unable to determine one or more resource keys. Consult the trace log: {hc.TraceFileName}"); } } private sealed class BadLineInfo { public string File { get; set; } public string Line { get; set; } } } }
using Microsoft.AspNetCore.Http; using OrchardCore.Environment.Shell; using Xunit; namespace OrchardCore.Tests.Shell { public class RunningShellTableTests { [Fact] public void NoShellsGiveNoMatch() { var table = new RunningShellTable(); var match = table.Match(new HostString("localhost"), "/yadda"); Assert.Null(match); } [Fact] public void DefaultShellMatchesByDefault() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName }; table.Add(settings); var match = table.Match(new HostString("localhost"), "/yadda"); Assert.Equal(settings, match); } [Fact] public void DefaultShellMatchesAllPortsByDefault() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName }; table.Add(settings); var match = table.Match(new HostString("localhost:443"), "/yadda"); Assert.Equal(settings, match); } [Fact] public void AnotherShellMatchesByHostHeader() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName }; var settingsA = new ShellSettings { Name = "Alpha", RequestUrlHost = "a.example.com" }; table.Add(settings); table.Add(settingsA); var match = table.Match(new HostString("a.example.com"), "/foo/bar"); Assert.Equal(settingsA, match); } [Fact] public void DefaultStillCatchesWhenOtherShellsMiss() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName }; var settingsA = new ShellSettings { Name = "Alpha", RequestUrlHost = "a.example.com" }; table.Add(settings); table.Add(settingsA); var match = table.Match(new HostString("b.example.com"), "/foo/bar"); Assert.Equal(settings, match); } [Fact] public void DefaultWontFallbackIfItHasCriteria() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName, RequestUrlHost = "www.example.com" }; var settingsA = new ShellSettings { Name = "Alpha", RequestUrlHost = "a.example.com" }; table.Add(settings); table.Add(settingsA); var match = table.Match(new HostString("b.example.com"), "/foo/bar"); Assert.Null(match); } [Fact] public void DefaultWillCatchRequestsIfItMatchesCriteria() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName, RequestUrlHost = "www.example.com" }; var settingsA = new ShellSettings { Name = "Alpha", RequestUrlHost = "a.example.com" }; table.Add(settings); table.Add(settingsA); var match = table.Match(new HostString("www.example.com"), "/foo/bar"); Assert.Equal(settings, match); } [Fact] public void NonDefaultCatchallWillFallbackIfNothingElseMatches() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName, RequestUrlHost = "www.example.com" }; var settingsA = new ShellSettings { Name = "Alpha" }; table.Add(settings); table.Add(settingsA); var match = table.Match(new HostString("b.example.com"), "/foo/bar"); Assert.Equal(settingsA, match); } [Fact] public void DefaultCatchallIsFallbackEvenWhenOthersAreUnqualified() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName }; var settingsA = new ShellSettings { Name = "Alpha" }; var settingsB = new ShellSettings { Name = "Beta", RequestUrlHost = "b.example.com" }; var settingsG = new ShellSettings { Name = "Gamma" }; table.Add(settings); table.Add(settingsA); table.Add(settingsB); table.Add(settingsG); var match = table.Match(new HostString("a.example.com"), "/foo/bar"); Assert.Equal(settings, match); } [Fact] public void PathAlsoCausesMatch() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName }; var settingsA = new ShellSettings { Name = "Alpha", RequestUrlPrefix = "foo" }; table.Add(settings); table.Add(settingsA); var match = table.Match(new HostString("a.example.com"), "/foo/bar"); Assert.Equal(settingsA, match); } [Fact] public void PathAndHostMustBothMatch() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName, RequestUrlHost = "www.example.com", }; var settingsA = new ShellSettings { Name = "Alpha", RequestUrlHost = "wiki.example.com", RequestUrlPrefix = "foo" }; var settingsB = new ShellSettings { Name = "Beta", RequestUrlHost = "wiki.example.com", RequestUrlPrefix = "bar" }; var settingsG = new ShellSettings { Name = "Gamma", RequestUrlHost = "wiki.example.com" }; var settingsD = new ShellSettings { Name = "Delta", RequestUrlPrefix = "Quux" }; table.Add(settings); table.Add(settingsA); table.Add(settingsB); table.Add(settingsG); table.Add(settingsD); Assert.Equal(settingsA, table.Match(new HostString("wiki.example.com"), "/foo/bar")); Assert.Equal(settingsB, table.Match(new HostString("wiki.example.com"), "/bar/foo")); Assert.Equal(settingsG, table.Match(new HostString("wiki.example.com"), "/")); Assert.Equal(settingsG, table.Match(new HostString("wiki.example.com"), "/baaz")); Assert.Equal(settings, table.Match(new HostString("www.example.com"), "/foo/bar")); Assert.Equal(settings, table.Match(new HostString("www.example.com"), "/bar/foo")); Assert.Equal(settings, table.Match(new HostString("www.example.com"), "/baaz")); Assert.Null(table.Match(new HostString("a.example.com"), "/foo/bar")); Assert.Equal(settingsG, table.Match(new HostString("wiki.example.com"), "/quux/quad")); Assert.Equal(settings, table.Match(new HostString("www.example.com"), "/quux/quad")); Assert.Equal(settingsD, table.Match(new HostString("a.example.com"), "/quux/quad")); Assert.Equal(settingsG, table.Match(new HostString("wiki.example.com"), "/yarg")); Assert.Equal(settings, table.Match(new HostString("www.example.com"), "/yarg")); Assert.Null(table.Match(new HostString("a.example.com"), "/yarg")); } [Fact] public void PathAndHostMustMatchOnFullUrl() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName, RequestUrlHost = "www.example.com", }; var settingsB = new ShellSettings { Name = "Beta", RequestUrlHost = "wiki.example.com", RequestUrlPrefix = "bar" }; var settingsG = new ShellSettings { Name = "Gamma", RequestUrlHost = "wiki.example.com" }; table.Add(settings); table.Add(settingsB); table.Add(settingsG); Assert.Equal(settingsB, table.Match(new HostString("wiki.example.com"), "/bar/foo")); Assert.Equal(settingsG, table.Match(new HostString("wiki.example.com"), "/")); Assert.Equal(settingsG, table.Match(new HostString("wiki.example.com"), "/baaz")); Assert.Equal(settingsG, table.Match(new HostString("wiki.example.com"), "/barbaz")); } [Fact] public void PathAloneWillMatch() { var table = new RunningShellTable(); var settingsA = new ShellSettings { Name = "Alpha", RequestUrlPrefix = "foo" }; table.Add(settingsA); Assert.Equal(settingsA, table.Match(new HostString("wiki.example.com"), "/foo/bar")); Assert.Null(table.Match(new HostString("wiki.example.com"), "/bar/foo")); } [Fact] public void HostNameMatchesRightmostIfRequestIsLonger() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName }; var settingsA = new ShellSettings { Name = "Alpha", RequestUrlHost = "example.com" }; table.Add(settings); table.Add(settingsA); Assert.Equal(settings, table.Match(new HostString("www.example.com"), "/foo/bar")); Assert.Equal(settings, table.Match(new HostString("wiki.example.com"), "/foo/bar")); Assert.Equal(settingsA, table.Match(new HostString("example.com"), "/foo/bar")); Assert.Equal(settings, table.Match(new HostString("localhost"), "/foo/bar")); } [Fact] public void HostNameMatchesRightmostIfStar() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName }; var settingsA = new ShellSettings { Name = "Alpha", RequestUrlHost = "*.example.com" }; table.Add(settings); table.Add(settingsA); Assert.Equal(settingsA, table.Match(new HostString("www.example.com"), "/foo/bar")); Assert.Equal(settingsA, table.Match(new HostString("wiki.example.com"), "/foo/bar")); Assert.Equal(settingsA, table.Match(new HostString("example.com"), "/foo/bar")); Assert.Equal(settings, table.Match(new HostString("localhost"), "/foo/bar")); } [Fact] public void LongestMatchingHostHasPriority() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName }; var settingsA = new ShellSettings { Name = "Alpha", RequestUrlHost = "www.example.com" }; var settingsB = new ShellSettings { Name = "Beta", RequestUrlHost = "*.example.com" }; var settingsG = new ShellSettings { Name = "Gamma", RequestUrlHost = "wiki.example.com" }; table.Add(settings); table.Add(settingsA); table.Add(settingsB); table.Add(settingsG); Assert.Equal(settingsA, table.Match(new HostString("www.example.com"), "/foo/bar")); Assert.Equal(settingsG, table.Match(new HostString("wiki.example.com"), "/foo/bar")); Assert.Equal(settingsB, table.Match(new HostString("username.example.com"), "/foo/bar")); Assert.Equal(settings, table.Match(new HostString("localhost"), "/foo/bar")); } [Fact] public void ShellNameUsedToDistinctThingsAsTheyAreAdded() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName }; var settingsA = new ShellSettings { Name = "Alpha", RequestUrlHost = "removed.example.com" }; var settingsB = new ShellSettings { Name = "Alpha", RequestUrlHost = "added.example.com" }; table.Add(settings); table.Add(settingsA); table.Remove(settingsA); table.Add(settingsB); Assert.Equal(settings, table.Match(new HostString("removed.example.com"), "/foo/bar")); Assert.Equal(settingsB, table.Match(new HostString("added.example.com"), "/foo/bar")); Assert.Equal(settings, table.Match(new HostString("localhost"), "/foo/bar")); } [Fact] public void MultipleHostsOnShellAreAdded() { var table = new RunningShellTable(); var settingsAlpha = new ShellSettings { Name = "Alpha", RequestUrlHost = "a.example.com,b.example.com" }; var settingsBeta = new ShellSettings { Name = "Beta", RequestUrlHost = "c.example.com,d.example.com,e.example.com" }; table.Add(settingsAlpha); table.Add(settingsBeta); Assert.Equal(settingsAlpha, table.Match(new HostString("a.example.com"), "/foo/bar")); Assert.Equal(settingsAlpha, table.Match(new HostString("b.example.com"), "/foo/bar")); Assert.Equal(settingsBeta, table.Match(new HostString("c.example.com"), "/foo/bar")); Assert.Equal(settingsBeta, table.Match(new HostString("d.example.com"), "/foo/bar")); Assert.Equal(settingsBeta, table.Match(new HostString("e.example.com"), "/foo/bar")); } [Fact] public void HostContainsSpaces() { var table = new RunningShellTable(); var settingsAlpha = new ShellSettings { Name = "Alpha", RequestUrlHost = " a.example.com, b.example.com " }; table.Add(settingsAlpha); Assert.Equal(settingsAlpha, table.Match(new HostString("a.example.com"), "/foo/bar")); Assert.Equal(settingsAlpha, table.Match(new HostString("b.example.com"), "/foo/bar")); } [Fact] public void PortAreIgnoredIfNotSetInSettings() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName }; var settingsA = new ShellSettings { Name = "Alpha", RequestUrlHost = "a.example.com" }; table.Add(settings); table.Add(settingsA); Assert.Equal(settingsA, table.Match(new HostString("a.example.com:80"), "/foo/bar")); Assert.Equal(settings, table.Match(new HostString("foo.com:80"), "/foo/bar")); } [Fact] public void ShouldNotFallBackToDefault() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName }; var settingsA = new ShellSettings { Name = "Alpha", RequestUrlHost = "a.example.com" }; table.Add(settings); table.Add(settingsA); Assert.Equal(settingsA, table.Match(new HostString("a.example.com"), "/foo/bar")); Assert.Equal(settings, table.Match(new HostString("foo.com"), "/foo/bar")); Assert.Null(table.Match(new HostString("foo.com"), "/foo/bar", false)); } [Fact] public void PortAreNotIgnoredIfSetInSettings() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName }; var settingsA = new ShellSettings { Name = "Alpha", RequestUrlHost = "a.example.com:80" }; var settingsB = new ShellSettings { Name = "Beta", RequestUrlHost = "a.example.com:8080" }; table.Add(settings); table.Add(settingsA); table.Add(settingsB); Assert.Equal(settingsA, table.Match(new HostString("a.example.com:80"), "/foo/bar")); Assert.Equal(settingsB, table.Match(new HostString("a.example.com:8080"), "/foo/bar")); Assert.Equal(settings, table.Match(new HostString("a.example.com:123"), "/foo/bar")); Assert.Null(table.Match(new HostString("a.example.com:123"), "/foo/bar", false)); } [Fact] public void IPv6AddressesAreSupported() { var table = new RunningShellTable(); var settings = new ShellSettings { Name = ShellHelper.DefaultShellName }; var settingsA = new ShellSettings { Name = "Alpha", RequestUrlHost = "[::abc]" }; var settingsB = new ShellSettings { Name = "Beta", RequestUrlHost = "[::1]:123" }; table.Add(settings); table.Add(settingsA); table.Add(settingsB); Assert.Equal(settingsA, table.Match(new HostString("::abc"), "/foo/bar")); Assert.Equal(settingsA, table.Match(new HostString("[::abc]"), "/foo/bar")); Assert.Equal(settingsA, table.Match(new HostString("[::ABC]"), "/foo/bar")); Assert.Equal(settingsA, table.Match(new HostString("[::abc]:"), "/foo/bar")); Assert.Equal(settingsA, table.Match(new HostString("[::abc]:123"), "/foo/bar")); Assert.Equal(settingsB, table.Match(new HostString("[::1]:123"), "/foo/bar")); Assert.Equal(settings, table.Match(new HostString("[::1]:321"), "/foo/bar")); Assert.Equal(settings, table.Match(new HostString("[::1]:"), "/foo/bar")); Assert.Equal(settings, table.Match(new HostString("[::1]"), "/foo/bar")); Assert.Equal(settings, table.Match(new HostString("::1"), "/foo/bar")); Assert.Equal(settings, table.Match(new HostString(":"), "/foo/bar")); Assert.Null(table.Match(new HostString("::1"), "/foo/bar", false)); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using System; namespace NPOI.POIFS.Storage { /** * Wraps a <c>byte</c> array and provides simple data input access. * Internally, this class maintains a buffer read index, so that for the most part, primitive * data can be read in a data-input-stream-like manner.<p/> * * Note - the calling class should call the {@link #available()} method to detect end-of-buffer * and Move to the next data block when the current is exhausted. * For optimisation reasons, no error handling is performed in this class. Thus, mistakes in * calling code ran may raise ugly exceptions here, like {@link ArrayIndexOutOfBoundsException}, * etc .<p/> * * The multi-byte primitive input methods ({@link #readUshortLE()}, {@link #readIntLE()} and * {@link #readLongLE()}) have corresponding 'spanning Read' methods which (when required) perform * a read across the block boundary. These spanning read methods take the previous * {@link DataInputBlock} as a parameter. * Reads of larger amounts of data (into <c>byte</c> array buffers) must be managed by the caller * since these could conceivably involve more than two blocks. * * @author Josh Micich */ public class DataInputBlock { /** * Possibly any size (usually 512K or 64K). Assumed to be at least 8 bytes for all blocks * before the end of the stream. The last block in the stream can be any size except zero. */ private byte[] _buf; private int _readIndex; private int _maxIndex; internal DataInputBlock(byte[] data, int startOffset) { _buf = data; _readIndex = startOffset; _maxIndex = _buf.Length; } public int Available() { return _maxIndex - _readIndex; } public int ReadUByte() { return _buf[_readIndex++] & 0xFF; } /** * Reads a <c>short</c> which was encoded in <em>little endian</em> format. */ public int ReadUshortLE() { int i = _readIndex; int b0 = _buf[i++] & 0xFF; int b1 = _buf[i++] & 0xFF; _readIndex = i; return (b1 << 8) + (b0 << 0); } /** * Reads a <c>short</c> which spans the end of <c>prevBlock</c> and the start of this block. */ public int ReadUshortLE(DataInputBlock prevBlock) { // simple case - will always be one byte in each block int i = prevBlock._buf.Length - 1; int b0 = prevBlock._buf[i] & 0xFF; int b1 = _buf[_readIndex++] & 0xFF; return (b1 << 8) + (b0 << 0); } /** * Reads an <c>int</c> which was encoded in <em>little endian</em> format. */ public int ReadIntLE() { int i = _readIndex; int b0 = _buf[i++] & 0xFF; int b1 = _buf[i++] & 0xFF; int b2 = _buf[i++] & 0xFF; int b3 = _buf[i++] & 0xFF; _readIndex = i; return (b3 << 24) + (b2 << 16) + (b1 << 8) + (b0 << 0); } /** * Reads an <c>int</c> which spans the end of <c>prevBlock</c> and the start of this block. */ public int ReadIntLE(DataInputBlock prevBlock, int prevBlockAvailable) { byte[] buf = new byte[4]; ReadSpanning(prevBlock, prevBlockAvailable, buf); int b0 = buf[0] & 0xFF; int b1 = buf[1] & 0xFF; int b2 = buf[2] & 0xFF; int b3 = buf[3] & 0xFF; return (b3 << 24) + (b2 << 16) + (b1 << 8) + (b0 << 0); } /** * Reads a <c>long</c> which was encoded in <em>little endian</em> format. */ public long ReadLongLE() { int i = _readIndex; int b0 = _buf[i++] & 0xFF; int b1 = _buf[i++] & 0xFF; int b2 = _buf[i++] & 0xFF; int b3 = _buf[i++] & 0xFF; int b4 = _buf[i++] & 0xFF; int b5 = _buf[i++] & 0xFF; int b6 = _buf[i++] & 0xFF; int b7 = _buf[i++] & 0xFF; _readIndex = i; return (((long)b7 << 56) + ((long)b6 << 48) + ((long)b5 << 40) + ((long)b4 << 32) + ((long)b3 << 24) + (b2 << 16) + (b1 << 8) + (b0 << 0)); } /** * Reads a <c>long</c> which spans the end of <c>prevBlock</c> and the start of this block. */ public long ReadLongLE(DataInputBlock prevBlock, int prevBlockAvailable) { byte[] buf = new byte[8]; ReadSpanning(prevBlock, prevBlockAvailable, buf); int b0 = buf[0] & 0xFF; int b1 = buf[1] & 0xFF; int b2 = buf[2] & 0xFF; int b3 = buf[3] & 0xFF; int b4 = buf[4] & 0xFF; int b5 = buf[5] & 0xFF; int b6 = buf[6] & 0xFF; int b7 = buf[7] & 0xFF; return (((long)b7 << 56) + ((long)b6 << 48) + ((long)b5 << 40) + ((long)b4 << 32) + ((long)b3 << 24) + (b2 << 16) + (b1 << 8) + (b0 << 0)); } /** * Reads a small amount of data from across the boundary between two blocks. * The {@link #_readIndex} of this (the second) block is updated accordingly. * Note- this method (and other code) assumes that the second {@link DataInputBlock} * always is big enough to complete the read without being exhausted. */ private void ReadSpanning(DataInputBlock prevBlock, int prevBlockAvailable, byte[] buf) { Array.Copy(prevBlock._buf, prevBlock._readIndex, buf, 0, prevBlockAvailable); int secondReadLen = buf.Length - prevBlockAvailable; Array.Copy(_buf, 0, buf, prevBlockAvailable, secondReadLen); _readIndex = secondReadLen; } /** * Reads <c>len</c> bytes from this block into the supplied buffer. */ public void ReadFully(byte[] buf, int off, int len) { Array.Copy(_buf, _readIndex, buf, off, len); _readIndex += len; } } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Model { /// <summary> /// PipelineFolderImpl /// </summary> [DataContract(Name = "PipelineFolderImpl")] public partial class PipelineFolderImpl : IEquatable<PipelineFolderImpl>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="PipelineFolderImpl" /> class. /// </summary> /// <param name="_class">_class.</param> /// <param name="displayName">displayName.</param> /// <param name="fullName">fullName.</param> /// <param name="name">name.</param> /// <param name="organization">organization.</param> /// <param name="numberOfFolders">numberOfFolders.</param> /// <param name="numberOfPipelines">numberOfPipelines.</param> public PipelineFolderImpl(string _class = default(string), string displayName = default(string), string fullName = default(string), string name = default(string), string organization = default(string), int numberOfFolders = default(int), int numberOfPipelines = default(int)) { this.Class = _class; this.DisplayName = displayName; this.FullName = fullName; this.Name = name; this.Organization = organization; this.NumberOfFolders = numberOfFolders; this.NumberOfPipelines = numberOfPipelines; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name = "_class", EmitDefaultValue = false)] public string Class { get; set; } /// <summary> /// Gets or Sets DisplayName /// </summary> [DataMember(Name = "displayName", EmitDefaultValue = false)] public string DisplayName { get; set; } /// <summary> /// Gets or Sets FullName /// </summary> [DataMember(Name = "fullName", EmitDefaultValue = false)] public string FullName { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name = "name", EmitDefaultValue = false)] public string Name { get; set; } /// <summary> /// Gets or Sets Organization /// </summary> [DataMember(Name = "organization", EmitDefaultValue = false)] public string Organization { get; set; } /// <summary> /// Gets or Sets NumberOfFolders /// </summary> [DataMember(Name = "numberOfFolders", EmitDefaultValue = false)] public int NumberOfFolders { get; set; } /// <summary> /// Gets or Sets NumberOfPipelines /// </summary> [DataMember(Name = "numberOfPipelines", EmitDefaultValue = false)] public int NumberOfPipelines { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class PipelineFolderImpl {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" DisplayName: ").Append(DisplayName).Append("\n"); sb.Append(" FullName: ").Append(FullName).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Organization: ").Append(Organization).Append("\n"); sb.Append(" NumberOfFolders: ").Append(NumberOfFolders).Append("\n"); sb.Append(" NumberOfPipelines: ").Append(NumberOfPipelines).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as PipelineFolderImpl); } /// <summary> /// Returns true if PipelineFolderImpl instances are equal /// </summary> /// <param name="input">Instance of PipelineFolderImpl to be compared</param> /// <returns>Boolean</returns> public bool Equals(PipelineFolderImpl input) { if (input == null) { return false; } return ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ) && ( this.DisplayName == input.DisplayName || (this.DisplayName != null && this.DisplayName.Equals(input.DisplayName)) ) && ( this.FullName == input.FullName || (this.FullName != null && this.FullName.Equals(input.FullName)) ) && ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ) && ( this.Organization == input.Organization || (this.Organization != null && this.Organization.Equals(input.Organization)) ) && ( this.NumberOfFolders == input.NumberOfFolders || this.NumberOfFolders.Equals(input.NumberOfFolders) ) && ( this.NumberOfPipelines == input.NumberOfPipelines || this.NumberOfPipelines.Equals(input.NumberOfPipelines) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Class != null) { hashCode = (hashCode * 59) + this.Class.GetHashCode(); } if (this.DisplayName != null) { hashCode = (hashCode * 59) + this.DisplayName.GetHashCode(); } if (this.FullName != null) { hashCode = (hashCode * 59) + this.FullName.GetHashCode(); } if (this.Name != null) { hashCode = (hashCode * 59) + this.Name.GetHashCode(); } if (this.Organization != null) { hashCode = (hashCode * 59) + this.Organization.GetHashCode(); } hashCode = (hashCode * 59) + this.NumberOfFolders.GetHashCode(); hashCode = (hashCode * 59) + this.NumberOfPipelines.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// LoadBalancersOperations operations. /// </summary> public partial interface ILoadBalancersOperations { /// <summary> /// Deletes the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<LoadBalancer>> GetWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<LoadBalancer>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<LoadBalancer>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<LoadBalancer>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<LoadBalancer>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; using Microsoft.TeamFoundation.Build.WebApi; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Worker; using Microsoft.VisualStudio.Services.Agent.Worker.Build; using Microsoft.VisualStudio.Services.Agent.Worker.Release; using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines; using Moq; using Xunit; using Agent.Sdk; namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker.Build { public sealed class BuildJobExtensionL0 { private Mock<IExecutionContext> _ec; private Mock<IExtensionManager> _extensionManager; private Mock<ISourceProvider> _sourceProvider; private Mock<IBuildDirectoryManager> _buildDirectoryManager; private Mock<IConfigurationStore> _configurationStore; private Variables _variables; private string stubWorkFolder; private BuildJobExtension buildJobExtension; private List<Pipelines.JobStep> steps; private List<Pipelines.RepositoryResource> repositories { get; set; } private Dictionary<string, string> jobSettings { get; set; } private const string CollectionId = "31ffacb8-b468-4e60-b2f9-c50ce437da92"; private const string DefinitionId = "1234"; private Pipelines.WorkspaceOptions _workspaceOptions; private char directorySeparator = Path.DirectorySeparatorChar; [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public void CheckSingleRepoWithoutPathInput() { using (TestHostContext tc = Setup(createWorkDirectory: false, checkOutConfig: CheckoutConfigType.SingleCheckoutDefaultPath)) { buildJobExtension.InitializeJobExtension(_ec.Object, steps, _workspaceOptions); var repoLocalPath = _ec.Object.Variables.Get(Constants.Variables.Build.RepoLocalPath); Assert.NotNull(repoLocalPath); Assert.Equal(Path.Combine(stubWorkFolder, $"1{directorySeparator}s"), repoLocalPath); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public void CheckSingleRepoWithCustomPaths() { using (TestHostContext tc = Setup(createWorkDirectory: false, checkOutConfig: CheckoutConfigType.SingleCheckoutCustomPath, pathToSelfRepo: "s/CustomApplicationFolder")) { buildJobExtension.InitializeJobExtension(_ec.Object, steps, _workspaceOptions); var repoLocalPath = _ec.Object.Variables.Get(Constants.Variables.Build.RepoLocalPath); Assert.NotNull(repoLocalPath); Assert.Equal(Path.Combine(stubWorkFolder, $"1{directorySeparator}s"), repoLocalPath); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public void CheckMultiRepoWithoutPathInput() { using (TestHostContext tc = Setup(createWorkDirectory: false, checkOutConfig: CheckoutConfigType.MultiCheckoutDefaultPath)) { buildJobExtension.InitializeJobExtension(_ec.Object, steps, _workspaceOptions); var repoLocalPath = _ec.Object.Variables.Get(Constants.Variables.Build.RepoLocalPath); Assert.NotNull(repoLocalPath); Assert.Equal(Path.Combine(stubWorkFolder, $"1{directorySeparator}s"), repoLocalPath); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public void CheckMultiRepoWithPathInputToCustomPath() { using (TestHostContext tc = Setup(createWorkDirectory: false, checkOutConfig: CheckoutConfigType.MultiCheckoutCustomPath, pathToSelfRepo: "s/CustomApplicationFolder")) { buildJobExtension.InitializeJobExtension(_ec.Object, steps, _workspaceOptions); var repoLocalPath = _ec.Object.Variables.Get(Constants.Variables.Build.RepoLocalPath); Assert.NotNull(repoLocalPath); Assert.Equal(Path.Combine(stubWorkFolder, $"1{directorySeparator}s{directorySeparator}App"), repoLocalPath); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public void CheckMultiRepoWithPathInputToDefaultPath() { using (TestHostContext tc = Setup(createWorkDirectory: false, checkOutConfig: CheckoutConfigType.MultiCheckoutCustomPath, pathToSelfRepo: "s/App")) { buildJobExtension.InitializeJobExtension(_ec.Object, steps, _workspaceOptions); var repoLocalPath = _ec.Object.Variables.Get(Constants.Variables.Build.RepoLocalPath); Assert.NotNull(repoLocalPath); Assert.Equal(Path.Combine(stubWorkFolder, $"1{directorySeparator}s"), repoLocalPath); } } private TestHostContext Setup([CallerMemberName] string name = "", bool createWorkDirectory = true, CheckoutConfigType checkOutConfig = CheckoutConfigType.SingleCheckoutDefaultPath, string pathToSelfRepo = "") { bool isMulticheckoutScenario = checkOutConfig == CheckoutConfigType.MultiCheckoutCustomPath || checkOutConfig == CheckoutConfigType.MultiCheckoutDefaultPath; bool isCustomPathScenario = checkOutConfig == CheckoutConfigType.SingleCheckoutCustomPath || checkOutConfig == CheckoutConfigType.MultiCheckoutCustomPath; TestHostContext hc = new TestHostContext(this, name); this.stubWorkFolder = hc.GetDirectory(WellKnownDirectory.Work); if (createWorkDirectory) { Directory.CreateDirectory(this.stubWorkFolder); } _ec = new Mock<IExecutionContext>(); _extensionManager = new Mock<IExtensionManager>(); _sourceProvider = new Mock<ISourceProvider>(); _buildDirectoryManager = new Mock<IBuildDirectoryManager>(); _workspaceOptions = new Pipelines.WorkspaceOptions(); _configurationStore = new Mock<IConfigurationStore>(); _configurationStore.Setup(store => store.GetSettings()).Returns(new AgentSettings { WorkFolder = this.stubWorkFolder }); steps = new List<Pipelines.JobStep>(); var selfCheckoutTask = new Pipelines.TaskStep() { Reference = new Pipelines.TaskStepDefinitionReference() { Id = Guid.Parse("6d15af64-176c-496d-b583-fd2ae21d4df4"), Name = "Checkout", Version = "1.0.0" } }; selfCheckoutTask.Inputs.Add("repository", "self"); if (isCustomPathScenario) { selfCheckoutTask.Inputs.Add("path", pathToSelfRepo); } steps.Add(selfCheckoutTask); // Setup second checkout only for multicheckout jobs if (isMulticheckoutScenario) { var anotherCheckoutTask = new Pipelines.TaskStep() { Reference = new Pipelines.TaskStepDefinitionReference() { Id = Guid.Parse("6d15af64-176c-496d-b583-fd2ae21d4df4"), Name = "Checkout", Version = "1.0.0" } }; anotherCheckoutTask.Inputs.Add("repository", "BuildRepo"); anotherCheckoutTask.Inputs.Add("path", "s/BuildRepo"); steps.Add(anotherCheckoutTask); } hc.SetSingleton(_buildDirectoryManager.Object); hc.SetSingleton(_extensionManager.Object); hc.SetSingleton(_configurationStore.Object); var buildVariables = GetBuildVariables(); _variables = new Variables(hc, buildVariables, out _); _ec.Setup(x => x.Variables).Returns(_variables); repositories = new List<Pipelines.RepositoryResource>(); repositories.Add(GetRepository(hc, "self", "App", "App")); repositories.Add(GetRepository(hc, "repo2", "BuildRepo", "BuildRepo")); _ec.Setup(x => x.Repositories).Returns(repositories); jobSettings = new Dictionary<string, string>(); jobSettings.Add(WellKnownJobSettings.HasMultipleCheckouts, isMulticheckoutScenario.ToString()); _ec.Setup(x => x.JobSettings).Returns(jobSettings); _ec.Setup(x => x.SetVariable(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<bool>(), It.IsAny<bool>(), It.IsAny<bool>())) .Callback((string varName, string varValue, bool isSecret, bool isOutput, bool isFilePath, bool isReadOnly) => { _variables.Set(varName, varValue, false); }); _extensionManager.Setup(x => x.GetExtensions<ISourceProvider>()) .Returns(new List<ISourceProvider> { _sourceProvider.Object }); _sourceProvider.Setup(x => x.RepositoryType) .Returns(Pipelines.RepositoryTypes.ExternalGit); _buildDirectoryManager.Setup(x => x.PrepareDirectory(_ec.Object, repositories, _workspaceOptions)) .Returns(new TrackingConfig(_ec.Object, repositories, 1)); buildJobExtension = new BuildJobExtension(); buildJobExtension.Initialize(hc); return hc; } private Dictionary<string, VariableValue> GetBuildVariables() { var buildVariables = new Dictionary<string, VariableValue>(); buildVariables.Add(Constants.Variables.Build.SyncSources, Boolean.TrueString); buildVariables.Add(Constants.Variables.System.CollectionId, CollectionId); buildVariables.Add(Constants.Variables.System.DefinitionId, DefinitionId); return buildVariables; } private Pipelines.RepositoryResource GetRepository(TestHostContext hostContext, String alias, String relativePath, String Name) { var workFolder = hostContext.GetDirectory(WellKnownDirectory.Work); var repo = new Pipelines.RepositoryResource() { Alias = alias, Type = Pipelines.RepositoryTypes.ExternalGit, Id = alias, Url = new Uri($"http://contoso.visualstudio.com/{Name}"), Name = Name, }; repo.Properties.Set<string>(Pipelines.RepositoryPropertyNames.Path, Path.Combine(workFolder, "1", relativePath)); return repo; } private enum CheckoutConfigType { MultiCheckoutDefaultPath = 0, MultiCheckoutCustomPath = 1, SingleCheckoutDefaultPath = 2, SingleCheckoutCustomPath = 3, } } }
using System; using System.IO; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Net; using System.Configuration; namespace DesappstreStudio.CouchDB.Bulk { /// <summary> /// CouchDB Bulk Loader from file. /// Data contained in file must be in JSON valid format /// </summary> public class BulkLoader : object { // private long bulk_operations; // private int bulk_errors; // private int block_limit; // private DateTime init_time; // private static object Sync = new object(); /// <summary> /// URL to _bulk_docs operations /// </summary> private string CouchDBURL { get; set; } /// <summary> /// Load data from a file to CouchDB /// </summary> /// <param name="file">File that contains json valid data</param> /// <param name="rows">Inserts per operation</param> public BulkLoader(string file, int limit) : base() { this.FormatCouchDBURL(); this.init_time = DateTime.Now; this.block_limit = limit; List<string> lines = new List<string>(); List<Task> tasks = new List<Task>(); FileStream fs = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); BufferedStream bs = new BufferedStream(fs); using(StreamReader sr = new StreamReader(bs)) { int count = 0; string line = string.Empty; while((line = sr.ReadLine()) != null) { lines.Add(line); count++; if(count == limit) { List<string> copy = new List<string>(lines); Task bulk_task = this.CreateBulkTask(copy); tasks.Add(bulk_task); count = 0; lines.Clear(); } } if(lines.Count != 0) { Task bulk_task = this.CreateBulkTask(lines); tasks.Add(bulk_task); } } Task.WaitAll(tasks.ToArray()); } /// <summary> /// Build the URL based on the App.config data /// </summary> private void FormatCouchDBURL() { string base_url = ConfigurationManager.AppSettings["couchdb_server_baseurl"]; string database = ConfigurationManager.AppSettings["couchdb_server_db"]; this.CouchDBURL = string.Format("{0}/{1}/_bulk_docs", base_url, database); } /// <summary> /// Create an async operation in which the data are loaded into CouchDB /// </summary> /// <param name="lines"></param> /// <returns></returns> private Task CreateBulkTask(List<string> lines) { Task bulk_task = new Task(() => { this.Bulk(lines); }); bulk_task.Start(); return bulk_task; } /// <summary> /// HTTP Bulk process /// </summary> /// <param name="lines">JSON docs to upload</param> private void Bulk(List<string> lines) { HttpWebRequest request = (HttpWebRequest) WebRequest.Create(this.CouchDBURL); request.ContentType = "application/json"; request.Method = "POST"; request.ProtocolVersion = HttpVersion.Version11; string documents = string.Empty; foreach(string line in lines) { documents = string.IsNullOrEmpty(documents) ? line : string.Concat(documents, ", ", line); } string content = string.Concat("{ \"docs\" : [ ", documents, " ] }"); StreamWriter writer = new StreamWriter(request.GetRequestStream()); writer.Write(content); writer.Close(); writer.Dispose(); try { HttpWebResponse response = (HttpWebResponse) request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string response_content = reader.ReadToEnd(); } catch(WebException) { // GetResponse error. Interlocked.Increment(ref bulk_errors); } // TODO. Process response data lock(BulkLoader.Sync) { bulk_operations += lines.Count; this.ShowBulkState(); } } /// <summary> /// Show bulk state info during operations /// </summary> private void ShowBulkState() { TimeSpan span = (DateTime.Now - init_time); if(bulk_operations == block_limit) { string message = string.Format("JSON objects loaded: {0}\r\nBulk operation running: {1}\r\nBulk errors: {2}", bulk_operations.ToString("N0"), span.ToString(), bulk_errors.ToString("N0")); Console.Write(message); } else { Console.CursorTop -= 2; Console.CursorLeft = "JSON objects loaded: ".Length; Console.Write(bulk_operations.ToString("N0")); Console.CursorTop++; Console.CursorLeft = "Bulk operation running: ".Length; Console.Write(span.ToString()); Console.CursorTop++; Console.CursorLeft = "Bulk errors: ".Length; Console.Write(bulk_errors.ToString("N0")); } } /// <summary> /// Stating point... /// </summary> /// <param name="args"></param> public static void Main(string[] args) { Console.CursorVisible = false; if(args.Length == 1) { if(!File.Exists(args[0])) { Console.WriteLine("File doen't exists. Check file path."); Environment.Exit(-1); } int block = Convert.ToInt32(ConfigurationManager.AppSettings["couchdb_server_block"]); BulkLoader bulkOP = new BulkLoader(args[0], block); } else { Environment.Exit(-1); } } } }
/* ==================================================================== */ using System; using System.Xml; using System.Text; namespace Oranikle.Report.Engine { ///<summary> /// The width of the border. Expressions for all sides as well as default expression. ///</summary> [Serializable] public class StyleBorderWidth : ReportLink { Expression _Default; //(Size) Width of the border (unless overridden for a specific side) // Borders are centered on the edge of the object // Default: 1 pt Max: 20 pt Min: 0.25 pt Expression _Left; //(Size) Width of the left border. Max: 20 pt Min: 0.25 pt Expression _Right; //(Size) Width of the right border. Max: 20 pt Min: 0.25 pt Expression _Top; //(Size) Width of the top border. Max: 20 pt Min: 0.25 pt Expression _Bottom; //(Size) Width of the bottom border. Max: 20 pt Min: 0.25 pt public StyleBorderWidth(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p) { _Default=null; _Left=null; // Loop thru all the child nodes foreach(XmlNode xNodeLoop in xNode.ChildNodes) { if (xNodeLoop.NodeType != XmlNodeType.Element) continue; switch (xNodeLoop.Name) { case "Default": _Default = new Expression(r, this, xNodeLoop, ExpressionType.ReportUnit); break; case "Left": _Left = new Expression(r, this, xNodeLoop, ExpressionType.ReportUnit); break; case "Right": _Right = new Expression(r, this, xNodeLoop, ExpressionType.ReportUnit); break; case "Top": _Top = new Expression(r, this, xNodeLoop, ExpressionType.ReportUnit); break; case "Bottom": _Bottom = new Expression(r, this, xNodeLoop, ExpressionType.ReportUnit); break; default: // don't know this element - log it OwnerReport.rl.LogError(4, "Unknown BorderWidth element '" + xNodeLoop.Name + "' ignored."); break; } } } // Handle parsing of function in final pass override public void FinalPass() { if (_Default != null) _Default.FinalPass(); if (_Left != null) _Left.FinalPass(); if (_Right != null) _Right.FinalPass(); if (_Top != null) _Top.FinalPass(); if (_Bottom != null) _Bottom.FinalPass(); return; } // Generate a CSS string from the specified styles public string GetCSS(Report rpt, Row row, bool bDefaults) { StringBuilder sb = new StringBuilder(); if (_Default != null) sb.AppendFormat("border-width:{0};",_Default.EvaluateString(rpt, row)); else if (bDefaults) sb.Append("border-width:1pt;"); if (_Left != null) sb.AppendFormat("border-left-width:{0};",_Left.EvaluateString(rpt, row)); if (_Right != null) sb.AppendFormat("border-right-width:{0};",_Right.EvaluateString(rpt, row)); if (_Top != null) sb.AppendFormat("border-top-width:{0};",_Top.EvaluateString(rpt, row)); if (_Bottom != null) sb.AppendFormat("border-bottom-width:{0};",_Bottom.EvaluateString(rpt, row)); return sb.ToString(); } public bool IsConstant() { bool rc = true; if (_Default != null) rc = _Default.IsConstant(); if (!rc) return false; if (_Left != null) rc = _Left.IsConstant(); if (!rc) return false; if (_Right != null) rc = _Right.IsConstant(); if (!rc) return false; if (_Top != null) rc = _Top.IsConstant(); if (!rc) return false; if (_Bottom != null) rc = _Bottom.IsConstant(); return rc; } static public string GetCSSDefaults() { return "border-width:1pt;"; } public Expression Default { get { return _Default; } set { _Default = value; } } public float EvalDefault(Report rpt, Row r) // return points { if (_Default == null) return 1; string sw; sw = _Default.EvaluateString(rpt, r); RSize rs = new RSize(this.OwnerReport, sw); return rs.Points; } public Expression Left { get { return _Left; } set { _Left = value; } } public float EvalLeft(Report rpt, Row r) // return points { if (_Left == null) return EvalDefault(rpt, r); string sw = _Left.EvaluateString(rpt, r); RSize rs = new RSize(this.OwnerReport, sw); return rs.Points; } public Expression Right { get { return _Right; } set { _Right = value; } } public float EvalRight(Report rpt, Row r) // return points { if (_Right == null) return EvalDefault(rpt, r); string sw = _Right.EvaluateString(rpt, r); RSize rs = new RSize(this.OwnerReport, sw); return rs.Points; } public Expression Top { get { return _Top; } set { _Top = value; } } public float EvalTop(Report rpt, Row r) // return points { if (_Top == null) return EvalDefault(rpt, r); string sw = _Top.EvaluateString(rpt, r); RSize rs = new RSize(this.OwnerReport, sw); return rs.Points; } public Expression Bottom { get { return _Bottom; } set { _Bottom = value; } } public float EvalBottom(Report rpt, Row r) // return points { if (_Bottom == null) return EvalDefault(rpt, r); string sw = _Bottom.EvaluateString(rpt, r); RSize rs = new RSize(this.OwnerReport, sw); return rs.Points; } } }
//----------------------------------------------------------------------- // <copyright file="NativeSession.cs" company="Google"> // // Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCoreInternal { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using GoogleARCore; using UnityEngine; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Internal")] public class NativeSession { private IntPtr m_SessionHandle = IntPtr.Zero; private IntPtr m_FrameHandle = IntPtr.Zero; private IntPtr m_PointCloudHandle = IntPtr.Zero; private float m_LastReleasedPointcloudTimestamp = 0.0f; private TrackableManager m_TrackableManager = null; private Dictionary<IntPtr, int> m_AcquiredHandleCounts = new Dictionary<IntPtr, int>( new IntPtrEqualityComparer()); public NativeSession(IntPtr sessionHandle, IntPtr frameHandle) { m_SessionHandle = sessionHandle; m_FrameHandle = frameHandle; m_TrackableManager = new TrackableManager(this); AnchorApi = new AnchorApi(this); CameraApi = new CameraApi(this); CameraMetadataApi = new CameraMetadataApi(this); FrameApi = new FrameApi(this); HitTestApi = new HitTestApi(this); ImageApi = new ImageApi(this); LightEstimateApi = new LightEstimateApi(this); PlaneApi = new PlaneApi(this); PointApi = new PointApi(this); PointCloudApi = new PointCloudApi(this); PoseApi = new PoseApi(this); SessionApi = new SessionApi(this); SessionConfigApi = new SessionConfigApi(this); TrackableApi = new TrackableApi(this); TrackableListApi = new TrackableListApi(this); } public IntPtr SessionHandle { get { return m_SessionHandle; } } public IntPtr FrameHandle { get { return m_FrameHandle; } } public IntPtr PointCloudHandle { get { return m_PointCloudHandle; } } public bool IsPointCloudNew { get { // TODO (b/73256094): Remove when fixed. if (LifecycleManager.Instance.SessionStatus != SessionStatus.Tracking) { var previousLastTimestamp = m_LastReleasedPointcloudTimestamp; m_LastReleasedPointcloudTimestamp = 0.0f; return previousLastTimestamp != 0; } return PointCloudApi.GetTimestamp(PointCloudHandle) != m_LastReleasedPointcloudTimestamp; } } public AnchorApi AnchorApi { get; private set; } public CameraApi CameraApi { get; private set; } public CameraMetadataApi CameraMetadataApi { get; private set; } public FrameApi FrameApi { get; private set; } public HitTestApi HitTestApi { get; private set; } public ImageApi ImageApi { get; private set; } public LightEstimateApi LightEstimateApi { get; private set; } public PlaneApi PlaneApi { get; private set; } public PointApi PointApi { get; private set; } public PointCloudApi PointCloudApi { get; private set; } public PoseApi PoseApi { get; private set; } public SessionApi SessionApi { get; private set; } public SessionConfigApi SessionConfigApi { get; private set; } public TrackableApi TrackableApi { get; private set; } public TrackableListApi TrackableListApi { get; private set; } public void MarkHandleAcquired(IntPtr handle) { if (handle == IntPtr.Zero) { Debug.LogError("MarkHandleAcquired::Attempted to mark a null handle acquired."); return; } int acquireCount; m_AcquiredHandleCounts.TryGetValue(handle, out acquireCount); m_AcquiredHandleCounts[handle] = ++acquireCount; } public void MarkHandleReleased(IntPtr handle) { int acquireCount; if (m_AcquiredHandleCounts.TryGetValue(handle, out acquireCount)) { if (--acquireCount > 0) { m_AcquiredHandleCounts[handle] = acquireCount; } else { m_AcquiredHandleCounts.Remove(handle); } } } public bool IsHandleAcquired(IntPtr handle) { int acquireCount; m_AcquiredHandleCounts.TryGetValue(handle, out acquireCount); return acquireCount > 0; } public Trackable TrackableFactory(IntPtr nativeHandle) { return m_TrackableManager.TrackableFactory(nativeHandle); } public void GetTrackables<T>(List<T> trackables, TrackableQueryFilter filter) where T : Trackable { m_TrackableManager.GetTrackables<T>(trackables, filter); } public void OnUpdate() { // After first frame, release previous frame's point cloud. if (m_PointCloudHandle != IntPtr.Zero) { m_LastReleasedPointcloudTimestamp = PointCloudApi.GetTimestamp(m_PointCloudHandle); PointCloudApi.Release(m_PointCloudHandle); m_PointCloudHandle = IntPtr.Zero; } // TODO (b/73256094): Remove when fixed. if (LifecycleManager.Instance.SessionStatus == SessionStatus.Tracking) { FrameApi.TryAcquirePointCloudHandle(out m_PointCloudHandle); } } } }
// // Copyright 2011-2013, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Threading.Tasks; using Windows.Devices.Geolocation; using Windows.Foundation; using Plugin.Geolocator.Abstractions; using System.Threading; namespace Plugin.Geolocator { /// <summary> /// Implementation for Geolocator /// </summary> public class GeolocatorImplementation : IGeolocator { public GeolocatorImplementation() { DesiredAccuracy = 100; } /// <inheritdoc/> public event EventHandler<PositionEventArgs> PositionChanged; /// <inheritdoc/> public event EventHandler<PositionErrorEventArgs> PositionError; /// <inheritdoc/> public bool SupportsHeading { get { return false; } } /// <inheritdoc/> public bool IsGeolocationAvailable { get { PositionStatus status = GetGeolocatorStatus(); while (status == PositionStatus.Initializing) { Task.Delay(10).Wait(); status = GetGeolocatorStatus(); } return status != PositionStatus.NotAvailable; } } /// <inheritdoc/> public bool IsGeolocationEnabled { get { PositionStatus status = GetGeolocatorStatus(); while (status == PositionStatus.Initializing) { Task.Delay(10).Wait(); status = GetGeolocatorStatus(); } return status != PositionStatus.Disabled && status != PositionStatus.NotAvailable; } } /// <inheritdoc/> public double DesiredAccuracy { get { return desiredAccuracy; } set { desiredAccuracy = value; GetGeolocator().DesiredAccuracy = (value < 100) ? PositionAccuracy.High : PositionAccuracy.Default; } } /// <inheritdoc/> public bool IsListening { get { return isListening; } } /// <inheritdoc/> public Task<Position> GetPositionAsync(int timeoutMilliseconds = Timeout.Infite, CancellationToken? token = null, bool includeHeading = false) { if (timeoutMilliseconds < 0 && timeoutMilliseconds != Timeout.Infite) throw new ArgumentOutOfRangeException("timeoutMilliseconds"); if (!token.HasValue) token = CancellationToken.None; IAsyncOperation<Geoposition> pos = GetGeolocator().GetGeopositionAsync(TimeSpan.FromTicks(0), TimeSpan.FromDays(365)); token.Value.Register(o => ((IAsyncOperation<Geoposition>)o).Cancel(), pos); var timer = new Timeout(timeoutMilliseconds, pos.Cancel); var tcs = new TaskCompletionSource<Position>(); pos.Completed = (op, s) => { timer.Cancel(); switch (s) { case AsyncStatus.Canceled: tcs.SetCanceled(); break; case AsyncStatus.Completed: tcs.SetResult(GetPosition(op.GetResults())); break; case AsyncStatus.Error: Exception ex = op.ErrorCode; if (ex is UnauthorizedAccessException) ex = new GeolocationException(GeolocationError.Unauthorized, ex); tcs.SetException(ex); break; } }; return tcs.Task; } /// <inheritdoc/> public Task<bool> StartListeningAsync(int minTime, double minDistance, bool includeHeading = false, ListenerSettings settings = null) { if (minTime < 0) throw new ArgumentOutOfRangeException("minTime"); if (minDistance < 0) throw new ArgumentOutOfRangeException("minDistance"); if (isListening) throw new InvalidOperationException(); isListening = true; var loc = GetGeolocator(); loc.ReportInterval = (uint)minTime; loc.MovementThreshold = minDistance; loc.PositionChanged += OnLocatorPositionChanged; loc.StatusChanged += OnLocatorStatusChanged; return Task.FromResult(true); } /// <inheritdoc/> public Task<bool> StopListeningAsync() { if (!isListening) return Task.FromResult(true); locator.PositionChanged -= OnLocatorPositionChanged; locator.StatusChanged -= OnLocatorStatusChanged; isListening = false; return Task.FromResult(true); } private bool isListening; private double desiredAccuracy; private Windows.Devices.Geolocation.Geolocator locator = new Windows.Devices.Geolocation.Geolocator(); private async void OnLocatorStatusChanged(Windows.Devices.Geolocation.Geolocator sender, StatusChangedEventArgs e) { GeolocationError error; switch (e.Status) { case PositionStatus.Disabled: error = GeolocationError.Unauthorized; break; case PositionStatus.NoData: error = GeolocationError.PositionUnavailable; break; default: return; } if (isListening) { await StopListeningAsync(); OnPositionError(new PositionErrorEventArgs(error)); } locator = null; } private void OnLocatorPositionChanged(Windows.Devices.Geolocation.Geolocator sender, PositionChangedEventArgs e) { OnPositionChanged(new PositionEventArgs(GetPosition(e.Position))); } private void OnPositionChanged(PositionEventArgs e) { var handler = PositionChanged; if (handler != null) handler(this, e); } private void OnPositionError(PositionErrorEventArgs e) { var handler = PositionError; if (handler != null) handler(this, e); } private Windows.Devices.Geolocation.Geolocator GetGeolocator() { var loc = locator; if (loc == null) { locator = new Windows.Devices.Geolocation.Geolocator(); locator.StatusChanged += OnLocatorStatusChanged; loc = locator; } return loc; } private PositionStatus GetGeolocatorStatus() { var loc = GetGeolocator(); return loc.LocationStatus; } private static Position GetPosition(Geoposition position) { var pos = new Position { Accuracy = position.Coordinate.Accuracy, Latitude = position.Coordinate.Point.Position.Latitude, Longitude = position.Coordinate.Point.Position.Longitude, Timestamp = position.Coordinate.Timestamp.ToUniversalTime(), }; if (position.Coordinate.Heading != null) pos.Heading = position.Coordinate.Heading.Value; if (position.Coordinate.Speed != null) pos.Speed = position.Coordinate.Speed.Value; if (position.Coordinate.AltitudeAccuracy.HasValue) pos.AltitudeAccuracy = position.Coordinate.AltitudeAccuracy.Value; pos.Altitude = position.Coordinate.Point.Position.Altitude; return pos; } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Navigation; using ArcGIS.Core.CIM; using ArcGIS.Desktop.Mapping; using Field = ArcGIS.Core.Data.Field; namespace LayerPopups.Helpers { /// <summary> /// Enumeration used for the NormalizeField in ChartMediaInfo /// </summary> public enum RelateFieldStatistic { Count = 0, Minimum, Maximum, Sum, Mean, StandardDeviation } /// <summary> /// Types supported by ChartMediaInfos /// </summary> public enum ChartMediaType { Column = 0, Line, Pie, Bar } /// <summary> /// Definition for a layer popup. Includes the various media types that can be added to a popup /// </summary> /// <remarks>The CIM model allows for an arbitrary mix of media elements to be added to a popup /// but in order to be compatible with Online, the first two elements are always Text and Table (if /// they are present). /// Text that is added to the CIM should be formatted as XHTML. Some default format strings are /// provided in this class that mimic the ones Pro uses but feel free to experiment</remarks> public class CustomPopupDefinition { internal static readonly string DefaultFormat = "<div><p><span style=\"font-weight:normal;text-decoration:none;\">{0}</span></p></div>"; internal static readonly string DefaultTitleFormat = "<div><p><span style=\"color:black;font-weight:bold;text-decoration:none;\">{0}</span></p></div>"; internal static readonly string DefaultURLFormat = "<a href=\"{0}\" target=\"_blank\" style=\"color:#6D6D6D;text-decoration:underline;\">{1}</a>"; private List<BaseMediaInfo> _mediaInfos = new List<BaseMediaInfo>(); private string _title = ""; /// <summary> /// Popup title. Shows along the popup window frame (not in the popup content itself). /// </summary> public string Title { get { return _title; } set { _title = value; } } /// <summary> /// Text media. Always shows first if it has been added /// </summary> public TextMediaInfo TextMediaInfo { get; set; } /// <summary> /// Table media. Always shows first or second - second if a /// Text media has been added to the popup /// </summary> public TableMediaInfo TableMediaInfo { get; set; } /// <summary> /// A mix of charts, images, attachements - in any order. These /// are added to the popup carousel ( with "next" and "previous" navigation) /// </summary> /// <remarks>If a text or table media is added it is ignored</remarks> public IList<BaseMediaInfo> OtherMediaInfos => _mediaInfos; public static string FormatTitle(string title) { return String.Format(DefaultTitleFormat, title); } /// <summary> /// Format a caption for a popup /// </summary> /// <param name="caption"></param> /// <returns></returns> public static string FormatCaption(string caption) { return String.Format(DefaultTitleFormat, caption); } /// <summary> /// Format a plain text string /// </summary> /// <param name="text"></param> /// <returns></returns> public static string FormatText(string text) { return String.Format(DefaultFormat, text); } /// <summary> /// Format a string as a field name /// </summary> /// <param name="fieldName"></param> /// <returns></returns> public static string FormatFieldName(string fieldName) { return String.Format("{0}{1}{2}", "{", fieldName, "}"); } /// <summary> /// Format a URI as a string for the popup /// </summary> /// <param name="uri"></param> /// <returns></returns> public static string FormatUrl(Uri uri) { return uri.IsAbsoluteUri ? uri.AbsoluteUri : uri.OriginalString; } /// <summary> /// Field names can also be added as URLs to the popup (eg for an image media) /// </summary> /// <param name="fieldName"></param> /// <returns></returns> public static string FormatUrl(string fieldName) { return FormatFieldName(fieldName); } /// <summary> /// When adding charts, related fields can be used either as values for the /// ChartMedia NormalizeField property. Specify the name of the relate (as read from the /// GDB), the name of the field in the related table, and the statistic to use when /// Normalizing. /// </summary> /// <param name="relateName"></param> /// <param name="fieldName"></param> /// <param name="statistic"></param> /// <returns></returns> public static string FormatRelatedFieldName(string relateName, string fieldName, RelateFieldStatistic statistic) { string format = "{0}\\{1}:"; switch (statistic) { case RelateFieldStatistic.Count: format += "COUNT"; break; case RelateFieldStatistic.Minimum: format += "MIN"; break; case RelateFieldStatistic.Maximum: format += "MAX"; break; case RelateFieldStatistic.Sum: format += "SUM"; break; case RelateFieldStatistic.Mean: format += "MEAN"; break; case RelateFieldStatistic.StandardDeviation: format += "STDDEV"; break; default: throw new ArgumentException(String.Format("{0} is not a valid statistic value", statistic)); } return String.Format(format, relateName, fieldName); } /// <summary> /// Generate the CIMPopupInfo for the layer from the current media infos /// </summary> /// <returns></returns> public CIMPopupInfo CreatePopupInfo() { CIMPopupInfo popupInfo = new CIMPopupInfo(); popupInfo.Title = this.Title; List<CIMMediaInfo> mediaInfos = new List<CIMMediaInfo>(); if (this.TextMediaInfo != null) { var cimText = new CIMTextMediaInfo { Row = 1, Column = 1, Text = this.TextMediaInfo.Text }; mediaInfos.Add(cimText); } if (this.TableMediaInfo != null) { var cimTable = new CIMTableMediaInfo { Row = mediaInfos.Count + 1, Column = 1, Fields = this.TableMediaInfo.FieldNames.ToArray() }; mediaInfos.Add(cimTable); } foreach (var cimMediaInfo in OtherMediaInfos) { if (cimMediaInfo is TextMediaInfo || cimMediaInfo is TableMediaInfo) continue; if (cimMediaInfo is AttachmentsMediaInfo) { var mediaInfo = CreateAttachmentMediaInfo((AttachmentsMediaInfo)cimMediaInfo); mediaInfo.Row = mediaInfos.Count + 1; mediaInfo.Column = 1; mediaInfos.Add(mediaInfo); } else if (cimMediaInfo is ImageMediaInfo) { var mediaInfo = CreateImageMediaInfo((ImageMediaInfo)cimMediaInfo); mediaInfo.Row = mediaInfos.Count + 1; mediaInfo.Column = 1; mediaInfos.Add(mediaInfo); } else if (cimMediaInfo is ChartMediaInfo) { var mediaInfo = CreateChartMediaInfo((ChartMediaInfo)cimMediaInfo); mediaInfo.Row = mediaInfos.Count + 1; mediaInfo.Column = 1; mediaInfos.Add(mediaInfo); } } if (mediaInfos.Count > 0) { popupInfo.MediaInfos = mediaInfos.ToArray(); } return popupInfo;; } //Convert the AttachmentsMediaInfo to its CIM equivalent internal CIMAttachmentsMediaInfo CreateAttachmentMediaInfo(AttachmentsMediaInfo attachment) { CIMAttachmentsMediaInfo mediaInfo = new CIMAttachmentsMediaInfo(); mediaInfo.Title = attachment.Title; mediaInfo.Caption = attachment.Caption; mediaInfo.ContentType = attachment.MimeContentType; mediaInfo.DisplayType = attachment.AttachmentDisplayType; return mediaInfo; } //Convert the ImageMediaInfo to its CIM equivalent internal CIMImageMediaInfo CreateImageMediaInfo(ImageMediaInfo image) { CIMImageMediaInfo mediaInfo = new CIMImageMediaInfo(); mediaInfo.Title = image.Title; mediaInfo.Caption = image.Caption; mediaInfo.SourceURL = image.SourceURL; mediaInfo.LinkURL = image.LinkURL; return mediaInfo; } //Convert the ChartMediaInfo to its CIM equivalent internal CIMChartMediaInfo CreateChartMediaInfo(ChartMediaInfo chart) { CIMChartMediaInfo mediaInfo = null; if (chart.ChartMediaType == ChartMediaType.Column) { mediaInfo = new CIMColumnChartMediaInfo(); } else if (chart.ChartMediaType == ChartMediaType.Bar) { mediaInfo = new CIMBarChartMediaInfo(); } else if (chart.ChartMediaType == ChartMediaType.Line) { mediaInfo = new CIMLineChartMediaInfo(); } else { mediaInfo = new CIMPieChartMediaInfo(); } mediaInfo.Title = chart.Title; mediaInfo.Caption = chart.Caption; mediaInfo.NormalizeField = chart.NormalizeFieldName; mediaInfo.Fields = chart.FieldNames.ToArray(); return mediaInfo; } } /// <summary> /// Base class for the MediaInfos. The MediaInfos wrap the underlying CIM definitions /// that the CIMPopupInfo uses /// </summary> public abstract class BaseMediaInfo { } /// <summary> /// Define a Text media element for the popup /// </summary> public class TextMediaInfo : BaseMediaInfo { private string _formattedText = ""; public TextMediaInfo() { } /// <summary> /// Copy constructor /// </summary> /// <param name="copy"></param> public TextMediaInfo(TextMediaInfo copy) { this._formattedText = copy._formattedText; } /// <summary> /// The actual text content to show on the popup /// </summary> public string Text { get { return _formattedText; } set { _formattedText = value; } } } /// <summary> /// Define a Table media element for the popup /// </summary> public class TableMediaInfo : BaseMediaInfo { private List<string> _fieldNames = new List<string>(); public TableMediaInfo() { } /// <summary> /// Copy constructor /// </summary> /// <param name="copy"></param> public TableMediaInfo(TableMediaInfo copy) { this._fieldNames.AddRange(copy._fieldNames); } public TableMediaInfo(IEnumerable<Field> fields) : base() { _fieldNames.AddRange(fields.Select((f) => f.Name).ToArray()); } public TableMediaInfo(IEnumerable<string> fieldNames) : base() { _fieldNames.AddRange(fieldNames.ToArray()); } /// <summary> /// The list of field names to show in the Table media element /// </summary> public IList<string> FieldNames => _fieldNames; } /// <summary> /// Base class for all the other media types each of which have a /// Caption and Title field /// </summary> public abstract class BaseTitleAndCaptionMediaInfo : BaseMediaInfo { protected string _formattedTitle = ""; protected string _formattedCaption = ""; /// <summary> /// Title shows at the top of the media element (above the /// line demarcating the carousel region of the popup) /// </summary> public string Title { get { return _formattedTitle; } set { _formattedTitle = value; } } /// <summary> /// Caption shows directly above the media element on the /// carousel (beneath the Title and line at the top of the carousel) /// </summary> public string Caption { get { return _formattedCaption; } set { _formattedCaption = value; } } } /// <summary> /// If your feature class has attachments you can use an Attachment media element /// </summary> /// <remarks>You do NOT have to specify the attachment field. The popup is smart /// enough to know which field is the attachement field (based on the attachment /// relationship in the GDB).</remarks> public class AttachmentsMediaInfo : BaseTitleAndCaptionMediaInfo { private string _contentType = ""; private AttachmentDisplayType _displayType = AttachmentDisplayType.PreviewAll; public AttachmentsMediaInfo() { } /// <summary> /// Copyy constructor /// </summary> /// <param name="copy"></param> public AttachmentsMediaInfo(AttachmentsMediaInfo copy) { this._formattedTitle = copy._formattedTitle; this._formattedCaption = copy._formattedCaption; this._contentType = copy._contentType; this._displayType = copy._displayType; } //Must be one of these: http://www.iana.org/assignments/media-types/media-types.xhtml public string MimeContentType { get { return _contentType; } set { _contentType = value; } } public AttachmentDisplayType AttachmentDisplayType { get { return _displayType;} set { _displayType = value;} } } /// <summary> /// Display an image or a link to an image /// </summary> public class ImageMediaInfo : BaseTitleAndCaptionMediaInfo { private string _sourceUri; private string _linkUri; public ImageMediaInfo() { } /// <summary> /// Copy constructor /// </summary> /// <param name="copy"></param> public ImageMediaInfo(ImageMediaInfo copy) { this._formattedTitle = copy._formattedTitle; this._formattedCaption = copy._formattedCaption; this._sourceUri = copy._sourceUri; this._linkUri = copy._linkUri; } /// <summary> /// Note: This can be a field name if it has a URL to an image as /// an attribute /// </summary> public string SourceURL { get { return _sourceUri; } set { _sourceUri = value; } } /// <summary> /// Note: This can be a field name if it has a URL to an image as /// an attribute /// </summary> /// <remarks>Shows a link to an image rather than an image</remarks> public string LinkURL { get { return _linkUri; } set { _linkUri = value; } } } /// <summary> /// Display a chart. There are four types - Column, Bar, Pie, Line /// </summary> /// <remarks>They all follow the same configuration. Specify the field or /// fields to plot, any normalization (in Normalize field) as well as a Title /// and Caption. /// You can also use a related field for the normalization but you must specify the /// name of the relate as well as the related field.</remarks> public class ChartMediaInfo : BaseTitleAndCaptionMediaInfo { private List<string> _fieldNames = new List<string>(); private string _normalizeFieldName = ""; private ChartMediaType _chartType = default(ChartMediaType); public ChartMediaInfo() { } public ChartMediaInfo(ChartMediaInfo copy) { if (this._fieldNames.Count > 0) this._fieldNames.AddRange(copy._fieldNames); this.Title = copy.Title; this.Caption = copy.Caption; this._normalizeFieldName = copy._normalizeFieldName; this._chartType = copy._chartType; } /// <summary> /// Pick the chart type /// </summary> public ChartMediaType ChartMediaType { get { return _chartType; } set { _chartType = value; } } public string NormalizeFieldName { get { return _normalizeFieldName; } set { _normalizeFieldName = value; } } public IList<string> FieldNames => _fieldNames; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute; using Encoding = System.Text.Encoding; namespace System.Xml.Linq { /// <summary> /// Represents an XML document. /// </summary> /// <remarks> /// An <see cref="XDocument"/> can contain: /// <list> /// <item> /// A Document Type Declaration (DTD), see <see cref="XDocumentType"/> /// </item> /// <item>One root element.</item> /// <item>Zero or more <see cref="XComment"/> objects.</item> /// <item>Zero or more <see cref="XProcessingInstruction"/> objects.</item> /// </list> /// </remarks> public class XDocument : XContainer { XDeclaration declaration; ///<overloads> /// Initializes a new instance of the <see cref="XDocument"/> class. /// Overloaded constructors are provided for creating a new empty /// <see cref="XDocument"/>, creating an <see cref="XDocument"/> with /// a parameter list of initial content, and as a copy of another /// <see cref="XDocument"/> object. /// </overloads> /// <summary> /// Initializes a new instance of the <see cref="XDocument"/> class. /// </summary> public XDocument() { } /// <summary> /// Initializes a new instance of the <see cref="XDocument"/> class with the specified content. /// </summary> /// <param name="content"> /// A parameter list of content objects to add to this document. /// </param> /// <remarks> /// Valid content includes: /// <list> /// <item>Zero or one <see cref="XDocumentType"/> objects</item> /// <item>Zero or one elements</item> /// <item>Zero or more comments</item> /// <item>Zero or more processing instructions</item> /// </list> /// See <see cref="XContainer.Add(object)"/> for details about the content that can be added /// using this method. /// </remarks> public XDocument(params object[] content) : this() { AddContentSkipNotify(content); } /// <summary> /// Initializes a new instance of the <see cref="XDocument"/> class /// with the specified <see cref="XDeclaration"/> and content. /// </summary> /// <param name="declaration"> /// The XML declaration for the document. /// </param> /// <param name="content"> /// The contents of the document. /// </param> /// <remarks> /// Valid content includes: /// <list> /// <item>Zero or one <see cref="XDocumentType"/> objects</item> /// <item>Zero or one elements</item> /// <item>Zero or more comments</item> /// <item>Zero or more processing instructions</item> /// <item></item> /// </list> /// See <see cref="XContainer.Add(object)"/> for details about the content that can be added /// using this method. /// </remarks> public XDocument(XDeclaration declaration, params object[] content) : this(content) { this.declaration = declaration; } /// <summary> /// Initializes a new instance of the <see cref="XDocument"/> class from an /// existing XDocument object. /// </summary> /// <param name="other"> /// The <see cref="XDocument"/> object that will be copied. /// </param> public XDocument(XDocument other) : base(other) { if (other.declaration != null) { declaration = new XDeclaration(other.declaration); } } /// <summary> /// Gets the XML declaration for this document. /// </summary> public XDeclaration Declaration { get { return declaration; } set { declaration = value; } } /// <summary> /// Gets the Document Type Definition (DTD) for this document. /// </summary> public XDocumentType DocumentType { get { return GetFirstNode<XDocumentType>(); } } /// <summary> /// Gets the node type for this node. /// </summary> /// <remarks> /// This property will always return XmlNodeType.Document. /// </remarks> public override XmlNodeType NodeType { get { return XmlNodeType.Document; } } /// <summary> /// Gets the root element of the XML Tree for this document. /// </summary> public XElement Root { get { return GetFirstNode<XElement>(); } } /// <overloads> /// The Load method provides multiple strategies for creating a new /// <see cref="XDocument"/> and initializing it from a data source containing /// raw XML. Load from a file (passing in a URI to the file), a /// <see cref="Stream"/>, a <see cref="TextReader"/>, or an /// <see cref="XmlReader"/>. Note: Use <see cref="XDocument.Parse(string)"/> /// to create an <see cref="XDocument"/> from a string containing XML. /// <seealso cref="XDocument.Parse(string)"/> /// </overloads> /// <summary> /// Create a new <see cref="XDocument"/> based on the contents of the file /// referenced by the URI parameter passed in. Note: Use /// <see cref="XDocument.Parse(string)"/> to create an <see cref="XDocument"/> from /// a string containing XML. /// <seealso cref="XmlReader.Create(string)"/> /// <seealso cref="XDocument.Parse(string)"/> /// </summary> /// <remarks> /// This method uses the <see cref="XmlReader.Create(string)"/> method to create /// an <see cref="XmlReader"/> to read the raw XML into the underlying /// XML tree. /// </remarks> /// <param name="uri"> /// A URI string referencing the file to load into a new <see cref="XDocument"/>. /// </param> /// <returns> /// An <see cref="XDocument"/> initialized with the contents of the file referenced /// in the passed in uri parameter. /// </returns> [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#", Justification = "Back-compat with System.Xml.")] public static XDocument Load(string uri) { return Load(uri, LoadOptions.None); } /// <summary> /// Create a new <see cref="XDocument"/> based on the contents of the file /// referenced by the URI parameter passed in. Optionally, whitespace can be preserved. /// <see cref="XmlReader.Create(string)"/> /// </summary> /// <remarks> /// This method uses the <see cref="XmlReader.Create(string)"/> method to create /// an <see cref="XmlReader"/> to read the raw XML into an underlying /// XML tree. If LoadOptions.PreserveWhitespace is enabled then /// the <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/> /// is set to false. /// </remarks> /// <param name="uri"> /// A string representing the URI of the file to be loaded into a new <see cref="XDocument"/>. /// </param> /// <param name="options"> /// A set of <see cref="LoadOptions"/>. /// </param> /// <returns> /// An <see cref="XDocument"/> initialized with the contents of the file referenced /// in the passed uri parameter. If LoadOptions.PreserveWhitespace is enabled then /// all whitespace will be preserved. /// </returns> [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#", Justification = "Back-compat with System.Xml.")] public static XDocument Load(string uri, LoadOptions options) { XmlReaderSettings rs = GetXmlReaderSettings(options); using (XmlReader r = XmlReader.Create(uri, rs)) { return Load(r, options); } } /// <summary> /// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using /// the passed <see cref="Stream"/> parameter. /// </summary> /// <param name="stream"> /// A <see cref="Stream"/> containing the raw XML to read into the newly /// created <see cref="XDocument"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed in /// <see cref="Stream"/>. /// </returns> public static XDocument Load(Stream stream) { return Load(stream, LoadOptions.None); } /// <summary> /// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using /// the passed <see cref="Stream"/> parameter. Optionally whitespace handling /// can be preserved. /// </summary> /// <remarks> /// If LoadOptions.PreserveWhitespace is enabled then /// the underlying <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/> /// is set to false. /// </remarks> /// <param name="stream"> /// A <see cref="Stream"/> containing the raw XML to read into the newly /// created <see cref="XDocument"/>. /// </param> /// <param name="options"> /// A set of <see cref="LoadOptions"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed in /// <see cref="Stream"/>. /// </returns> public static XDocument Load(Stream stream, LoadOptions options) { XmlReaderSettings rs = GetXmlReaderSettings(options); using (XmlReader r = XmlReader.Create(stream, rs)) { return Load(r, options); } } /// <summary> /// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using /// the passed <see cref="TextReader"/> parameter. /// </summary> /// <param name="textReader"> /// A <see cref="TextReader"/> containing the raw XML to read into the newly /// created <see cref="XDocument"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed in /// <see cref="TextReader"/>. /// </returns> public static XDocument Load(TextReader textReader) { return Load(textReader, LoadOptions.None); } /// <summary> /// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using /// the passed <see cref="TextReader"/> parameter. Optionally whitespace handling /// can be preserved. /// </summary> /// <remarks> /// If LoadOptions.PreserveWhitespace is enabled then /// the <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/> /// is set to false. /// </remarks> /// <param name="textReader"> /// A <see cref="TextReader"/> containing the raw XML to read into the newly /// created <see cref="XDocument"/>. /// </param> /// <param name="options"> /// A set of <see cref="LoadOptions"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed in /// <see cref="TextReader"/>. /// </returns> public static XDocument Load(TextReader textReader, LoadOptions options) { XmlReaderSettings rs = GetXmlReaderSettings(options); using (XmlReader r = XmlReader.Create(textReader, rs)) { return Load(r, options); } } /// <summary> /// Create a new <see cref="XDocument"/> containing the contents of the /// passed in <see cref="XmlReader"/>. /// </summary> /// <param name="reader"> /// An <see cref="XmlReader"/> containing the XML to be read into the new /// <see cref="XDocument"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed /// in <see cref="XmlReader"/>. /// </returns> public static XDocument Load(XmlReader reader) { return Load(reader, LoadOptions.None); } /// <summary> /// Create a new <see cref="XDocument"/> containing the contents of the /// passed in <see cref="XmlReader"/>. /// </summary> /// <param name="reader"> /// An <see cref="XmlReader"/> containing the XML to be read into the new /// <see cref="XDocument"/>. /// </param> /// <param name="options"> /// A set of <see cref="LoadOptions"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed /// in <see cref="XmlReader"/>. /// </returns> public static XDocument Load(XmlReader reader, LoadOptions options) { if (reader == null) throw new ArgumentNullException("reader"); if (reader.ReadState == ReadState.Initial) reader.Read(); XDocument d = new XDocument(); if ((options & LoadOptions.SetBaseUri) != 0) { string baseUri = reader.BaseURI; if (baseUri != null && baseUri.Length != 0) { d.SetBaseUri(baseUri); } } if ((options & LoadOptions.SetLineInfo) != 0) { IXmlLineInfo li = reader as IXmlLineInfo; if (li != null && li.HasLineInfo()) { d.SetLineInfo(li.LineNumber, li.LinePosition); } } if (reader.NodeType == XmlNodeType.XmlDeclaration) { d.Declaration = new XDeclaration(reader); } d.ReadContentFrom(reader, options); if (!reader.EOF) throw new InvalidOperationException(SR.InvalidOperation_ExpectedEndOfFile); if (d.Root == null) throw new InvalidOperationException(SR.InvalidOperation_MissingRoot); return d; } /// <overloads> /// Create a new <see cref="XDocument"/> from a string containing /// XML. Optionally whitespace can be preserved. /// </overloads> /// <summary> /// Create a new <see cref="XDocument"/> from a string containing /// XML. /// </summary> /// <param name="text"> /// A string containing XML. /// </param> /// <returns> /// An <see cref="XDocument"/> containing an XML tree initialized from the /// passed in XML string. /// </returns> public static XDocument Parse(string text) { return Parse(text, LoadOptions.None); } /// <summary> /// Create a new <see cref="XDocument"/> from a string containing /// XML. Optionally whitespace can be preserved. /// </summary> /// <remarks> /// This method uses <see cref="XmlReader.Create"/> method passing it a StringReader /// constructed from the passed in XML String. If LoadOptions.PreserveWhitespace /// is enabled then <see cref="XmlReaderSettings.IgnoreWhitespace"/> is /// set to false. See <see cref="XmlReaderSettings.IgnoreWhitespace"/> /// for more information on whitespace handling. /// </remarks> /// <param name="text"> /// A string containing XML. /// </param> /// <param name="options"> /// A set of <see cref="LoadOptions"/>. /// </param> /// <returns> /// An <see cref="XDocument"/> containing an XML tree initialized from the /// passed in XML string. /// </returns> public static XDocument Parse(string text, LoadOptions options) { using (StringReader sr = new StringReader(text)) { XmlReaderSettings rs = GetXmlReaderSettings(options); using (XmlReader r = XmlReader.Create(sr, rs)) { return Load(r, options); } } } /// <summary> /// Output this <see cref="XDocument"/> to the passed in <see cref="Stream"/>. /// </summary> /// <remarks> /// The format will be indented by default. If you want /// no indenting then use the SaveOptions version of Save (see /// <see cref="XDocument.Save(Stream, SaveOptions)"/>) enabling /// SaveOptions.DisableFormatting /// There is also an option SaveOptions.OmitDuplicateNamespaces for removing duplicate namespace declarations. /// Or instead use the SaveOptions as an annotation on this node or its ancestors, then this method will use those options. /// </remarks> /// <param name="stream"> /// The <see cref="Stream"/> to output this <see cref="XDocument"/> to. /// </param> public void Save(Stream stream) { Save(stream, GetSaveOptionsFromAnnotations()); } /// <summary> /// Output this <see cref="XDocument"/> to a <see cref="Stream"/>. /// </summary> /// <param name="stream"> /// The <see cref="Stream"/> to output the XML to. /// </param> /// <param name="options"> /// If SaveOptions.DisableFormatting is enabled the output is not indented. /// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed. /// </param> public void Save(Stream stream, SaveOptions options) { XmlWriterSettings ws = GetXmlWriterSettings(options); if (declaration != null && !string.IsNullOrEmpty(declaration.Encoding)) { try { ws.Encoding = Encoding.GetEncoding(declaration.Encoding); } catch (ArgumentException) { } } using (XmlWriter w = XmlWriter.Create(stream, ws)) { Save(w); } } /// <summary> /// Output this <see cref="XDocument"/> to the passed in <see cref="TextWriter"/>. /// </summary> /// <remarks> /// The format will be indented by default. If you want /// no indenting then use the SaveOptions version of Save (see /// <see cref="XDocument.Save(TextWriter, SaveOptions)"/>) enabling /// SaveOptions.DisableFormatting /// There is also an option SaveOptions.OmitDuplicateNamespaces for removing duplicate namespace declarations. /// Or instead use the SaveOptions as an annotation on this node or its ancestors, then this method will use those options. /// </remarks> /// <param name="textWriter"> /// The <see cref="TextWriter"/> to output this <see cref="XDocument"/> to. /// </param> public void Save(TextWriter textWriter) { Save(textWriter, GetSaveOptionsFromAnnotations()); } /// <summary> /// Output this <see cref="XDocument"/> to a <see cref="TextWriter"/>. /// </summary> /// <param name="textWriter"> /// The <see cref="TextWriter"/> to output the XML to. /// </param> /// <param name="options"> /// If SaveOptions.DisableFormatting is enabled the output is not indented. /// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed. /// </param> public void Save(TextWriter textWriter, SaveOptions options) { XmlWriterSettings ws = GetXmlWriterSettings(options); using (XmlWriter w = XmlWriter.Create(textWriter, ws)) { Save(w); } } /// <summary> /// Output this <see cref="XDocument"/> to an <see cref="XmlWriter"/>. /// </summary> /// <param name="writer"> /// The <see cref="XmlWriter"/> to output the XML to. /// </param> public void Save(XmlWriter writer) { WriteTo(writer); } /// <summary> /// Output this <see cref="XDocument"/>'s underlying XML tree to the /// passed in <see cref="XmlWriter"/>. /// <seealso cref="XDocument.Save(XmlWriter)"/> /// </summary> /// <param name="writer"> /// The <see cref="XmlWriter"/> to output the content of this /// <see cref="XDocument"/>. /// </param> public override void WriteTo(XmlWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); if (declaration != null && declaration.Standalone == "yes") { writer.WriteStartDocument(true); } else if (declaration != null && declaration.Standalone == "no") { writer.WriteStartDocument(false); } else { writer.WriteStartDocument(); } WriteContentTo(writer); writer.WriteEndDocument(); } internal override void AddAttribute(XAttribute a) { throw new ArgumentException(SR.Argument_AddAttribute); } internal override void AddAttributeSkipNotify(XAttribute a) { throw new ArgumentException(SR.Argument_AddAttribute); } internal override XNode CloneNode() { return new XDocument(this); } internal override bool DeepEquals(XNode node) { XDocument other = node as XDocument; return other != null && ContentsEqual(other); } internal override int GetDeepHashCode() { return ContentsHashCode(); } T GetFirstNode<T>() where T : XNode { XNode n = content as XNode; if (n != null) { do { n = n.next; T e = n as T; if (e != null) return e; } while (n != content); } return null; } internal static bool IsWhitespace(string s) { foreach (char ch in s) { if (ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n') return false; } return true; } internal override void ValidateNode(XNode node, XNode previous) { switch (node.NodeType) { case XmlNodeType.Text: ValidateString(((XText)node).Value); break; case XmlNodeType.Element: ValidateDocument(previous, XmlNodeType.DocumentType, XmlNodeType.None); break; case XmlNodeType.DocumentType: ValidateDocument(previous, XmlNodeType.None, XmlNodeType.Element); break; case XmlNodeType.CDATA: throw new ArgumentException(SR.Format(SR.Argument_AddNode, XmlNodeType.CDATA)); case XmlNodeType.Document: throw new ArgumentException(SR.Format(SR.Argument_AddNode, XmlNodeType.Document)); } } void ValidateDocument(XNode previous, XmlNodeType allowBefore, XmlNodeType allowAfter) { XNode n = content as XNode; if (n != null) { if (previous == null) allowBefore = allowAfter; do { n = n.next; XmlNodeType nt = n.NodeType; if (nt == XmlNodeType.Element || nt == XmlNodeType.DocumentType) { if (nt != allowBefore) throw new InvalidOperationException(SR.InvalidOperation_DocumentStructure); allowBefore = XmlNodeType.None; } if (n == previous) allowBefore = allowAfter; } while (n != content); } } internal override void ValidateString(string s) { if (!IsWhitespace(s)) throw new ArgumentException(SR.Argument_AddNonWhitespace); } } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using UnityEngine; using System.Collections.Generic; /// <summary> /// Controls the player's movement in virtual reality. /// </summary> [RequireComponent(typeof(CharacterController))] public class OVRPlayerController : MonoBehaviour { /// <summary> /// The rate acceleration during movement. /// </summary> public float Acceleration = 0.1f; /// <summary> /// The rate of damping on movement. /// </summary> public float Damping = 0.3f; /// <summary> /// The rate of additional damping when moving sideways or backwards. /// </summary> public float BackAndSideDampen = 0.5f; /// <summary> /// The force applied to the character when jumping. /// </summary> public float JumpForce = 0.3f; /// <summary> /// The rate of rotation when using a gamepad. /// </summary> public float RotationAmount = 1.5f; /// <summary> /// The rate of rotation when using the keyboard. /// </summary> public float RotationRatchet = 45.0f; /// <summary> /// If true, reset the initial yaw of the player controller when the Hmd pose is recentered. /// </summary> public bool HmdResetsY = true; /// <summary> /// If true, tracking data from a child OVRCameraRig will update the direction of movement. /// </summary> public bool HmdRotatesY = true; /// <summary> /// Modifies the strength of gravity. /// </summary> public float GravityModifier = 0.379f; /// <summary> /// If true, each OVRPlayerController will use the player's physical height. /// </summary> public bool useProfileData = true; protected CharacterController Controller = null; protected OVRCameraRig CameraRig = null; private float MoveScale = 1.0f; private Vector3 MoveThrottle = Vector3.zero; private float FallSpeed = 0.0f; private OVRPose? InitialPose; private float InitialYRotation = 0.0f; private float MoveScaleMultiplier = 1.0f; private float RotationScaleMultiplier = 1.0f; private bool SkipMouseRotation = false; private bool HaltUpdateMovement = false; private bool prevHatLeft = false; private bool prevHatRight = false; private float SimulationRate = 60f; void Start() { // Add eye-depth as a camera offset from the player controller var p = CameraRig.transform.localPosition; p.z = OVRManager.profile.eyeDepth; CameraRig.transform.localPosition = p; } void Awake() { Controller = gameObject.GetComponent<CharacterController>(); if(Controller == null) Debug.LogWarning("OVRPlayerController: No CharacterController attached."); // We use OVRCameraRig to set rotations to cameras, // and to be influenced by rotation OVRCameraRig[] CameraRigs = gameObject.GetComponentsInChildren<OVRCameraRig>(); if(CameraRigs.Length == 0) Debug.LogWarning("OVRPlayerController: No OVRCameraRig attached."); else if (CameraRigs.Length > 1) Debug.LogWarning("OVRPlayerController: More then 1 OVRCameraRig attached."); else CameraRig = CameraRigs[0]; InitialYRotation = transform.rotation.eulerAngles.y; } void OnEnable() { OVRManager.display.RecenteredPose += ResetOrientation; if (CameraRig != null) { CameraRig.UpdatedAnchors += UpdateTransform; } } void OnDisable() { OVRManager.display.RecenteredPose -= ResetOrientation; if (CameraRig != null) { CameraRig.UpdatedAnchors -= UpdateTransform; } } protected virtual void Update() { if (useProfileData) { if (InitialPose == null) { // Save the initial pose so it can be recovered if useProfileData // is turned off later. InitialPose = new OVRPose() { position = CameraRig.transform.localPosition, orientation = CameraRig.transform.localRotation }; } var p = CameraRig.transform.localPosition; p.y = OVRManager.profile.eyeHeight - 0.5f * Controller.height + Controller.center.y; CameraRig.transform.localPosition = p; } else if (InitialPose != null) { // Return to the initial pose if useProfileData was turned off at runtime CameraRig.transform.localPosition = InitialPose.Value.position; CameraRig.transform.localRotation = InitialPose.Value.orientation; InitialPose = null; } UpdateMovement(); Vector3 moveDirection = Vector3.zero; float motorDamp = (1.0f + (Damping * SimulationRate * Time.deltaTime)); MoveThrottle.x /= motorDamp; MoveThrottle.y = (MoveThrottle.y > 0.0f) ? (MoveThrottle.y / motorDamp) : MoveThrottle.y; MoveThrottle.z /= motorDamp; moveDirection += MoveThrottle * SimulationRate * Time.deltaTime; // Gravity if (Controller.isGrounded && FallSpeed <= 0) FallSpeed = ((Physics.gravity.y * (GravityModifier * 0.002f))); else FallSpeed += ((Physics.gravity.y * (GravityModifier * 0.002f)) * SimulationRate * Time.deltaTime); moveDirection.y += FallSpeed * SimulationRate * Time.deltaTime; // Offset correction for uneven ground float bumpUpOffset = 0.0f; if (Controller.isGrounded && MoveThrottle.y <= transform.lossyScale.y * 0.001f) { bumpUpOffset = Mathf.Max(Controller.stepOffset, new Vector3(moveDirection.x, 0, moveDirection.z).magnitude); moveDirection -= bumpUpOffset * Vector3.up; } Vector3 predictedXZ = Vector3.Scale((Controller.transform.localPosition + moveDirection), new Vector3(1, 0, 1)); // Move contoller Controller.Move(moveDirection); Vector3 actualXZ = Vector3.Scale(Controller.transform.localPosition, new Vector3(1, 0, 1)); if (predictedXZ != actualXZ) MoveThrottle += (actualXZ - predictedXZ) / (SimulationRate * Time.deltaTime); } public virtual void UpdateMovement() { if (HaltUpdateMovement) return; bool moveForward = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow); bool moveLeft = Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow); bool moveRight = Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow); bool moveBack = Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow); bool dpad_move = false; #if UNITY_ANDROID if (OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Up)) #else if (OVRInput.Get(OVRInput.Button.DpadUp)) #endif { moveForward = true; dpad_move = true; } #if UNITY_ANDROID if (OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Down)) #else if (OVRInput.Get(OVRInput.Button.DpadDown)) #endif { moveBack = true; dpad_move = true; } MoveScale = 1.0f; if ( (moveForward && moveLeft) || (moveForward && moveRight) || (moveBack && moveLeft) || (moveBack && moveRight) ) MoveScale = 0.70710678f; // No positional movement if we are in the air if (!Controller.isGrounded) MoveScale = 0.0f; MoveScale *= SimulationRate * Time.deltaTime; // Compute this for key movement float moveInfluence = Acceleration * 0.1f * MoveScale * MoveScaleMultiplier; // Run! if (dpad_move || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) moveInfluence *= 2.0f; Quaternion ort = transform.rotation; Vector3 ortEuler = ort.eulerAngles; ortEuler.z = ortEuler.x = 0f; ort = Quaternion.Euler(ortEuler); if (moveForward) MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * Vector3.forward); if (moveBack) MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * BackAndSideDampen * Vector3.back); if (moveLeft) MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.left); if (moveRight) MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.right); Vector3 euler = transform.rotation.eulerAngles; #if UNITY_ANDROID bool curHatLeft = OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.LeftShoulder); #else bool curHatLeft = OVRInput.Get(OVRInput.Button.PrimaryShoulder); #endif if (curHatLeft && !prevHatLeft) euler.y -= RotationRatchet; prevHatLeft = curHatLeft; #if UNITY_ANDROID bool curHatRight = OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.RightShoulder); #else bool curHatRight = OVRInput.Get(OVRInput.Button.SecondaryShoulder); #endif if(curHatRight && !prevHatRight) euler.y += RotationRatchet; prevHatRight = curHatRight; //Use keys to ratchet rotation if (Input.GetKeyDown(KeyCode.Q)) euler.y -= RotationRatchet; if (Input.GetKeyDown(KeyCode.E)) euler.y += RotationRatchet; float rotateInfluence = SimulationRate * Time.deltaTime * RotationAmount * RotationScaleMultiplier; #if !UNITY_ANDROID || UNITY_EDITOR if (!SkipMouseRotation) euler.y += Input.GetAxis("Mouse X") * rotateInfluence * 3.25f; #endif moveInfluence = SimulationRate * Time.deltaTime * Acceleration * 0.1f * MoveScale * MoveScaleMultiplier; #if !UNITY_ANDROID // LeftTrigger not avail on Android game pad moveInfluence *= 1.0f + OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger); #endif #if UNITY_ANDROID float leftAxisX = OVRGamepadController.GPC_GetAxis(OVRGamepadController.Axis.LeftXAxis); float leftAxisY = OVRGamepadController.GPC_GetAxis(OVRGamepadController.Axis.LeftYAxis); if(leftAxisY > 0.0f) MoveThrottle += ort * (leftAxisY * transform.lossyScale.z * moveInfluence * Vector3.forward); if(leftAxisY < 0.0f) MoveThrottle += ort * (Mathf.Abs(leftAxisY) * transform.lossyScale.z * moveInfluence * BackAndSideDampen * Vector3.back); if(leftAxisX < 0.0f) MoveThrottle += ort * (Mathf.Abs(leftAxisX) * transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.left); if(leftAxisX > 0.0f) MoveThrottle += ort * (leftAxisX * transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.right); float rightAxisX = OVRGamepadController.GPC_GetAxis(OVRGamepadController.Axis.RightXAxis); euler.y += rightAxisX * rotateInfluence; transform.rotation = Quaternion.Euler(euler); #else Vector2 primaryAxis = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick); if(primaryAxis.y > 0.0f) MoveThrottle += ort * (primaryAxis.y * transform.lossyScale.z * moveInfluence * Vector3.forward); if(primaryAxis.y < 0.0f) MoveThrottle += ort * (Mathf.Abs(primaryAxis.y) * transform.lossyScale.z * moveInfluence * BackAndSideDampen * Vector3.back); if(primaryAxis.x < 0.0f) MoveThrottle += ort * (Mathf.Abs(primaryAxis.x) * transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.left); if(primaryAxis.x > 0.0f) MoveThrottle += ort * (primaryAxis.x * transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.right); Vector2 secondaryAxis = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick); euler.y += secondaryAxis.x * rotateInfluence; transform.rotation = Quaternion.Euler(euler); #endif } /// <summary> /// Invoked by OVRCameraRig's UpdatedAnchors callback. Allows the Hmd rotation to update the facing direction of the player. /// </summary> public void UpdateTransform(OVRCameraRig rig) { Transform root = CameraRig.trackingSpace; Transform centerEye = CameraRig.centerEyeAnchor; if (HmdRotatesY) { Vector3 prevPos = root.position; Quaternion prevRot = root.rotation; transform.rotation = Quaternion.Euler(0.0f, centerEye.rotation.eulerAngles.y, 0.0f); root.position = prevPos; root.rotation = prevRot; } } /// <summary> /// Jump! Must be enabled manually. /// </summary> public bool Jump() { if (!Controller.isGrounded) return false; MoveThrottle += new Vector3(0, transform.lossyScale.y * JumpForce, 0); return true; } /// <summary> /// Stop this instance. /// </summary> public void Stop() { Controller.Move(Vector3.zero); MoveThrottle = Vector3.zero; FallSpeed = 0.0f; } /// <summary> /// Gets the move scale multiplier. /// </summary> /// <param name="moveScaleMultiplier">Move scale multiplier.</param> public void GetMoveScaleMultiplier(ref float moveScaleMultiplier) { moveScaleMultiplier = MoveScaleMultiplier; } /// <summary> /// Sets the move scale multiplier. /// </summary> /// <param name="moveScaleMultiplier">Move scale multiplier.</param> public void SetMoveScaleMultiplier(float moveScaleMultiplier) { MoveScaleMultiplier = moveScaleMultiplier; } /// <summary> /// Gets the rotation scale multiplier. /// </summary> /// <param name="rotationScaleMultiplier">Rotation scale multiplier.</param> public void GetRotationScaleMultiplier(ref float rotationScaleMultiplier) { rotationScaleMultiplier = RotationScaleMultiplier; } /// <summary> /// Sets the rotation scale multiplier. /// </summary> /// <param name="rotationScaleMultiplier">Rotation scale multiplier.</param> public void SetRotationScaleMultiplier(float rotationScaleMultiplier) { RotationScaleMultiplier = rotationScaleMultiplier; } /// <summary> /// Gets the allow mouse rotation. /// </summary> /// <param name="skipMouseRotation">Allow mouse rotation.</param> public void GetSkipMouseRotation(ref bool skipMouseRotation) { skipMouseRotation = SkipMouseRotation; } /// <summary> /// Sets the allow mouse rotation. /// </summary> /// <param name="skipMouseRotation">If set to <c>true</c> allow mouse rotation.</param> public void SetSkipMouseRotation(bool skipMouseRotation) { SkipMouseRotation = skipMouseRotation; } /// <summary> /// Gets the halt update movement. /// </summary> /// <param name="haltUpdateMovement">Halt update movement.</param> public void GetHaltUpdateMovement(ref bool haltUpdateMovement) { haltUpdateMovement = HaltUpdateMovement; } /// <summary> /// Sets the halt update movement. /// </summary> /// <param name="haltUpdateMovement">If set to <c>true</c> halt update movement.</param> public void SetHaltUpdateMovement(bool haltUpdateMovement) { HaltUpdateMovement = haltUpdateMovement; } /// <summary> /// Resets the player look rotation when the device orientation is reset. /// </summary> public void ResetOrientation() { if (HmdResetsY) { Vector3 euler = transform.rotation.eulerAngles; euler.y = InitialYRotation; transform.rotation = Quaternion.Euler(euler); } } }
// --------------------------------------------------------------------------------------------- using Palaso.UI.WindowsForms.Keyboarding; #region // Copyright (c) 2013, SIL International. All Rights Reserved. // <copyright from='2013' to='2013' company='SIL International'> // Copyright (c) 2013, SIL International. All Rights Reserved. // // Distributable under the terms of either the Common Public License or the // GNU Lesser General Public License, as specified in the LICENSING.txt file. // </copyright> #endregion // --------------------------------------------------------------------------------------------- namespace PalasoUIWindowsForms.TestApp { /// ---------------------------------------------------------------------------------------- /// <summary> /// /// </summary> /// ---------------------------------------------------------------------------------------- partial class TestAppForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing) { if (_KeyboardControllerInitialized) { KeyboardController.Shutdown(); _KeyboardControllerInitialized = false; } if (components != null) components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); Palaso.UI.WindowsForms.SuperToolTip.SuperToolTipInfoWrapper superToolTipInfoWrapper1 = new Palaso.UI.WindowsForms.SuperToolTip.SuperToolTipInfoWrapper(); Palaso.UI.WindowsForms.SuperToolTip.SuperToolTipInfo superToolTipInfo1 = new Palaso.UI.WindowsForms.SuperToolTip.SuperToolTipInfo(); this.btnFolderBrowserControl = new System.Windows.Forms.Button(); this.btnLookupISOCodeDialog = new System.Windows.Forms.Button(); this.btnWritingSystemSetupDialog = new System.Windows.Forms.Button(); this.btnArtOfReading = new System.Windows.Forms.Button(); this.btnSilAboutBox = new System.Windows.Forms.Button(); this.btnShowReleaseNotes = new System.Windows.Forms.Button(); this.superToolTip1 = new Palaso.UI.WindowsForms.SuperToolTip.SuperToolTip(this.components); this.label1 = new System.Windows.Forms.Label(); this.btnMetaDataEditor = new System.Windows.Forms.Button(); this.btnSelectFile = new System.Windows.Forms.Button(); this._silAboutBoxGecko = new System.Windows.Forms.Button(); this.SuspendLayout(); // // btnFolderBrowserControl // this.btnFolderBrowserControl.Location = new System.Drawing.Point(12, 12); this.btnFolderBrowserControl.Name = "btnFolderBrowserControl"; this.btnFolderBrowserControl.Size = new System.Drawing.Size(157, 23); this.btnFolderBrowserControl.TabIndex = 0; this.btnFolderBrowserControl.Text = "FolderBrowserControl"; this.btnFolderBrowserControl.UseVisualStyleBackColor = true; this.btnFolderBrowserControl.Click += new System.EventHandler(this.OnFolderBrowserControlClicked); // // btnLookupISOCodeDialog // this.btnLookupISOCodeDialog.Location = new System.Drawing.Point(12, 41); this.btnLookupISOCodeDialog.Name = "btnLookupISOCodeDialog"; this.btnLookupISOCodeDialog.Size = new System.Drawing.Size(157, 23); this.btnLookupISOCodeDialog.TabIndex = 0; this.btnLookupISOCodeDialog.Text = "LookupISOCodeDialog"; this.btnLookupISOCodeDialog.UseVisualStyleBackColor = true; this.btnLookupISOCodeDialog.Click += new System.EventHandler(this.OnLookupISOCodeDialogClicked); // // btnWritingSystemSetupDialog // this.btnWritingSystemSetupDialog.Location = new System.Drawing.Point(12, 70); this.btnWritingSystemSetupDialog.Name = "btnWritingSystemSetupDialog"; this.btnWritingSystemSetupDialog.Size = new System.Drawing.Size(157, 23); this.btnWritingSystemSetupDialog.TabIndex = 0; this.btnWritingSystemSetupDialog.Text = "WritingSystemSetupDialog"; this.btnWritingSystemSetupDialog.UseVisualStyleBackColor = true; this.btnWritingSystemSetupDialog.Click += new System.EventHandler(this.OnWritingSystemSetupDialogClicked); // // btnArtOfReading // this.btnArtOfReading.Location = new System.Drawing.Point(12, 99); this.btnArtOfReading.Name = "btnArtOfReading"; this.btnArtOfReading.Size = new System.Drawing.Size(157, 23); this.btnArtOfReading.TabIndex = 0; this.btnArtOfReading.Text = "ArtOfReading"; this.btnArtOfReading.UseVisualStyleBackColor = true; this.btnArtOfReading.Click += new System.EventHandler(this.OnArtOfReadingClicked); // // btnSilAboutBox // this.btnSilAboutBox.Location = new System.Drawing.Point(12, 128); this.btnSilAboutBox.Name = "btnSilAboutBox"; this.btnSilAboutBox.Size = new System.Drawing.Size(157, 23); this.btnSilAboutBox.TabIndex = 0; this.btnSilAboutBox.Text = "SIL AboutBox"; this.btnSilAboutBox.UseVisualStyleBackColor = true; this.btnSilAboutBox.Click += new System.EventHandler(this.OnSilAboutBoxClicked); // // btnShowReleaseNotes // this.btnShowReleaseNotes.Location = new System.Drawing.Point(12, 185); this.btnShowReleaseNotes.Name = "btnShowReleaseNotes"; this.btnShowReleaseNotes.Size = new System.Drawing.Size(157, 23); this.btnShowReleaseNotes.TabIndex = 0; this.btnShowReleaseNotes.Text = "Show Release Notes"; this.btnShowReleaseNotes.UseVisualStyleBackColor = true; this.btnShowReleaseNotes.Click += new System.EventHandler(this.OnShowReleaseNotesClicked); // // superToolTip1 // this.superToolTip1.FadingInterval = 10; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 275); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(149, 13); superToolTipInfo1.BackgroundGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0))))); superToolTipInfo1.BackgroundGradientEnd = System.Drawing.Color.Blue; superToolTipInfo1.BackgroundGradientMiddle = System.Drawing.Color.FromArgb(((int)(((byte)(242)))), ((int)(((byte)(246)))), ((int)(((byte)(251))))); superToolTipInfo1.BodyText = "This is the body text"; superToolTipInfo1.FooterForeColor = System.Drawing.Color.Lime; superToolTipInfo1.FooterText = "And this is the footer"; superToolTipInfo1.HeaderForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(0)))), ((int)(((byte)(0))))); superToolTipInfo1.HeaderText = "The header can serve as a title"; superToolTipInfo1.OffsetForWhereToDisplay = new System.Drawing.Point(0, 0); superToolTipInfo1.ShowFooter = true; superToolTipInfo1.ShowFooterSeparator = true; superToolTipInfoWrapper1.SuperToolTipInfo = superToolTipInfo1; superToolTipInfoWrapper1.UseSuperToolTip = true; this.superToolTip1.SetSuperStuff(this.label1, superToolTipInfoWrapper1); this.label1.TabIndex = 1; this.label1.Text = "Hover over me to see a tooltip"; // // btnMetaDataEditor // this.btnMetaDataEditor.Location = new System.Drawing.Point(12, 214); this.btnMetaDataEditor.Name = "btnMetaDataEditor"; this.btnMetaDataEditor.Size = new System.Drawing.Size(157, 23); this.btnMetaDataEditor.TabIndex = 0; this.btnMetaDataEditor.Text = "Meta Data Editor"; this.btnMetaDataEditor.UseVisualStyleBackColor = true; this.btnMetaDataEditor.Click += new System.EventHandler(this.OnShowMetaDataEditorClicked); // // btnSelectFile // this.btnSelectFile.Location = new System.Drawing.Point(12, 243); this.btnSelectFile.Name = "btnSelectFile"; this.btnSelectFile.Size = new System.Drawing.Size(157, 23); this.btnSelectFile.TabIndex = 0; this.btnSelectFile.Text = "Select File"; this.btnSelectFile.UseVisualStyleBackColor = true; this.btnSelectFile.Click += new System.EventHandler(this.OnSelectFileClicked); // // _silAboutBoxGecko // this._silAboutBoxGecko.Location = new System.Drawing.Point(12, 157); this._silAboutBoxGecko.Name = "_silAboutBoxGecko"; this._silAboutBoxGecko.Size = new System.Drawing.Size(157, 23); this._silAboutBoxGecko.TabIndex = 2; this._silAboutBoxGecko.Text = "SIL AboutBox (Gecko)"; this._silAboutBoxGecko.UseVisualStyleBackColor = true; this._silAboutBoxGecko.Click += new System.EventHandler(this.OnSilAboutBoxGeckoClicked); // // TestAppForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(187, 297); this.Controls.Add(this._silAboutBoxGecko); this.Controls.Add(this.label1); this.Controls.Add(this.btnSelectFile); this.Controls.Add(this.btnMetaDataEditor); this.Controls.Add(this.btnShowReleaseNotes); this.Controls.Add(this.btnSilAboutBox); this.Controls.Add(this.btnArtOfReading); this.Controls.Add(this.btnWritingSystemSetupDialog); this.Controls.Add(this.btnLookupISOCodeDialog); this.Controls.Add(this.btnFolderBrowserControl); this.Name = "TestAppForm"; this.Text = "PalasoUIWindowsForms.TestApp"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnFolderBrowserControl; private System.Windows.Forms.Button btnLookupISOCodeDialog; private System.Windows.Forms.Button btnWritingSystemSetupDialog; private System.Windows.Forms.Button btnArtOfReading; private System.Windows.Forms.Button btnSilAboutBox; private System.Windows.Forms.Button btnShowReleaseNotes; private Palaso.UI.WindowsForms.SuperToolTip.SuperToolTip superToolTip1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button btnMetaDataEditor; private System.Windows.Forms.Button btnSelectFile; private System.Windows.Forms.Button _silAboutBoxGecko; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { internal abstract partial class AbstractCodeGenerationService : ICodeGenerationService { private readonly ISymbolDeclarationService _symbolDeclarationService; protected AbstractCodeGenerationService( ISymbolDeclarationService symbolDeclarationService) { _symbolDeclarationService = symbolDeclarationService; } public TDeclarationNode AddEvent<TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode { return AddEvent(destination, @event, options ?? CodeGenerationOptions.Default, GetAvailableInsertionIndices(destination, cancellationToken)); } public TDeclarationNode AddField<TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode { return AddField(destination, field, options ?? CodeGenerationOptions.Default, GetAvailableInsertionIndices(destination, cancellationToken)); } public TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode { return AddMethod(destination, method, options ?? CodeGenerationOptions.Default, GetAvailableInsertionIndices(destination, cancellationToken)); } public TDeclarationNode AddProperty<TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode { return AddProperty(destination, property, options ?? CodeGenerationOptions.Default, GetAvailableInsertionIndices(destination, cancellationToken)); } public TDeclarationNode AddNamedType<TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode { return AddNamedType(destination, namedType, options ?? CodeGenerationOptions.Default, GetAvailableInsertionIndices(destination, cancellationToken), cancellationToken); } public TDeclarationNode AddNamespace<TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode { return AddNamespace(destination, @namespace, options ?? CodeGenerationOptions.Default, GetAvailableInsertionIndices(destination, cancellationToken), cancellationToken); } public TDeclarationNode AddMembers<TDeclarationNode>(TDeclarationNode destination, IEnumerable<ISymbol> members, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode { return AddMembers(destination, members, GetAvailableInsertionIndices(destination, cancellationToken), options ?? CodeGenerationOptions.Default, cancellationToken); } protected abstract TDeclarationNode AddEvent<TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions options, IList<bool> availableIndices) where TDeclarationNode : SyntaxNode; protected abstract TDeclarationNode AddField<TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions options, IList<bool> availableIndices) where TDeclarationNode : SyntaxNode; protected abstract TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) where TDeclarationNode : SyntaxNode; protected abstract TDeclarationNode AddProperty<TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions options, IList<bool> availableIndices) where TDeclarationNode : SyntaxNode; protected abstract TDeclarationNode AddNamedType<TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode; protected abstract TDeclarationNode AddNamespace<TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode; protected abstract TDeclarationNode AddMembers<TDeclarationNode>(TDeclarationNode destination, IEnumerable<SyntaxNode> members) where TDeclarationNode : SyntaxNode; public abstract TDeclarationNode AddParameters<TDeclarationNode>(TDeclarationNode destinationMember, IEnumerable<IParameterSymbol> parameters, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode; public abstract TDeclarationNode AddAttributes<TDeclarationNode>(TDeclarationNode destination, IEnumerable<AttributeData> attributes, SyntaxToken? target, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode; public abstract TDeclarationNode RemoveAttribute<TDeclarationNode>(TDeclarationNode destination, SyntaxNode attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode; public abstract TDeclarationNode RemoveAttribute<TDeclarationNode>(TDeclarationNode destination, AttributeData attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode; public abstract TDeclarationNode AddStatements<TDeclarationNode>(TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode; public abstract TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, IEnumerable<SyntaxToken> newModifiers, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode; public abstract TDeclarationNode UpdateDeclarationAccessibility<TDeclarationNode>(TDeclarationNode declaration, Accessibility newAccessibility, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode; public abstract TDeclarationNode UpdateDeclarationType<TDeclarationNode>(TDeclarationNode declaration, ITypeSymbol newType, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode; public abstract TDeclarationNode UpdateDeclarationMembers<TDeclarationNode>(TDeclarationNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) where TDeclarationNode : SyntaxNode; public abstract CodeGenerationDestination GetDestination(SyntaxNode node); public abstract SyntaxNode CreateEventDeclaration(IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options); public abstract SyntaxNode CreateFieldDeclaration(IFieldSymbol field, CodeGenerationDestination destination, CodeGenerationOptions options); public abstract SyntaxNode CreateMethodDeclaration(IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options); public abstract SyntaxNode CreatePropertyDeclaration(IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options); public abstract SyntaxNode CreateNamedTypeDeclaration(INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken); public abstract SyntaxNode CreateNamespaceDeclaration(INamespaceSymbol @namespace, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken); protected abstract AbstractImportsAdder CreateImportsAdder(Document document); protected static T Cast<T>(object value) { return (T)value; } protected static void CheckDeclarationNode<TDeclarationNode>(SyntaxNode destination) where TDeclarationNode : SyntaxNode { if (destination == null) { throw new ArgumentNullException(nameof(destination)); } if (!(destination is TDeclarationNode)) { throw new ArgumentException( string.Format(WorkspacesResources.Destination_type_must_be_a_0_but_given_one_is_1, typeof(TDeclarationNode).Name, destination.GetType().Name), nameof(destination)); } } protected static void CheckDeclarationNode<TDeclarationNode1, TDeclarationNode2>(SyntaxNode destination) where TDeclarationNode1 : SyntaxNode where TDeclarationNode2 : SyntaxNode { if (destination == null) { throw new ArgumentNullException(nameof(destination)); } if (!(destination is TDeclarationNode1) && !(destination is TDeclarationNode2)) { throw new ArgumentException( string.Format(WorkspacesResources.Destination_type_must_be_a_0_or_a_1_but_given_one_is_2, typeof(TDeclarationNode1).Name, typeof(TDeclarationNode2).Name, destination.GetType().Name), nameof(destination)); } } protected static void CheckDeclarationNode<TDeclarationNode1, TDeclarationNode2, TDeclarationNode3>(SyntaxNode destination) where TDeclarationNode1 : SyntaxNode where TDeclarationNode2 : SyntaxNode where TDeclarationNode3 : SyntaxNode { if (destination == null) { throw new ArgumentNullException(nameof(destination)); } if (!(destination is TDeclarationNode1) && !(destination is TDeclarationNode2) && !(destination is TDeclarationNode3)) { throw new ArgumentException( string.Format(WorkspacesResources.Destination_type_must_be_a_0_1_or_2_but_given_one_is_3, typeof(TDeclarationNode1).Name, typeof(TDeclarationNode2).Name, typeof(TDeclarationNode3).Name, destination.GetType().Name), nameof(destination)); } } protected static void CheckDeclarationNode<TDeclarationNode1, TDeclarationNode2, TDeclarationNode3, TDeclarationNode4>(SyntaxNode destination) where TDeclarationNode1 : SyntaxNode where TDeclarationNode2 : SyntaxNode where TDeclarationNode3 : SyntaxNode where TDeclarationNode4 : SyntaxNode { if (!(destination is TDeclarationNode1) && !(destination is TDeclarationNode2) && !(destination is TDeclarationNode3) && !(destination is TDeclarationNode4)) { throw new ArgumentException( string.Format(WorkspacesResources.Destination_type_must_be_a_0_1_or_2_but_given_one_is_3, typeof(TDeclarationNode1).Name, typeof(TDeclarationNode2).Name, typeof(TDeclarationNode3).Name, typeof(TDeclarationNode4).Name), nameof(destination)); } } private async Task<Document> GetEditAsync( Solution solution, INamespaceOrTypeSymbol destination, Func<SyntaxNode, CodeGenerationOptions, IList<bool>, CancellationToken, SyntaxNode> declarationTransform, CodeGenerationOptions options, IEnumerable<ISymbol> members, CancellationToken cancellationToken) { options = options ?? CodeGenerationOptions.Default; var result = await this.FindMostRelevantDeclarationAsync(solution, destination, options, cancellationToken).ConfigureAwait(false); SyntaxNode destinationDeclaration = result.Item1; IList<bool> availableIndices = result.Item2; if (destinationDeclaration == null) { throw new ArgumentException(WorkspacesResources.Could_not_find_location_to_generation_symbol_into); } var transformedDeclaration = declarationTransform(destinationDeclaration, options, availableIndices, cancellationToken); var destinationTree = destinationDeclaration.SyntaxTree; var root = await destinationTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var currentRoot = root.ReplaceNode(destinationDeclaration, transformedDeclaration); var oldDocument = solution.GetDocument(destinationTree); var newDocument = oldDocument.WithSyntaxRoot(currentRoot); if (options.AddImports) { var adder = this.CreateImportsAdder(newDocument); newDocument = await adder.AddAsync(members, options.PlaceSystemNamespaceFirst, options, cancellationToken).ConfigureAwait(false); } return newDocument; } protected TDeclarationNode AddMembers<TDeclarationNode>( TDeclarationNode destination, IEnumerable<ISymbol> members, IList<bool> availableIndices, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode { var membersList = members.ToList(); if (membersList.Count > 1) { options = CreateOptionsForMultipleMembers(options); } var currentDestination = destination; // Filter out the members that are implicitly declared. They're implicit, hence we do // not want an explicit declaration. var filteredMembers = membersList.Where(m => !m.IsImplicitlyDeclared); if (options.AutoInsertionLocation) { foreach (var member in filteredMembers) { cancellationToken.ThrowIfCancellationRequested(); currentDestination = member.TypeSwitch( (IEventSymbol @event) => this.AddEvent(currentDestination, @event, options, availableIndices), (IFieldSymbol field) => this.AddField(currentDestination, field, options, availableIndices), (IPropertySymbol property) => this.AddProperty(currentDestination, property, options, availableIndices), (IMethodSymbol method) => this.AddMethod(currentDestination, method, options, availableIndices), (INamedTypeSymbol namedType) => this.AddNamedType(currentDestination, namedType, options, availableIndices, cancellationToken), (INamespaceSymbol @namespace) => this.AddNamespace(currentDestination, @namespace, options, availableIndices, cancellationToken), _ => currentDestination); } } else { var newMembers = new List<SyntaxNode>(); var codeGenerationDestination = GetDestination(destination); foreach (var member in filteredMembers) { cancellationToken.ThrowIfCancellationRequested(); var newMember = member.TypeSwitch( (IEventSymbol @event) => this.CreateEventDeclaration(@event, codeGenerationDestination, options), (IFieldSymbol field) => this.CreateFieldDeclaration(field, codeGenerationDestination, options), (IPropertySymbol property) => this.CreatePropertyDeclaration(property, codeGenerationDestination, options), (IMethodSymbol method) => this.CreateMethodDeclaration(method, codeGenerationDestination, options), (INamedTypeSymbol namedType) => this.CreateNamedTypeDeclaration(namedType, codeGenerationDestination, options, cancellationToken), (INamespaceSymbol @namespace) => this.CreateNamespaceDeclaration(@namespace, codeGenerationDestination, options, cancellationToken), _ => null); if (newMember != null) { newMembers.Add(newMember); } } // Metadata as source generates complete declarations and doesn't modify // existing ones. We can take the members to generate, sort them once, // and then add them in that order to the end of the destination. if (!GeneratingEnum(members)) { newMembers.Sort(GetMemberComparer()); } currentDestination = this.AddMembers(currentDestination, newMembers); } return currentDestination; } private bool GeneratingEnum(IEnumerable<ISymbol> members) { var field = members.OfType<IFieldSymbol>().FirstOrDefault(); return field != null && field.ContainingType.IsEnumType(); } protected abstract IComparer<SyntaxNode> GetMemberComparer(); protected static CodeGenerationOptions CreateOptionsForMultipleMembers(CodeGenerationOptions options) { // For now we ignore the afterThisLocation/beforeThisLocation if we're adding // multiple members. In the future it would be nice to appropriately handle this. // The difficulty lies with ensuring that we properly understand the position we're // inserting into, even as we change the type by adding multiple members. Not // impossible to figure out, but out of scope right now. options = new CodeGenerationOptions( options.ContextLocation, addImports: options.AddImports, placeSystemNamespaceFirst: options.PlaceSystemNamespaceFirst, additionalImports: options.AdditionalImports, generateMembers: options.GenerateMembers, mergeNestedNamespaces: options.MergeNestedNamespaces, mergeAttributes: options.MergeAttributes, generateDefaultAccessibility: options.GenerateDefaultAccessibility, generateMethodBodies: options.GenerateMethodBodies, generateDocumentationComments: options.GenerateDocumentationComments, autoInsertionLocation: options.AutoInsertionLocation, reuseSyntax: options.ReuseSyntax); return options; } public Task<Document> AddEventAsync(Solution solution, INamedTypeSymbol destination, IEventSymbol @event, CodeGenerationOptions options, CancellationToken cancellationToken) { return GetEditAsync( solution, destination, (t, opts, ai, ct) => AddEvent(t, @event, opts, ai), options, new[] { @event }, cancellationToken); } public Task<Document> AddFieldAsync(Solution solution, INamedTypeSymbol destination, IFieldSymbol field, CodeGenerationOptions options, CancellationToken cancellationToken) { return GetEditAsync( solution, destination, (t, opts, ai, ct) => AddField(t, field, opts, ai), options, new[] { field }, cancellationToken); } public Task<Document> AddPropertyAsync(Solution solution, INamedTypeSymbol destination, IPropertySymbol property, CodeGenerationOptions options, CancellationToken cancellationToken) { return GetEditAsync( solution, destination, (t, opts, ai, ct) => AddProperty(t, property, opts, ai), options, new[] { property }, cancellationToken); } public Task<Document> AddNamedTypeAsync(Solution solution, INamedTypeSymbol destination, INamedTypeSymbol namedType, CodeGenerationOptions options, CancellationToken cancellationToken) { return GetEditAsync( solution, destination, (t, opts, ai, ct) => AddNamedType(t, namedType, opts, ai, ct), options, new[] { namedType }, cancellationToken); } public Task<Document> AddNamedTypeAsync(Solution solution, INamespaceSymbol destination, INamedTypeSymbol namedType, CodeGenerationOptions options, CancellationToken cancellationToken) { return GetEditAsync( solution, destination, (t, opts, ai, ct) => AddNamedType(t, namedType, opts, ai, ct), options, new[] { namedType }, cancellationToken); } public Task<Document> AddNamespaceAsync(Solution solution, INamespaceSymbol destination, INamespaceSymbol @namespace, CodeGenerationOptions options, CancellationToken cancellationToken) { return GetEditAsync( solution, destination, (t, opts, ai, ct) => AddNamespace(t, @namespace, opts, ai, ct), options, new[] { @namespace }, cancellationToken); } public Task<Document> AddMethodAsync(Solution solution, INamedTypeSymbol destination, IMethodSymbol method, CodeGenerationOptions options, CancellationToken cancellationToken) { return GetEditAsync( solution, destination, (t, opts, ai, ct) => AddMethod(t, method, opts, ai), options, new[] { method }, cancellationToken); } public Task<Document> AddMembersAsync(Solution solution, INamedTypeSymbol destination, IEnumerable<ISymbol> members, CodeGenerationOptions options, CancellationToken cancellationToken) { return GetEditAsync( solution, destination, (t, opts, ai, ct) => AddMembers(t, members, ai, opts, ct), options, members, cancellationToken); } public Task<Document> AddNamespaceOrTypeAsync(Solution solution, INamespaceSymbol destination, INamespaceOrTypeSymbol namespaceOrType, CodeGenerationOptions options, CancellationToken cancellationToken) { if (namespaceOrType == null) { throw new ArgumentNullException(nameof(namespaceOrType)); } if (namespaceOrType is INamespaceSymbol) { return AddNamespaceAsync(solution, destination, (INamespaceSymbol)namespaceOrType, options, cancellationToken); } else { return AddNamedTypeAsync(solution, destination, (INamedTypeSymbol)namespaceOrType, options, cancellationToken); } } protected static void CheckLocation<TDeclarationNode>( TDeclarationNode destinationMember, Location location) where TDeclarationNode : SyntaxNode { if (location == null) { throw new ArgumentException(WorkspacesResources.No_location_provided_to_add_statements_to); } if (!location.IsInSource) { throw new ArgumentException(WorkspacesResources.Destination_location_was_not_in_source); } if (location.SourceTree != destinationMember.SyntaxTree) { throw new ArgumentException(WorkspacesResources.Destination_location_was_from_a_different_tree); } } protected static void ComputePositionAndTriviaForRemoveAttributeList( SyntaxNode attributeList, Func<SyntaxTrivia, bool> isEndOfLineTrivia, out int positionOfRemovedNode, out IEnumerable<SyntaxTrivia> triviaOfRemovedNode) { positionOfRemovedNode = attributeList.FullSpan.Start; var leading = attributeList.GetLeadingTrivia(); var trailing = attributeList.GetTrailingTrivia(); if (trailing.Count >= 1 && isEndOfLineTrivia(trailing.Last())) { // Remove redundant trailing trivia as we are removing the entire attribute list. triviaOfRemovedNode = leading; } else { triviaOfRemovedNode = leading.Concat(trailing); } } protected static void ComputePositionAndTriviaForRemoveAttributeFromAttributeList( SyntaxNode attributeToRemove, Func<SyntaxToken, bool> isComma, out int positionOfRemovedNode, out IEnumerable<SyntaxTrivia> triviaOfRemovedNode) { positionOfRemovedNode = attributeToRemove.FullSpan.Start; var root = attributeToRemove.SyntaxTree.GetRoot(); var previousToken = root.FindToken(attributeToRemove.FullSpan.Start - 1); var leading = isComma(previousToken) ? previousToken.LeadingTrivia : attributeToRemove.GetLeadingTrivia(); var nextToken = root.FindToken(attributeToRemove.FullSpan.End + 1); var trailing = isComma(nextToken) ? nextToken.TrailingTrivia : attributeToRemove.GetTrailingTrivia(); triviaOfRemovedNode = leading.Concat(trailing); } protected static T AppendTriviaAtPosition<T>(T node, int position, SyntaxTriviaList trivia) where T : SyntaxNode { if (trivia.Any()) { var tokenToInsertTrivia = node.FindToken(position); var tokenWithInsertedTrivia = tokenToInsertTrivia.WithLeadingTrivia(trivia.Concat(tokenToInsertTrivia.LeadingTrivia)); return node.ReplaceToken(tokenToInsertTrivia, tokenWithInsertedTrivia); } return node; } protected static IList<SyntaxToken> GetUpdatedDeclarationAccessibilityModifiers(IList<SyntaxToken> newModifierTokens, SyntaxTokenList modifiersList, Func<SyntaxToken, bool> isAccessibilityModifier) { var updatedModifiersList = new List<SyntaxToken>(); var anyAccessModifierSeen = false; foreach (var modifier in modifiersList) { SyntaxToken newModifier; if (isAccessibilityModifier(modifier)) { if (newModifierTokens.Count == 0) { continue; } newModifier = newModifierTokens[0] .WithLeadingTrivia(modifier.LeadingTrivia) .WithTrailingTrivia(modifier.TrailingTrivia); newModifierTokens.RemoveAt(0); anyAccessModifierSeen = true; } else { if (anyAccessModifierSeen && newModifierTokens.Any()) { updatedModifiersList.AddRange(newModifierTokens); newModifierTokens.Clear(); } newModifier = modifier; } updatedModifiersList.Add(newModifier); } if (!anyAccessModifierSeen) { updatedModifiersList.InsertRange(0, newModifierTokens); } else { updatedModifiersList.AddRange(newModifierTokens); } return updatedModifiersList; } } }
//Apache2,GitHub:mongodb-csharp using System; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using MongoDB.Bson; using MongoDB.Util; namespace MongoDB { /// <summary> /// Oid is an immutable object that represents a Mongo ObjectId. /// </summary> [Serializable] public sealed class Oid : IEquatable<Oid>, IComparable<Oid>, IFormattable, IXmlSerializable { private static readonly OidGenerator OidGenerator = new OidGenerator(); private byte[] _bytes; /// <summary> /// Initializes a new instance of the <see cref="Oid"/> class. /// </summary> /// <remarks> /// Needed for some serializers. /// </remarks> private Oid() { } /// <summary> /// Initializes a new instance of the <see cref = "Oid" /> class. /// </summary> /// <param name = "value">The value.</param> public Oid(string value) { if(value == null) throw new ArgumentNullException("value"); ParseBytes(value); } /// <summary> /// Initializes a new instance of the <see cref = "Oid" /> class. /// </summary> /// <param name = "value">The value.</param> public Oid(byte[] value) { if(value == null) throw new ArgumentNullException("value"); _bytes = new byte[12]; Array.Copy(value, _bytes, 12); } /// <summary> /// Initializes a new instance of the <see cref="Oid"/> class. /// </summary> /// <param name="oid">The oid.</param> public Oid(Oid oid) { if(oid == null) throw new ArgumentNullException("oid"); _bytes = oid._bytes; } /// <summary> /// Gets the created. /// </summary> /// <value>The created.</value> public DateTime Created { get { var time = new byte[4]; Array.Copy(_bytes, time, 4); Array.Reverse(time); var seconds = BitConverter.ToInt32(time, 0); return BsonInfo.Epoch.AddSeconds(seconds); } } /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <param name = "other">An object to compare with this object.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings: /// Value /// Meaning /// Less than zero /// This object is less than the <paramref name = "other" /> parameter. /// Zero /// This object is equal to <paramref name = "other" />. /// Greater than zero /// This object is greater than <paramref name = "other" />. /// </returns> public int CompareTo(Oid other) { if(ReferenceEquals(other, null)) return 1; var otherBytes = other._bytes; for(var x = 0; x < _bytes.Length; x++) if(_bytes[x] < otherBytes[x]) return -1; else if(_bytes[x] > otherBytes[x]) return 1; return 0; } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name = "other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name = "other" /> parameter; otherwise, false. /// </returns> public bool Equals(Oid other) { return CompareTo(other) == 0; } /// <summary> /// Determines whether the specified <see cref = "System.Object" /> is equal to this instance. /// </summary> /// <param name = "obj">The <see cref = "System.Object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref = "System.Object" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if(obj is Oid) return CompareTo((Oid)obj) == 0; return false; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { return ToString().GetHashCode(); } /// <summary> /// Returns a <see cref = "System.String" /> that represents this instance. /// </summary> /// <returns> /// A <see cref = "System.String" /> that represents this instance. /// </returns> public override string ToString() { return BitConverter.ToString(_bytes).Replace("-", "").ToLower(); } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <param name="format">The format.</param> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> /// <remarks> /// J = Returns Javascript string /// </remarks> public string ToString(string format) { if(string.IsNullOrEmpty(format)) return ToString(); if(format == "J") return String.Format("\"{0}\"", ToString()); throw new ArgumentException("Invalid format string","format"); } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <param name="format">The format.</param> /// <param name="formatProvider">The format provider.</param> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> /// <remarks> /// J = Returns Javascript string /// </remarks> public string ToString(string format, IFormatProvider formatProvider) { return ToString(format); } /// <summary> /// Converts the Oid to a byte array. /// </summary> public byte[] ToByteArray() { var ret = new byte[12]; Array.Copy(_bytes, ret, 12); return ret; } /// <summary> /// Generates an Oid using OidGenerator. /// </summary> /// <returns> /// A <see cref = "Oid" /> /// </returns> public static Oid NewOid() { return OidGenerator.Generate(); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name = "a">A.</param> /// <param name = "b">The b.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(Oid a, Oid b){ if (ReferenceEquals(a, b)){ return true; } if((Object)a == null || (Object)b == null){ return false; } return a.Equals(b); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name = "a">A.</param> /// <param name = "b">The b.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(Oid a, Oid b) { return !(a == b); } /// <summary> /// Implements the operator &gt;. /// </summary> /// <param name = "a">A.</param> /// <param name = "b">The b.</param> /// <returns>The result of the operator.</returns> public static bool operator >(Oid a, Oid b) { return a.CompareTo(b) > 0; } /// <summary> /// Implements the operator &lt;. /// </summary> /// <param name = "a">A.</param> /// <param name = "b">The b.</param> /// <returns>The result of the operator.</returns> public static bool operator <(Oid a, Oid b) { return a.CompareTo(b) < 0; } /// <summary> /// Validates the hex. /// </summary> /// <param name = "value">The value.</param> private void ValidateHex(string value) { if(value == null || value.Length != 24) throw new ArgumentException("Oid strings should be 24 characters"); var notHexChars = new Regex(@"[^A-Fa-f0-9]", RegexOptions.None); if(notHexChars.IsMatch(value)) throw new ArgumentOutOfRangeException("value", "Value contains invalid characters"); } /// <summary> /// Decodes the hex. /// </summary> /// <param name = "value">The value.</param> /// <returns></returns> private static byte[] DecodeHex(string value) { var numberChars = value.Length; var bytes = new byte[numberChars/2]; for(var i = 0; i < numberChars; i += 2) try { bytes[i/2] = Convert.ToByte(value.Substring(i, 2), 16); } catch { //failed to convert these 2 chars, they may contain illegal charracters bytes[i/2] = 0; } return bytes; } /// <summary> /// Parses the bytes. /// </summary> /// <param name="value">The value.</param> private void ParseBytes(string value) { value = value.Replace("\"", ""); ValidateHex(value); _bytes = DecodeHex(value); } /// <summary> /// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class. /// </summary> /// <returns> /// An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method. /// </returns> XmlSchema IXmlSerializable.GetSchema() { return null; } /// <summary> /// Generates an object from its XML representation. /// </summary> /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param> void IXmlSerializable.ReadXml(XmlReader reader) { ParseBytes(reader.ReadElementContentAsString()); } /// <summary> /// Converts an object into its XML representation. /// </summary> /// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized.</param> void IXmlSerializable.WriteXml(XmlWriter writer) { writer.WriteString(ToString()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using EstimoteSdk; using Android.Webkit; using SharedClassLib; using System.Threading.Tasks; using Java.Lang; namespace RetailBeacon.Droid { public class RangingFragment : Fragment, BeaconManager.IServiceReadyCallback, BeaconManager.IRangingListener { private BeaconManager _beaconManager; private Region _region; private WebView mainWebView; private Beacon latetsClosestBeacon; private Button btnCategory; private string url; private List<beaconClass> listOfKnownBeacons = new List<beaconClass>(); private List<Beacon> listOfBeacons; private beaconClass apa; public void OnBeaconsDiscovered(Region region, IList<Beacon> beacons) { throw new NotImplementedException(); } public override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Console.WriteLine("LOGGAR ONCREATE"); //mainWebView = View.FindViewById<WebView>(Resource.Id.mainWebView); //mainWebView.SetWebViewClient(new WebViewClient()); //_beaconManager = new BeaconManager(Application.Context); //_region = new Region("ranged region", "b9407f30-f5f8-466e-aff9-25556b57fe6d"); //_beaconManager.Ranging += (sender2, e) => //{ // foreach (Beacon beacon in e.Beacons) // { // string url = getUrlForBeaconIfThereIsOne(beacon); // if (url != "noUrl") // { // mainWebView.LoadUrl(url); // latetsClosestBeacon = beacon; // break; // } // } //}; // Create your fragment here } private string[] getUrlForBeaconIfThereIsOne(Beacon closestBeacon) { string[] returnMessage = {"noUrl", "noUrl"}; if (!BeaconCalculator.isSameBeacon(latetsClosestBeacon, closestBeacon)) { Console.WriteLine("Returning in isSameBeacon"); return returnMessage; } Console.WriteLine("Beacons range is: " + BeaconCalculator.calculateDistance(closestBeacon)); string range = BeaconCalculator.calculateDistance(closestBeacon); switch (range) { case "Near": returnMessage = Api.productGroupInfo (closestBeacon.Major.ToString () + closestBeacon.Minor.ToString () + "N"); break; case "Immediate": returnMessage [0] = Api.productInfo (closestBeacon.Major.ToString () + closestBeacon.Minor.ToString () + "I"); if (returnMessage [0] == "noUrl") { returnMessage = Api.productGroupInfo(closestBeacon.Major.ToString() + closestBeacon.Minor.ToString() + "N"); } break; default: break; } return returnMessage; } public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Use this to return your custom view for this Fragment // return inflater.Inflate(Resource.Layout.YourFragment, container, false); Console.WriteLine("LOGGAR HERE"); View view = inflater.Inflate(Resource.Layout.fragmentinstoreinfo, container, false); // mainWebView = view.FindViewById<WebView>(Resource.Id.mainWebView); // mainWebView.SetWebViewClient(new WebViewClient()); btnCategory = view.FindViewById<Button>(Resource.Id.button1); btnCategory.Click += delegate { startWebActivity(); }; _beaconManager = new BeaconManager(Application.Context); _beaconManager.SetBackgroundScanPeriod (10000, 10000); _region = new Region("ranged region", "b9407f30-f5f8-466e-aff9-25556b57fe6d"); _beaconManager.Ranging += (sender2, e) => { if (MainActivity.webviewIsActive || MainActivity.mCurrentFragment != MainActivity.mRangingFragment) { return; } foreach (Beacon beacon in e.Beacons) { beaconClass bb = new beaconClass(beacon); listOfKnownBeacons.Add(bb); if(!listOfKnownBeacons.Any(x => x.MajorMinor == (beacon.Major.ToString() + beacon.Minor.ToString()))) { listOfKnownBeacons.Add(new beaconClass(beacon)); } beaconClass knownBeacon = listOfKnownBeacons.FirstOrDefault(x => x.MajorMinor == (beacon.Major.ToString() + beacon.Minor.ToString())); if(knownBeacon.url == "noUrl"){ return; } switch(knownBeacon.info){ case "Category": btnCategory.Text = knownBeacon.name; btnCategory.Visibility = ViewStates.Visible; url = knownBeacon.url; break; case "Product": if(BeaconCalculator.calculateDistance(beacon) == "Immediate") startWebActivity(knownBeacon.url); break; default: break; } // return; // var message = getUrlForBeaconIfThereIsOne(beacon); // // if (message[0] != "noUrl") // { // if (BeaconCalculator.calculateDistance(beacon)=="Immediate") // { // var webactivity = new Intent(this.Activity, typeof(WebViewActivity)); // webactivity.PutExtra("URL", message[0]); // StartActivity(webactivity); // break; // } // else // { // btnCategory.Text = message[1]; // btnCategory.Visibility = ViewStates.Visible; // url = message[0]; // } // } } }; _beaconManager.StartRanging(_region); _beaconManager.Connect(this); //var toolbarBottom = view.FindViewById<Toolbar>(Resource.Id.toolbar_bottom); //toolbarBottom.Title = "Photo Editing"; //toolbarBottom.InflateMenu(Resource.Menu.bottomMenu); ////Add menu click handler //toolbarBottom.MenuItemClick += (sender, e) => { // //Toast.MakeText(this, "Bottom toolbar pressed: " + e.Item.TitleFormatted, ToastLength.Short).Show(); //}; return view; } private void startWebActivity(){ if (!MainActivity.webviewIsActive) { var webactivity = new Intent (this.Activity, typeof(WebViewActivity)); webactivity.PutExtra ("URL", url); StartActivity (webactivity); } } private void startWebActivity(string URL){ if (!MainActivity.webviewIsActive) { var webactivity = new Intent (this.Activity, typeof(WebViewActivity)); webactivity.PutExtra ("URL", URL); StartActivity (webactivity); } } public void OnServiceReady() { Console.WriteLine("LOGGAR ONSERVICEREADY"); _beaconManager.StartRanging(_region); } } }
// // MiniModeWindow.cs // // Authors: // Aaron Bockover <aaron@abock.org> // Felipe Almeida Lessa // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2006-2010 Novell, Inc. // Copyright (C) 2006 Felipe Almeida Lessa // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Gtk; using Mono.Unix; using Hyena.Widgets; using Hyena.Gui; using Banshee.Collection; using Banshee.Collection.Gui; using Banshee.Gui; using Banshee.Gui.Widgets; using Banshee.Sources.Gui; using Banshee.MediaEngine; using Banshee.ServiceStack; using Banshee.Widgets; using Banshee.Configuration; namespace Banshee.MiniMode { public class MiniMode : Banshee.Gui.BaseClientWindow { const string CONFIG_NAMESPACE = "minimode"; static readonly SchemaEntry<int> WidthSchema = WindowConfiguration.NewWidthSchema (CONFIG_NAMESPACE, 0); static readonly SchemaEntry<int> HeightSchema = WindowConfiguration.NewHeightSchema (CONFIG_NAMESPACE, 0); static readonly SchemaEntry<int> XPosSchema = WindowConfiguration.NewXPosSchema (CONFIG_NAMESPACE); static readonly SchemaEntry<int> YPosSchema = WindowConfiguration.NewYPosSchema (CONFIG_NAMESPACE); static readonly SchemaEntry<bool> MaximizedSchema = WindowConfiguration.NewMaximizedSchema (CONFIG_NAMESPACE); private TrackInfoDisplay track_info_display; private ConnectedVolumeButton volume_button; private SourceComboBox source_combo_box; private ConnectedSeekSlider seek_slider; private BaseClientWindow default_main_window; public MiniMode (BaseClientWindow defaultMainWindow) : base (Catalog.GetString ("Banshee Media Player"), new WindowConfiguration (WidthSchema, HeightSchema, XPosSchema, YPosSchema, MaximizedSchema)) { default_main_window = defaultMainWindow; BorderWidth = 12; Resizable = false; Build (); ShowAll (); SetHeightLimit (); } private void Build () { var vbox = new VBox () { Spacing = 12 }; var top = new HBox () { Spacing = 6 }; var bot = new HBox () { Spacing = 6 }; vbox.PackStart (top, false, false, 0); vbox.PackStart (bot, false, false, 0); // Top row: playback buttons, seek slider, full-mode button, volume Widget previous_button = ActionService.PlaybackActions["PreviousAction"].CreateToolItem (); Widget playpause_button = ActionService.PlaybackActions["PlayPauseAction"].CreateToolItem (); Widget button = ActionService.PlaybackActions["NextAction"].CreateToolItem (); Menu menu = ActionService.PlaybackActions.ShuffleActions.CreateMenu (); MenuButton next_button = new MenuButton (button, menu, true); top.PackStart (previous_button, false, false, 0); top.PackStart (playpause_button, false, false, 0); top.PackStart (next_button, false, false, 0); seek_slider = new ConnectedSeekSlider (); top.PackStart (seek_slider, true, true, 0); var fullmode_button = new Button () { Label = Catalog.GetString ("Full Mode"), Image = new Image (Stock.LeaveFullscreen, Gtk.IconSize.Button), Relief = Gtk.ReliefStyle.None }; fullmode_button.Clicked += OnFullmode; top.PackStart (fullmode_button, false, false, 0); volume_button = new ConnectedVolumeButton (); top.PackStart (volume_button, false, false, 0); // Bottom row: source dropdown, track info display (cover art, etc), repeat mode button source_combo_box = new SourceComboBox (); bot.PackStart (source_combo_box, false, false, 0); track_info_display = new ClassicTrackInfoDisplay (); track_info_display.WidthRequest = 250; bot.PackStart (track_info_display, true, true, 0); var repeat_align = new Alignment (1, 1, 1, 1); var repeat_toggle_button = new RepeatActionButton (true); repeat_align.Add (repeat_toggle_button); bot.PackEnd (repeat_align, false, false, 0); fullmode_button.TooltipText = Catalog.GetString ("Switch back to full mode"); repeat_toggle_button.TooltipText = Catalog.GetString ("Change repeat playback mode"); Add (vbox); } protected override void Initialize () { } private void SetHeightLimit () { Gdk.Geometry limits = new Gdk.Geometry (); limits.MinHeight = -1; limits.MaxHeight = -1; int minimum_width, natural_width; GetPreferredWidth (out minimum_width, out natural_width); limits.MinWidth = minimum_width; limits.MaxWidth = Gdk.Screen.Default.Width; SetGeometryHints (this, limits, Gdk.WindowHints.MaxSize | Gdk.WindowHints.MinSize); } public void Enable () { source_combo_box.UpdateActiveSource (); default_main_window.Hide (); OverrideFullscreen (); Show (); } public void Disable () { Hide (); RelinquishFullscreen (); default_main_window.Show (); } private void OnFullmode (object o, EventArgs a) { ElementsService.PrimaryWindow = default_main_window; Disable (); } #region Mini-mode Fullscreen Override private ViewActions.FullscreenHandler previous_fullscreen_handler; private void OverrideFullscreen () { InterfaceActionService service = ServiceManager.Get<InterfaceActionService> (); if (service == null || service.ViewActions == null) { return; } previous_fullscreen_handler = service.ViewActions.Fullscreen; service.ViewActions.Fullscreen = FullscreenHandler; } private void RelinquishFullscreen () { InterfaceActionService service = ServiceManager.Get<InterfaceActionService> (); if (service == null || service.ViewActions == null) { return; } service.ViewActions.Fullscreen = previous_fullscreen_handler; } private void FullscreenHandler (bool fullscreen) { // Do nothing, we don't want full-screen while in mini-mode. } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Contracts; using System.Numerics.Hashing; namespace System.Drawing { /// <summary> /// <para> /// Stores the location and size of a rectangular region. /// </para> /// </summary> [Serializable] public struct RectangleF : IEquatable<RectangleF> { /// <summary> /// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> /// class. /// </summary> public static readonly RectangleF Empty = new RectangleF(); private float _x; private float _y; private float _width; private float _height; /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> /// class with the specified location and size. /// </para> /// </summary> public RectangleF(float x, float y, float width, float height) { _x = x; _y = y; _width = width; _height = height; } /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> /// class with the specified location /// and size. /// </para> /// </summary> public RectangleF(PointF location, SizeF size) { _x = location.X; _y = location.Y; _width = size.Width; _height = size.Height; } /// <summary> /// <para> /// Creates a new <see cref='System.Drawing.RectangleF'/> with /// the specified location and size. /// </para> /// </summary> public static RectangleF FromLTRB(float left, float top, float right, float bottom) => new RectangleF(left, top, right - left, bottom - top); /// <summary> /// <para> /// Gets or sets the coordinates of the upper-left corner of /// the rectangular region represented by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public PointF Location { get { return new PointF(X, Y); } set { X = value.X; Y = value.Y; } } /// <summary> /// <para> /// Gets or sets the size of this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public SizeF Size { get { return new SizeF(Width, Height); } set { Width = value.Width; Height = value.Height; } } /// <summary> /// <para> /// Gets or sets the x-coordinate of the /// upper-left corner of the rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float X { get { return _x; } set { _x = value; } } /// <summary> /// <para> /// Gets or sets the y-coordinate of the /// upper-left corner of the rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float Y { get { return _y; } set { _y = value; } } /// <summary> /// <para> /// Gets or sets the width of the rectangular /// region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float Width { get { return _width; } set { _width = value; } } /// <summary> /// <para> /// Gets or sets the height of the /// rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float Height { get { return _height; } set { _height = value; } } /// <summary> /// <para> /// Gets the x-coordinate of the upper-left corner of the /// rectangular region defined by this <see cref='System.Drawing.RectangleF'/> . /// </para> /// </summary> public float Left => X; /// <summary> /// <para> /// Gets the y-coordinate of the upper-left corner of the /// rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float Top => Y; /// <summary> /// <para> /// Gets the x-coordinate of the lower-right corner of the /// rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float Right => X + Width; /// <summary> /// <para> /// Gets the y-coordinate of the lower-right corner of the /// rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float Bottom => Y + Height; /// <summary> /// <para> /// Tests whether this <see cref='System.Drawing.RectangleF'/> has a <see cref='System.Drawing.RectangleF.Width'/> or a <see cref='System.Drawing.RectangleF.Height'/> of 0. /// </para> /// </summary> public bool IsEmpty => (Width <= 0) || (Height <= 0); /// <summary> /// <para> /// Tests whether <paramref name="obj"/> is a <see cref='System.Drawing.RectangleF'/> with the same location and size of this /// <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public override bool Equals(object obj) => obj is RectangleF && Equals((RectangleF)obj); public bool Equals(RectangleF other) => this == other; /// <summary> /// <para> /// Tests whether two <see cref='System.Drawing.RectangleF'/> /// objects have equal location and size. /// </para> /// </summary> public static bool operator ==(RectangleF left, RectangleF right) => left.X == right.X && left.Y == right.Y && left.Width == right.Width && left.Height == right.Height; /// <summary> /// <para> /// Tests whether two <see cref='System.Drawing.RectangleF'/> /// objects differ in location or size. /// </para> /// </summary> public static bool operator !=(RectangleF left, RectangleF right) => !(left == right); /// <summary> /// <para> /// Determines if the specified point is contained within the /// rectangular region defined by this <see cref='System.Drawing.Rectangle'/> . /// </para> /// </summary> [Pure] public bool Contains(float x, float y) => X <= x && x < X + Width && Y <= y && y < Y + Height; /// <summary> /// <para> /// Determines if the specified point is contained within the /// rectangular region defined by this <see cref='System.Drawing.Rectangle'/> . /// </para> /// </summary> [Pure] public bool Contains(PointF pt) => Contains(pt.X, pt.Y); /// <summary> /// <para> /// Determines if the rectangular region represented by /// <paramref name="rect"/> is entirely contained within the rectangular region represented by /// this <see cref='System.Drawing.Rectangle'/> . /// </para> /// </summary> [Pure] public bool Contains(RectangleF rect) => (X <= rect.X) && (rect.X + rect.Width <= X + Width) && (Y <= rect.Y) && (rect.Y + rect.Height <= Y + Height); /// <summary> /// Gets the hash code for this <see cref='System.Drawing.RectangleF'/>. /// </summary> public override int GetHashCode() => HashHelpers.Combine( HashHelpers.Combine(HashHelpers.Combine(X.GetHashCode(), Y.GetHashCode()), Width.GetHashCode()), Height.GetHashCode()); /// <summary> /// <para> /// Inflates this <see cref='System.Drawing.Rectangle'/> /// by the specified amount. /// </para> /// </summary> public void Inflate(float x, float y) { X -= x; Y -= y; Width += 2 * x; Height += 2 * y; } /// <summary> /// Inflates this <see cref='System.Drawing.Rectangle'/> by the specified amount. /// </summary> public void Inflate(SizeF size) => Inflate(size.Width, size.Height); /// <summary> /// <para> /// Creates a <see cref='System.Drawing.Rectangle'/> /// that is inflated by the specified amount. /// </para> /// </summary> public static RectangleF Inflate(RectangleF rect, float x, float y) { RectangleF r = rect; r.Inflate(x, y); return r; } /// <summary> Creates a Rectangle that represents the intersection between this Rectangle and rect. /// </summary> public void Intersect(RectangleF rect) { RectangleF result = Intersect(rect, this); X = result.X; Y = result.Y; Width = result.Width; Height = result.Height; } /// <summary> /// Creates a rectangle that represents the intersection between a and /// b. If there is no intersection, null is returned. /// </summary> [Pure] public static RectangleF Intersect(RectangleF a, RectangleF b) { float x1 = Math.Max(a.X, b.X); float x2 = Math.Min(a.X + a.Width, b.X + b.Width); float y1 = Math.Max(a.Y, b.Y); float y2 = Math.Min(a.Y + a.Height, b.Y + b.Height); if (x2 >= x1 && y2 >= y1) { return new RectangleF(x1, y1, x2 - x1, y2 - y1); } return Empty; } /// <summary> /// Determines if this rectangle intersects with rect. /// </summary> [Pure] public bool IntersectsWith(RectangleF rect) => (rect.X < X + Width) && (X < rect.X + rect.Width) && (rect.Y < Y + Height) && (Y < rect.Y + rect.Height); /// <summary> /// Creates a rectangle that represents the union between a and /// b. /// </summary> [Pure] public static RectangleF Union(RectangleF a, RectangleF b) { float x1 = Math.Min(a.X, b.X); float x2 = Math.Max(a.X + a.Width, b.X + b.Width); float y1 = Math.Min(a.Y, b.Y); float y2 = Math.Max(a.Y + a.Height, b.Y + b.Height); return new RectangleF(x1, y1, x2 - x1, y2 - y1); } /// <summary> /// Adjusts the location of this rectangle by the specified amount. /// </summary> public void Offset(PointF pos) => Offset(pos.X, pos.Y); /// <summary> /// Adjusts the location of this rectangle by the specified amount. /// </summary> public void Offset(float x, float y) { X += x; Y += y; } /// <summary> /// Converts the specified <see cref='System.Drawing.Rectangle'/> to a /// <see cref='System.Drawing.RectangleF'/>. /// </summary> public static implicit operator RectangleF(Rectangle r) => new RectangleF(r.X, r.Y, r.Width, r.Height); /// <summary> /// Converts the <see cref='System.Drawing.RectangleF.Location'/> and <see cref='System.Drawing.RectangleF.Size'/> of this <see cref='System.Drawing.RectangleF'/> to a /// human-readable string. /// </summary> public override string ToString() => "{X=" + X.ToString() + ",Y=" + Y.ToString() + ",Width=" + Width.ToString() + ",Height=" + Height.ToString() + "}"; } }
using System; using System.Net.Mail; using Aggregator.Core.Configuration; using Aggregator.Core.Context; using Aggregator.Core.Interfaces; using Aggregator.Core.Monitoring; using Microsoft.TeamFoundation.Client; using Microsoft.TeamFoundation.Framework.Client; using Microsoft.TeamFoundation.Framework.Common; using Microsoft.TeamFoundation.Framework.Server; using Microsoft.TeamFoundation.WorkItemTracking.Client; #if TFS2015u1 using IVssRequestContext = Microsoft.TeamFoundation.Framework.Server.IVssRequestContext; #else using IVssRequestContext = Microsoft.TeamFoundation.Framework.Server.TeamFoundationRequestContext; #endif #if ADOS2019 using IVssRegistryService = Microsoft.TeamFoundation.Framework.Server.IVssRegistryService; #else using IVssRegistryService = Microsoft.TeamFoundation.Framework.Server.TeamFoundationRegistryService; #endif /// <summary> /// This is the real meat for Plugin and WebService; /// ConsoleApp use fake in <seealso cref="Aggregator.Core.Script.ScriptLibrary"/>. /// </summary> namespace Aggregator.Core.Facade { public class ScriptLibrary : IScriptLibrary { private readonly ILogEvents logger; private readonly IRequestContext requestContext; private readonly ConnectionInfo connectionInfo; private readonly Mailer mailer; public ScriptLibrary(IRuntimeContext context) { this.connectionInfo = context.GetConnectionInfo(); this.requestContext = context.RequestContext; this.logger = context.Logger; this.mailer = new Mailer(context.RequestContext.VssContext); } private class Mailer { #if TFS2017 readonly string NotificationRootPath = FrameworkServerConstants.NotificationRootPath; #else // HACK is it completely useless? readonly string NotificationRootPath = "/Service/Integration/Settings"; #endif #pragma warning disable SA1306 // Field names must begin with lower-case letter private readonly bool Enabled; private readonly string SmtpServer; private readonly int SmtpPort; private readonly bool EnableSsl; private readonly MailAddress FromAddress; #pragma warning restore SA1306 // Field names must begin with lower-case letter internal Mailer(IVssRequestContext requestContext) { this.Enabled = false; try { IVssRegistryService service = requestContext.GetService<IVssRegistryService>(); Microsoft.TeamFoundation.Framework.Server.RegistryEntryCollection registryEntryCollection = service.ReadEntriesFallThru(requestContext, this.NotificationRootPath + "/*"); if (registryEntryCollection["EmailEnabled"].GetValue<bool>(true)) { this.SmtpServer = registryEntryCollection["SmtpServer"].GetValue(string.Empty); this.SmtpPort = registryEntryCollection["SmtpPort"].GetValue<int>(-1); this.EnableSsl = registryEntryCollection["SmtpEnableSsl"].GetValue<bool>(false); this.FromAddress = null; string value = registryEntryCollection["EmailNotificationFromAddress"].GetValue(string.Empty); if (!string.IsNullOrEmpty(value) && !string.IsNullOrEmpty(this.SmtpServer)) { this.FromAddress = new MailAddress(value); this.Enabled = true; } } } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine($"SendMail failed: {ex.Message}"); } } internal void Send(string to, string subject, string body) { if (this.Enabled) { using (SmtpClient client = new SmtpClient()) { client.Host = this.SmtpServer; client.Port = this.SmtpPort; client.EnableSsl = this.EnableSsl; using (MailMessage message = new MailMessage()) { message.From = this.FromAddress; message.To.Add(to); message.Subject = subject; message.Body = body; client.Send(message); } } } } } public void SendMail(string to, string subject, string body) { try { this.mailer.Send(to, subject, body); } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine($"SendMail failed: {ex.Message}"); } } // Get Email Address from TFS Account or Display Name // source: https://paulselles.wordpress.com/2014/03/24/tfs-api-tfs-user-email-address-lookup-and-reverse-lookup/ public string GetEmailAddress(string userName, string defaultValue) { using (var teamProjectCollection = this.connectionInfo.Token.GetCollection(this.connectionInfo.ProjectCollectionUri)) { Func<string, string>[] helpers = { #if !TFS2013 (lookup) => { string email = null; var workItemStore = teamProjectCollection.GetService<WorkItemStore>(); if (workItemStore.TryFindIdentity(lookup, out var identity)) { email = identity?.Email ?? string.Empty; } return email; }, #endif (lookup) => { var identityManagementService = teamProjectCollection.GetService<IIdentityManagementService>(); TeamFoundationIdentity identity = identityManagementService.ReadIdentity( IdentitySearchFactor.AccountName, lookup, MembershipQuery.None, ReadIdentityOptions.ExtendedProperties); if (identity == null) { return string.Empty; } else { string mailAddress = identity.GetAttribute("Mail", null); mailAddress = string.IsNullOrWhiteSpace(mailAddress) ? identity.GetAttribute("ConfirmedNotificationAddress", null) : mailAddress; return mailAddress; } }, (lookup) => { var identityManagementService = teamProjectCollection.GetService<IIdentityManagementService>(); TeamFoundationIdentity identity = identityManagementService.ReadIdentity( IdentitySearchFactor.DisplayName, lookup, MembershipQuery.None, ReadIdentityOptions.ExtendedProperties); if (identity == null) { return string.Empty; } else { string mailAddress = identity.GetAttribute("Mail", null); mailAddress = string.IsNullOrWhiteSpace(mailAddress) ? identity.GetAttribute("ConfirmedNotificationAddress", null) : mailAddress; return mailAddress; } } }; foreach (var helper in helpers) { try { var result = helper(userName); if (!string.IsNullOrWhiteSpace(result)) { return result; } } catch {} } return defaultValue; } } } }
// Copyright 2017 - Refael Ackermann // Distributed under MIT style license // See accompanying file LICENSE at https://github.com/node4good/windows-autoconf // Usage: // powershell -ExecutionPolicy Unrestricted -Version "2.0" -Command "&{Add-Type -Path Find-VS2017.cs; [VisualStudioConfiguration.Main]::Query()}" using System; using System.Text; using System.Runtime.InteropServices; namespace VisualStudioConfiguration { [Flags] public enum InstanceState : uint { None = 0, Local = 1, Registered = 2, NoRebootRequired = 4, NoErrors = 8, Complete = 4294967295, } [Guid("6380BCFF-41D3-4B2E-8B2E-BF8A6810C848")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IEnumSetupInstances { void Next([MarshalAs(UnmanagedType.U4), In] int celt, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Interface), Out] ISetupInstance[] rgelt, [MarshalAs(UnmanagedType.U4)] out int pceltFetched); void Skip([MarshalAs(UnmanagedType.U4), In] int celt); void Reset(); [return: MarshalAs(UnmanagedType.Interface)] IEnumSetupInstances Clone(); } [Guid("42843719-DB4C-46C2-8E7C-64F1816EFD5B")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ISetupConfiguration { } [Guid("26AAB78C-4A60-49D6-AF3B-3C35BC93365D")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ISetupConfiguration2 : ISetupConfiguration { [return: MarshalAs(UnmanagedType.Interface)] IEnumSetupInstances EnumInstances(); [return: MarshalAs(UnmanagedType.Interface)] ISetupInstance GetInstanceForCurrentProcess(); [return: MarshalAs(UnmanagedType.Interface)] ISetupInstance GetInstanceForPath([MarshalAs(UnmanagedType.LPWStr), In] string path); [return: MarshalAs(UnmanagedType.Interface)] IEnumSetupInstances EnumAllInstances(); } [Guid("B41463C3-8866-43B5-BC33-2B0676F7F42E")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ISetupInstance { } [Guid("89143C9A-05AF-49B0-B717-72E218A2185C")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ISetupInstance2 : ISetupInstance { [return: MarshalAs(UnmanagedType.BStr)] string GetInstanceId(); [return: MarshalAs(UnmanagedType.Struct)] System.Runtime.InteropServices.ComTypes.FILETIME GetInstallDate(); [return: MarshalAs(UnmanagedType.BStr)] string GetInstallationName(); [return: MarshalAs(UnmanagedType.BStr)] string GetInstallationPath(); [return: MarshalAs(UnmanagedType.BStr)] string GetInstallationVersion(); [return: MarshalAs(UnmanagedType.BStr)] string GetDisplayName([MarshalAs(UnmanagedType.U4), In] int lcid); [return: MarshalAs(UnmanagedType.BStr)] string GetDescription([MarshalAs(UnmanagedType.U4), In] int lcid); [return: MarshalAs(UnmanagedType.BStr)] string ResolvePath([MarshalAs(UnmanagedType.LPWStr), In] string pwszRelativePath); [return: MarshalAs(UnmanagedType.U4)] InstanceState GetState(); [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)] ISetupPackageReference[] GetPackages(); ISetupPackageReference GetProduct(); [return: MarshalAs(UnmanagedType.BStr)] string GetProductPath(); [return: MarshalAs(UnmanagedType.VariantBool)] bool IsLaunchable(); [return: MarshalAs(UnmanagedType.VariantBool)] bool IsComplete(); [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)] ISetupPropertyStore GetProperties(); [return: MarshalAs(UnmanagedType.BStr)] string GetEnginePath(); } [Guid("DA8D8A16-B2B6-4487-A2F1-594CCCCD6BF5")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ISetupPackageReference { [return: MarshalAs(UnmanagedType.BStr)] string GetId(); [return: MarshalAs(UnmanagedType.BStr)] string GetVersion(); [return: MarshalAs(UnmanagedType.BStr)] string GetChip(); [return: MarshalAs(UnmanagedType.BStr)] string GetLanguage(); [return: MarshalAs(UnmanagedType.BStr)] string GetBranch(); [return: MarshalAs(UnmanagedType.BStr)] string GetType(); [return: MarshalAs(UnmanagedType.BStr)] string GetUniqueId(); [return: MarshalAs(UnmanagedType.VariantBool)] bool GetIsExtension(); } [Guid("c601c175-a3be-44bc-91f6-4568d230fc83")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ISetupPropertyStore { [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)] string[] GetNames(); object GetValue([MarshalAs(UnmanagedType.LPWStr), In] string pwszName); } [Guid("42843719-DB4C-46C2-8E7C-64F1816EFD5B")] [CoClass(typeof(SetupConfigurationClass))] [ComImport] public interface SetupConfiguration : ISetupConfiguration2, ISetupConfiguration { } [Guid("177F0C4A-1CD3-4DE7-A32C-71DBBB9FA36D")] [ClassInterface(ClassInterfaceType.None)] [ComImport] public class SetupConfigurationClass { } public static class Main { public static void Query() { ISetupConfiguration query = new SetupConfiguration(); ISetupConfiguration2 query2 = (ISetupConfiguration2)query; IEnumSetupInstances e = query2.EnumAllInstances(); int pceltFetched; ISetupInstance2[] rgelt = new ISetupInstance2[1]; StringBuilder log = new StringBuilder(); while (true) { e.Next(1, rgelt, out pceltFetched); if (pceltFetched <= 0) { Console.WriteLine(String.Format("{{\"log\":\"{0}\"}}", log.ToString())); return; } if (CheckInstance(rgelt[0], ref log)) return; } } private static bool CheckInstance(ISetupInstance2 setupInstance2, ref StringBuilder log) { // Visual Studio Community 2017 component directory: // https://www.visualstudio.com/en-us/productinfo/vs2017-install-product-Community.workloads string path = setupInstance2.GetInstallationPath().Replace("\\", "\\\\"); log.Append(String.Format("Found installation at: {0}\\n", path)); bool hasMSBuild = false; bool hasVCTools = false; uint Win10SDKVer = 0; bool hasWin8SDK = false; foreach (ISetupPackageReference package in setupInstance2.GetPackages()) { const string Win10SDKPrefix = "Microsoft.VisualStudio.Component.Windows10SDK."; string id = package.GetId(); if (id == "Microsoft.VisualStudio.VC.MSBuild.Base") hasMSBuild = true; else if (id == "Microsoft.VisualStudio.Component.VC.Tools.x86.x64") hasVCTools = true; else if (id.StartsWith(Win10SDKPrefix)) { string[] parts = id.Substring(Win10SDKPrefix.Length).Split('.'); if (parts.Length > 1 && parts[1] != "Desktop") continue; uint foundSdkVer; if (UInt32.TryParse(parts[0], out foundSdkVer)) Win10SDKVer = Math.Max(Win10SDKVer, foundSdkVer); } else if (id == "Microsoft.VisualStudio.Component.Windows81SDK") hasWin8SDK = true; else continue; log.Append(String.Format(" - Found {0}\\n", id)); } if (!hasMSBuild) log.Append(" - Missing Visual Studio C++ core features (Microsoft.VisualStudio.VC.MSBuild.Base)\\n"); if (!hasVCTools) log.Append(" - Missing VC++ 2017 v141 toolset (x86,x64) (Microsoft.VisualStudio.Component.VC.Tools.x86.x64)\\n"); if ((Win10SDKVer == 0) && (!hasWin8SDK)) log.Append(" - Missing a Windows SDK (Microsoft.VisualStudio.Component.Windows10SDK.* or Microsoft.VisualStudio.Component.Windows81SDK)\\n"); if (hasMSBuild && hasVCTools) { if (Win10SDKVer > 0) { log.Append(" - Using this installation with Windows 10 SDK"/*\\n*/); Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"10.0.{2}.0\"}}", log.ToString(), path, Win10SDKVer)); return true; } else if (hasWin8SDK) { log.Append(" - Using this installation with Windows 8.1 SDK"/*\\n*/); Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"8.1\"}}", log.ToString(), path)); return true; } } log.Append(" - Some required components are missing, not using this installation\\n"); return false; } } }
// The MIT License (MIT) // // Copyright (c) 2015, Unity Technologies & Google, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using UnityEngine; using UnityEngine.EventSystems; #if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) using UnityEngine.VR; #endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) /// This script provides an implemention of Unity's `BaseInputModule` class, so /// that Canvas-based (_uGUI_) UI elements and 3D scene objects can be /// interacted with in a Gvr Application. /// /// This script is intended for use with either a /// 3D pointer with the Daydream Controller (Recommended for Daydream), /// or a Gaze-based-pointer (Recommended for Cardboard). /// /// To use, attach to the scene's **EventSystem** object. Be sure to move it above the /// other modules, such as _TouchInputModule_ and _StandaloneInputModule_, in order /// for the pointer to take priority in the event system. /// /// If you are using a **Canvas**, set the _Render Mode_ to **World Space**, /// and add the _GvrPointerGraphicRaycaster_ script to the object. /// /// If you'd like pointers to work with 3D scene objects, add a _GvrPointerPhysicsRaycaster_ to the main camera, /// and add a component that implements one of the _Event_ interfaces (_EventTrigger_ will work nicely) to /// an object with a collider. /// /// GvrPointerInputModule emits the following events: _Enter_, _Exit_, _Down_, _Up_, _Click_, _Select_, /// _Deselect_, _UpdateSelected_, and _GvrPointerHover_. Scroll, move, and submit/cancel events are not emitted. /// /// To use a 3D Pointer with the Daydream Controller: /// - Add the prefab GoogleVR/Prefabs/UI/GvrControllerPointer to your scene. /// - Set the parent of GvrControllerPointer to the same parent as the main camera /// (With a local position of 0,0,0). /// /// To use a Gaze-based-pointer: /// - Add the prefab GoogleVR/Prefabs/UI/GvrReticlePointer to your scene. /// - Set the parent of GvrReticlePointer to the main camera. /// [AddComponentMenu("GoogleVR/GvrPointerInputModule")] public class GvrPointerInputModule : BaseInputModule { /// Determines whether pointer input is active in VR Mode only (`true`), or all of the /// time (`false`). Set to false if you plan to use direct screen taps or other /// input when not in VR Mode. [Tooltip("Whether pointer input is active in VR Mode only (true), or all the time (false).")] public bool vrModeOnly = false; private PointerEventData pointerData; private Vector2 lastHeadPose; // Active state private bool isActive = false; /// Time in seconds between the pointer down and up events sent by a trigger. /// Allows time for the UI elements to make their state transitions. private const float clickTime = 0.1f; // Based on default time for a button to animate to Pressed. /// The IGvrPointer which will be responding to pointer events. private IGvrPointer pointer { get { return GvrPointerManager.Pointer; } } /// @cond public override bool ShouldActivateModule() { bool isVrModeEnabled = !vrModeOnly; #if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) isVrModeEnabled |= VRSettings.enabled; #else isVrModeEnabled |= GvrViewer.Instance.VRModeEnabled; #endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) bool activeState = base.ShouldActivateModule() && isVrModeEnabled; if (activeState != isActive) { isActive = activeState; // Activate pointer if (pointer != null) { if (isActive) { pointer.OnInputModuleEnabled(); } } } return activeState; } /// @endcond public override void DeactivateModule() { DisablePointer(); base.DeactivateModule(); if (pointerData != null) { HandlePendingClick(); HandlePointerExitAndEnter(pointerData, null); pointerData = null; } eventSystem.SetSelectedGameObject(null, GetBaseEventData()); } public override bool IsPointerOverGameObject(int pointerId) { return pointerData != null && pointerData.pointerEnter != null; } public override void Process() { // Save the previous Game Object GameObject previousObject = GetCurrentGameObject(); CastRay(); UpdateCurrentObject(previousObject); UpdateReticle(previousObject); bool isGvrTriggered = Input.GetMouseButtonDown(0); bool handlePendingClickRequired = !Input.GetMouseButton(0); #if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) handlePendingClickRequired &= !GvrController.ClickButton; isGvrTriggered |= GvrController.ClickButtonDown; #endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) // Handle input if (!Input.GetMouseButtonDown(0) && Input.GetMouseButton(0)) { HandleDrag(); } else if (Time.unscaledTime - pointerData.clickTime < clickTime) { // Delay new events until clickTime has passed. } else if (!pointerData.eligibleForClick && (isGvrTriggered || Input.GetMouseButtonDown(0))) { // New trigger action. HandleTrigger(); } else if (handlePendingClickRequired) { // Check if there is a pending click to handle. HandlePendingClick(); } } /// @endcond private void CastRay() { Quaternion headOrientation; #if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) headOrientation = InputTracking.GetLocalRotation(VRNode.Head); #else headOrientation = GvrViewer.Instance.HeadPose.Orientation; #endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) Vector2 headPose = NormalizedCartesianToSpherical(headOrientation * Vector3.forward); if (pointerData == null) { pointerData = new PointerEventData(eventSystem); lastHeadPose = headPose; } // Cast a ray into the scene pointerData.Reset(); pointerData.position = GetPointerPosition(); eventSystem.RaycastAll(pointerData, m_RaycastResultCache); RaycastResult raycastResult = FindFirstRaycast(m_RaycastResultCache); if (raycastResult.worldPosition == Vector3.zero) { raycastResult.worldPosition = GetIntersectionPosition(pointerData.enterEventCamera, raycastResult); } pointerData.pointerCurrentRaycast = raycastResult; m_RaycastResultCache.Clear(); pointerData.delta = headPose - lastHeadPose; lastHeadPose = headPose; } private void UpdateCurrentObject(GameObject previousObject) { // Send enter events and update the highlight. GameObject currentObject = GetCurrentGameObject(); // Get the pointer target HandlePointerExitAndEnter(pointerData, previousObject); // Update the current selection, or clear if it is no longer the current object. var selected = ExecuteEvents.GetEventHandler<ISelectHandler>(currentObject); if (selected == eventSystem.currentSelectedGameObject) { ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, GetBaseEventData(), ExecuteEvents.updateSelectedHandler); } else { eventSystem.SetSelectedGameObject(null, pointerData); } // Execute hover event. if (currentObject == previousObject) { ExecuteEvents.Execute(currentObject, pointerData, GvrExecuteEventsExtension.pointerHoverHandler); } } private void UpdateReticle(GameObject previousObject) { if (pointer == null) { return; } Camera camera = pointerData.enterEventCamera; // Get the camera GameObject currentObject = GetCurrentGameObject(); // Get the pointer target Vector3 intersectionPosition = pointerData.pointerCurrentRaycast.worldPosition; bool isInteractive = pointerData.pointerPress != null || ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentObject) != null; if (currentObject == previousObject) { if (currentObject != null) { pointer.OnPointerHover(currentObject, intersectionPosition, GetLastRay(), isInteractive); } } else { if (previousObject != null) { pointer.OnPointerExit(previousObject); } if (currentObject != null) { pointer.OnPointerEnter(currentObject, intersectionPosition, GetLastRay(), isInteractive); } } } private void HandleDrag() { bool moving = pointerData.IsPointerMoving(); if (moving && pointerData.pointerDrag != null && !pointerData.dragging) { ExecuteEvents.Execute(pointerData.pointerDrag, pointerData, ExecuteEvents.beginDragHandler); pointerData.dragging = true; } // Drag notification if (pointerData.dragging && moving && pointerData.pointerDrag != null) { // Before doing drag we should cancel any pointer down state // And clear selection! if (pointerData.pointerPress != pointerData.pointerDrag) { ExecuteEvents.Execute(pointerData.pointerPress, pointerData, ExecuteEvents.pointerUpHandler); pointerData.eligibleForClick = false; pointerData.pointerPress = null; pointerData.rawPointerPress = null; } ExecuteEvents.Execute(pointerData.pointerDrag, pointerData, ExecuteEvents.dragHandler); } } private void HandlePendingClick() { if (!pointerData.eligibleForClick && !pointerData.dragging) { return; } if (pointer != null) { Camera camera = pointerData.enterEventCamera; pointer.OnPointerClickUp(); } var go = pointerData.pointerCurrentRaycast.gameObject; // Send pointer up and click events. ExecuteEvents.Execute(pointerData.pointerPress, pointerData, ExecuteEvents.pointerUpHandler); if (pointerData.eligibleForClick) { ExecuteEvents.Execute(pointerData.pointerPress, pointerData, ExecuteEvents.pointerClickHandler); } else if (pointerData.dragging) { ExecuteEvents.ExecuteHierarchy(go, pointerData, ExecuteEvents.dropHandler); ExecuteEvents.Execute(pointerData.pointerDrag, pointerData, ExecuteEvents.endDragHandler); } // Clear the click state. pointerData.pointerPress = null; pointerData.rawPointerPress = null; pointerData.eligibleForClick = false; pointerData.clickCount = 0; pointerData.clickTime = 0; pointerData.pointerDrag = null; pointerData.dragging = false; } private void HandleTrigger() { var go = pointerData.pointerCurrentRaycast.gameObject; // Send pointer down event. pointerData.pressPosition = pointerData.position; pointerData.pointerPressRaycast = pointerData.pointerCurrentRaycast; pointerData.pointerPress = ExecuteEvents.ExecuteHierarchy(go, pointerData, ExecuteEvents.pointerDownHandler) ?? ExecuteEvents.GetEventHandler<IPointerClickHandler>(go); // Save the drag handler as well pointerData.pointerDrag = ExecuteEvents.GetEventHandler<IDragHandler>(go); if (pointerData.pointerDrag != null) { ExecuteEvents.Execute(pointerData.pointerDrag, pointerData, ExecuteEvents.initializePotentialDrag); } // Save the pending click state. pointerData.rawPointerPress = go; pointerData.eligibleForClick = true; pointerData.delta = Vector2.zero; pointerData.dragging = false; pointerData.useDragThreshold = true; pointerData.clickCount = 1; pointerData.clickTime = Time.unscaledTime; if (pointer != null) { pointer.OnPointerClickDown(); } } private Vector2 NormalizedCartesianToSpherical(Vector3 cartCoords) { cartCoords.Normalize(); if (cartCoords.x == 0) cartCoords.x = Mathf.Epsilon; float outPolar = Mathf.Atan(cartCoords.z / cartCoords.x); if (cartCoords.x < 0) outPolar += Mathf.PI; float outElevation = Mathf.Asin(cartCoords.y); return new Vector2(outPolar, outElevation); } private GameObject GetCurrentGameObject() { if (pointerData != null) { return pointerData.pointerCurrentRaycast.gameObject; } return null; } private Ray GetLastRay() { if (pointerData != null) { GvrBasePointerRaycaster raycaster = pointerData.pointerCurrentRaycast.module as GvrBasePointerRaycaster; if (raycaster != null) { return raycaster.GetLastRay(); } else if (pointerData.enterEventCamera != null) { Camera cam = pointerData.enterEventCamera; return new Ray(cam.transform.position, cam.transform.forward); } } return new Ray(); } private Vector3 GetIntersectionPosition(Camera cam, RaycastResult raycastResult) { // Check for camera if (cam == null) { return Vector3.zero; } float intersectionDistance = raycastResult.distance + cam.nearClipPlane; Vector3 intersectionPosition = cam.transform.position + cam.transform.forward * intersectionDistance; return intersectionPosition; } private void DisablePointer() { if (pointer == null) { return; } GameObject currentGameObject = GetCurrentGameObject(); if (currentGameObject) { Camera camera = pointerData.enterEventCamera; pointer.OnPointerExit(currentGameObject); } pointer.OnInputModuleDisabled(); } private Vector2 GetPointerPosition() { int viewportWidth = Screen.width; int viewportHeight = Screen.height; #if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) && UNITY_ANDROID // GVR native integration is supported. if (VRSettings.enabled) { viewportWidth = VRSettings.eyeTextureWidth; viewportHeight = VRSettings.eyeTextureHeight; } #endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) && UNITY_ANDROID return new Vector2(0.5f * viewportWidth, 0.5f * viewportHeight); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using FluentAssertions; using FluentAssertions.Extensions; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.Extensibility; using Newtonsoft.Json; using Xunit; using Xunit.Abstractions; using static Pocket.LogEvents; using static Pocket.Logger<Pocket.For.ApplicationInsights.Tests.PocketLoggerForApplicationInsightsTests>; namespace Pocket.For.ApplicationInsights.Tests { public class PocketLoggerForApplicationInsightsTests : IDisposable { private readonly TelemetryClient client; private readonly ITestOutputHelper output; private readonly IDisposable disposables; private readonly List<ITelemetry> telemetrySent; public PocketLoggerForApplicationInsightsTests(ITestOutputHelper output) { this.output = output; telemetrySent = new List<ITelemetry>(); disposables = Subscribe(e => this.output.WriteLine(e.ToLogString())); client = new TelemetryClient( new TelemetryConfiguration( "<instrumentation key>", new FakeTelemetryChannel(telemetrySent.Add))); } public void Dispose() => disposables.Dispose(); [Fact] public async Task Log_events_can_be_used_to_send_dependency_tracking_on_operation_complete() { client.TrackDependency(new DependencyTelemetry { Data = "http://example.com/", Duration = 500.Milliseconds(), Success = true, Timestamp = DateTimeOffset.UtcNow, Name = "my-operation", ResultCode = "200", Properties = { ["RequestUri"] = "http://example.com/", ["ResultCode"] = "200", ["Category"] = GetType().ToString() } }); using (client.SubscribeToPocketLogger()) using (var operation = Log.ConfirmOnExit( "my-operation", exitArgs: () => new (string, object)[] { ("RequestUri", new Uri("http://example.com") ) })) { await Task.Delay(200); operation.Succeed("{ResultCode}", 200); } var expected = (DependencyTelemetry) telemetrySent[0]; var actual = (DependencyTelemetry) telemetrySent[1]; actual.Data.Should().Be(expected.Data); actual.Duration.Should().BeGreaterOrEqualTo(190.Milliseconds()); actual.Name.Should().Be(expected.Name); actual.Properties.Should().BeEquivalentTo(expected.Properties); actual.ResultCode.Should().Be(expected.ResultCode); actual.Success.Should().Be(expected.Success); actual.Timestamp.Should().BeCloseTo(expected.Timestamp, precision: 1500); Log.Info(JsonConvert.SerializeObject(actual)); } [Fact] public void Log_events_can_be_used_to_send_custom_events_with_metrics() { client.TrackEvent( "my-event", metrics: new Dictionary<string, double> { ["my-metric"] = 1.23, ["my-other-metric"] = 123 }, properties: new Dictionary<string, string> { ["Category"] = GetType().ToString() }); using (client.SubscribeToPocketLogger()) { Log.Event("my-event", ("my-metric", 1.23), ("my-other-metric", 123)); } var expected = (EventTelemetry) telemetrySent[0]; var actual = (EventTelemetry) telemetrySent[1]; actual.Name.Should().Be(expected.Name); actual.Metrics.Should().BeEquivalentTo(expected.Metrics); actual.Properties.Should().BeEquivalentTo(expected.Properties); actual.Timestamp.Should().BeCloseTo(expected.Timestamp, precision: 1500); } [Fact] public void Log_events_can_be_used_to_send_custom_events_with_properties() { client.TrackEvent(new EventTelemetry { Name = "my-event", Properties = { ["my-property"] = "my-property-value", ["Category"] = GetType().ToString() } }); using (client.SubscribeToPocketLogger()) { Log.Event("my-event", properties: new (string, object)[] { ("my-property", "my-property-value") } ); } var expected = (EventTelemetry) telemetrySent[0]; var actual = (EventTelemetry) telemetrySent[1]; actual.Name.Should().Be(expected.Name); actual.Metrics.Should().BeEquivalentTo(expected.Metrics); actual.Properties.Should().BeEquivalentTo(expected.Properties); actual.Timestamp.Should().BeCloseTo(expected.Timestamp, precision: 1500); } [Fact] public void When_a_custom_event_is_part_of_an_operation_it_includes_a_Duration_property() { using (var operation = Log.OnExit()) using (client.SubscribeToPocketLogger()) { operation.Event(); } var @event = (EventTelemetry) telemetrySent[0]; @event.Properties .Should() .ContainKey("Duration") .WhichValue .Should() .MatchRegex(@"\d+", "it should be an int"); } [Fact] public void Log_events_can_be_used_to_send_exceptions() { try { throw new Exception("oops!"); } catch (Exception exception) { client.TrackException(new ExceptionTelemetry { Message = "oh no! 1 and 2 happened.", Exception = exception, SeverityLevel = SeverityLevel.Error, Properties = { ["Category"] = GetType().ToString(), ["this"] = 1.ToString(), ["that"] = 2.ToString() } }); using (client.SubscribeToPocketLogger()) { Log.Error("oh no! {this} and {that} happened.", exception, 1, 2); } } var expected = (ExceptionTelemetry) telemetrySent[0]; var actual = (ExceptionTelemetry) telemetrySent[1]; actual.Exception.Should().Be(expected.Exception); actual.Message.Should().Be(expected.Message); actual.Properties.Should().BeEquivalentTo(expected.Properties); actual.SeverityLevel.Should().Be(expected.SeverityLevel); actual.Timestamp.Should().BeCloseTo(expected.Timestamp, precision: 1500); } [Fact] public void Log_Error_uses_exception_ToString_if_no_message_is_specified() { string exceptionString; try { throw new Exception("oops!", new Exception("drat!")); } catch (Exception exception) { exceptionString = exception.ToString(); using (client.SubscribeToPocketLogger()) { Log.Error(exception); } } var actual = (ExceptionTelemetry) telemetrySent[0]; actual.Message.Should().Be(exceptionString); } [Fact] public void Log_Warning_sets_message_property() { using (client.SubscribeToPocketLogger()) { Log.Warning("oops..."); } var actual = (ExceptionTelemetry) telemetrySent[0]; actual.Message.Should().Be("oops..."); } [Fact] public void Log_Warning_uses_exception_ToString_if_no_message_is_specified() { string exceptionString; try { throw new Exception("oops!", new Exception("drat!")); } catch (Exception exception) { exceptionString = exception.ToString(); using (client.SubscribeToPocketLogger()) { Log.Warning(exception); } } var actual = (ExceptionTelemetry) telemetrySent[0]; actual.Message.Should().Be(exceptionString); } [Fact] public void When_an_exception_is_part_of_an_operation_it_includes_a_Duration_property() { using (var operation = Log.OnExit()) using (client.SubscribeToPocketLogger()) { operation.Warning(new Exception("oops")); } var exceptionTelemetry = (ExceptionTelemetry) telemetrySent[0]; exceptionTelemetry.Properties .Should() .ContainKey("Duration") .WhichValue .Should() .MatchRegex(@"\d+", "it should be an int"); } [Fact] public void Log_events_can_be_used_to_send_traces() { client.TrackTrace(new TraceTelemetry { Message = $"this is a trace of int 123 and tuple (this, 456)", SeverityLevel = SeverityLevel.Information, Properties = { ["some-int"] = "123", ["some-tuple"] = "(this, 456)", ["Category"] = GetType().ToString() } }); using (client.SubscribeToPocketLogger()) { Log.Info("this is a trace of int {some-int} and tuple {some-tuple}", 123, ("this", 456)); } var expected = (TraceTelemetry) telemetrySent[0]; var actual = (TraceTelemetry) telemetrySent[1]; actual.Message.Should().Be(expected.Message); actual.Properties.Should().BeEquivalentTo(expected.Properties); actual.SeverityLevel.Should().Be(expected.SeverityLevel); actual.Timestamp.Should().BeCloseTo(expected.Timestamp, precision: 1500); } [Fact] public void When_a_trace_is_part_of_an_operation_it_includes_a_Duration_property() { using (var operation = Log.OnExit()) using (client.SubscribeToPocketLogger()) { operation.Trace("checkpoint"); } var trace = (TraceTelemetry) telemetrySent[0]; trace.Properties .Should() .ContainKey("Duration") .WhichValue .Should() .MatchRegex(@"\d+", "it should be an int"); } [Fact] public void Events_sent_after_operation_completion_are_treated_as_custom_events() { using (client.SubscribeToPocketLogger()) using (var operation = Log.ConfirmOnExit()) { operation.Succeed(); operation.Event(); } telemetrySent.Last() .Should() .BeOfType<EventTelemetry>(); } [Fact] public void Context_Operation_name_is_set_in_all_telemetry() { using (client.SubscribeToPocketLogger()) using (var operation = Log.OnEnterAndConfirmOnExit()) { operation.Event(); operation.Info("hi!"); operation.Succeed(); } WriteTelemetryToConsole(); telemetrySent.Should() .OnlyContain(t => t.Context.Operation.Name == nameof(Context_Operation_name_is_set_in_all_telemetry)); } [Fact] public void Context_Operation_id_is_set_in_all_telemetry() { using (client.SubscribeToPocketLogger()) using (var operation = Log.OnEnterAndConfirmOnExit()) { operation.Event(); operation.Info("hi!"); operation.Succeed(); } WriteTelemetryToConsole(); telemetrySent.Should() .OnlyContain(t => t.Context.Operation.Id != null); } [Fact] public void Context_Operation_parent_id_is_set_in_all_telemetry() { var activity = new Activity("the-ambient-activity").Start(); using (Disposable.Create(() => activity.Stop())) using (client.SubscribeToPocketLogger()) using (var operation = Log.OnEnterAndConfirmOnExit()) { operation.Event(); operation.Info("hi!"); operation.Succeed(); } WriteTelemetryToConsole(); telemetrySent.Should() .OnlyContain(t => t.Context.Operation.ParentId == activity.Id); } private void WriteTelemetryToConsole() { for (var i = 0; i < telemetrySent.Count; i++) { var telemetry = telemetrySent[i]; output.WriteLine(JsonConvert.SerializeObject(telemetry, Formatting.Indented)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: This class will encapsulate a byte and provide an ** Object representation of it. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; // The Byte class extends the Value class and // provides object representation of the byte primitive type. // [System.Runtime.InteropServices.ComVisible(true)] [Serializable] [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] public struct Byte : IComparable, IFormattable, IConvertible , IComparable<Byte>, IEquatable<Byte> { private byte m_value; // The maximum value that a Byte may represent: 255. public const byte MaxValue = (byte)0xFF; // The minimum value that a Byte may represent: 0. public const byte MinValue = 0; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type byte, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (!(value is Byte)) { throw new ArgumentException(Environment.GetResourceString("Arg_MustBeByte")); } return m_value - (((Byte)value).m_value); } public int CompareTo(Byte value) { return m_value - value; } // Determines whether two Byte objects are equal. public override bool Equals(Object obj) { if (!(obj is Byte)) { return false; } return m_value == ((Byte)obj).m_value; } [System.Runtime.Versioning.NonVersionable] public bool Equals(Byte obj) { return m_value == obj; } // Gets a hash code for this instance. public override int GetHashCode() { return m_value; } [Pure] public static byte Parse(String s) { return Parse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [Pure] public static byte Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.CurrentInfo); } [Pure] public static byte Parse(String s, IFormatProvider provider) { return Parse(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } // Parses an unsigned byte from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. [Pure] public static byte Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static byte Parse(String s, NumberStyles style, NumberFormatInfo info) { int i = 0; try { i = Number.ParseInt32(s, style, info); } catch(OverflowException e) { throw new OverflowException(Environment.GetResourceString("Overflow_Byte"), e); } if (i < MinValue || i > MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_Byte")); return (byte)i; } public static bool TryParse(String s, out Byte result) { return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Byte result) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out Byte result) { result = 0; int i; if (!Number.TryParseInt32(s, style, info, out i)) { return false; } if (i < MinValue || i > MaxValue) { return false; } result = (byte) i; return true; } [Pure] [System.Security.SecuritySafeCritical] // auto-generated public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo); } [Pure] [System.Security.SecuritySafeCritical] // auto-generated public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo); } [Pure] [System.Security.SecuritySafeCritical] // auto-generated public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } [Pure] [System.Security.SecuritySafeCritical] // auto-generated public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider)); } // // IConvertible implementation // [Pure] public TypeCode GetTypeCode() { return TypeCode.Byte; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return m_value; } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Byte", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using Encog.ML.Data; namespace Encog.MathUtil { /// <summary> /// Used to produce an array of activations to classify data into groups. This /// class is provided the number of groups, as well as the range that the /// activations should fall into. /// </summary> [Serializable] public class Equilateral { /// <summary> /// Minimum number of classes for equilateral. /// </summary> public const int MinEq = 3; /// <summary> /// The matrix of values that was generated. /// </summary> private readonly double[][] _matrix; /// <summary> /// Construct an equilateral matrix. /// </summary> /// <param name="count">The number of sets, these will be the rows in the matrix.</param> /// <param name="high">The high value for the outputs.</param> /// <param name="low">The low value for the outputs.</param> public Equilateral(int count, double high, double low) { _matrix = Equilat(count, high, low); } /// <summary> /// Decode a set of activations and see which set it has the lowest Euclidean /// distance from. /// </summary> /// <param name="activations">The output from the neural network.</param> /// <returns>The set that these activations were closest too.</returns> public int Decode(double[] activations) { double minValue = double.PositiveInfinity; int minSet = -1; for (int i = 0; i < _matrix.GetLength(0); i++) { double dist = GetDistance(activations, i); if (dist < minValue) { minValue = dist; minSet = i; } } return minSet; } /// <summary> /// Decode a set of activations and see which set it has the lowest Euclidean /// distance from. /// </summary> /// <param name="activations">The output from the neural network.</param> /// <returns>The set that these activations were closest too.</returns> public int Decode(IMLData activations) { double minValue = double.PositiveInfinity; int minSet = -1; for(int i = 0; i < _matrix.GetLength(0); i++) { double dist = GetDistance(activations, i); if(dist < minValue) { minValue = dist; minSet = i; } } return minSet; } /// <summary> /// Get the activations for the specified set. /// </summary> /// <param name="set">The set to determine the activations for.</param> /// <returns>The activations for the specified sets.</returns> public double[] Encode(int set) { if (set < 0 || set > _matrix.Length) { throw new EncogError("Class out of range for equilateral: " + set); } return _matrix[set]; } /// <summary> /// Called internally to generate the matrix. /// </summary> /// <param name="n">The number of sets to generate for.</param> /// <param name="high">The high end of the range of values to generate.</param> /// <param name="low"> The low end of the range of values to generate.</param> /// <returns>One row for each set, the columns are the activations for that set.</returns> private static double[][] Equilat(int n, double high, double low) { var result = new double[n][]; // n - 1 for (int i = 0; i < n; i++) { result[i] = new double[n - 1]; } result[0][0] = -1; result[1][0] = 1.0; for (int k = 2; k < n; k++) { // scale the matrix so far double r = k; double f = Math.Sqrt(r*r - 1.0)/r; for (int i = 0; i < k; i++) { for (int j = 0; j < k - 1; j++) { result[i][j] *= f; } } r = -1.0/r; for (int i = 0; i < k; i++) { result[i][k - 1] = r; } for (int i = 0; i < k - 1; i++) { result[k][i] = 0.0; } result[k][k - 1] = 1.0; } // scale it for (int row = 0; row < result.GetLength(0); row++) { for (int col = 0; col < result[0].GetLength(0); col++) { const double min = -1; const double max = 1; result[row][col] = ((result[row][col] - min)/(max - min)) *(high - low) + low; } } return result; } /// <summary> /// Get the Euclidean distance between the specified data and the set number. /// </summary> /// <param name="data">The data to check.</param> /// <param name="set">The set to check.</param> /// <returns>The distance.</returns> public double GetDistance(double[] data, int set) { double result = 0; for (int i = 0; i < data.GetLength(0); i++) { var val = data[i] - _matrix[set][i]; result += val * val; } return Math.Sqrt(result); } /// <summary> /// Get the Euclidean distance between the specified data and the set number. /// </summary> /// <param name="data">The data to check.</param> /// <param name="set">The set to check.</param> /// <returns>The distance.</returns> public double GetDistance(IMLData data, int set) { double result = 0; for(int i = 0; i < data.Count; i++) { var val = data[i] - _matrix[set][i]; result += val * val; } return Math.Sqrt(result); } /// <summary> /// Get the smallest distance. /// </summary> /// <param name="data">The data to check.</param> /// <returns>The set with the smallest distance.</returns> public int GetSmallestDistance(double[] data) { int bestSet = -1; double bestDistance = double.MaxValue; for (int i = 0; i < _matrix.Length; i++) { double d = GetDistance(data, i); if (bestSet == -1 || d < bestDistance) { bestSet = i; bestDistance = d; } } return bestSet; } } }
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // * Neither the name of Jim Heising nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using Microsoft.Win32; using System.Data; using System.Windows.Forms; namespace WOSI.Utilities { public class FilenameEventArgs : EventArgs { public string Filename = ""; public FilenameEventArgs(string filename) { Filename = filename; } } public delegate void FilenameEventHandler(object sender, FilenameEventArgs e); public class ApplicationSettings { private class RecentlyUsedFileMenuItem : MenuItem { public RecentlyUsedFileMenuItem(string text) : base(text) { } } private const string asdlfka9098723 = "23987qlkwjhKA97K(*8kas9d8792835lasp"; private const string encryptPrefix = "-------092745"; public static event FilenameEventHandler RecentlyUsedFileMenuClicked; private static ApplicationSettingsDataset appSettingsDataset = new ApplicationSettingsDataset(); public static void LoadSettingsFromRegistry(string companyName, string applicationName, bool forCurrentUserOnly) { appSettingsDataset.Clear(); RegistryKey regKey; if(forCurrentUserOnly) { regKey = Registry.CurrentUser.CreateSubKey("Software\\" + companyName + "\\" + applicationName); } else { regKey = Registry.LocalMachine.CreateSubKey("Software\\" + companyName + "\\" + applicationName); } string[] subKeys = regKey.GetSubKeyNames(); for(int subKeyIndex = 0; subKeyIndex < subKeys.Length; subKeyIndex++) { RegistryKey subKey = regKey.OpenSubKey(subKeys[subKeyIndex]); string[] values = subKey.GetValueNames(); for(int valueIndex = 0; valueIndex < values.Length; valueIndex++) { SetSetting(subKeys[subKeyIndex], values[valueIndex], Convert.ToString(subKey.GetValue(values[valueIndex]))); } } // Load recently used files RegistryKey recentlyUsedFiles = regKey.CreateSubKey("9EF852E5-C9EF-4163-8D05-95EEBEFE999B-Recently Used Files"); string[] files = (string[])recentlyUsedFiles.GetValue("Files"); for(int index = 0; index < files.Length; index++) { appSettingsDataset.RecentlyUsedFiles.AddRecentlyUsedFilesRow(files[index]); } appSettingsDataset.AcceptChanges(); } public static void SaveSettingsToRegistry(string companyName, string applicationName, bool forCurrentUserOnly) { RegistryKey regKey; if(forCurrentUserOnly) { regKey = Registry.CurrentUser.CreateSubKey("Software\\" + companyName + "\\" + applicationName); } else { regKey = Registry.LocalMachine.CreateSubKey("Software\\" + companyName + "\\" + applicationName); } for(int index = 0; index < appSettingsDataset.Setting.Count; index++) { ApplicationSettingsDataset.SettingRow settingRow = appSettingsDataset.Setting[index]; RegistryKey groupKey = regKey.CreateSubKey(settingRow.SettingsGroupRow.GroupName); groupKey.SetValue(settingRow.Name, settingRow.Value); } // Save recently used files RegistryKey recentlyUsedFiles = regKey.CreateSubKey("9EF852E5-C9EF-4163-8D05-95EEBEFE999B-Recently Used Files"); recentlyUsedFiles.SetValue("Files", GetRecentlyUsedFiles()); } public static void LoadSettingsFromFile(bool forCurrentUserOnly) { LoadSettingsFromFile(Application.StartupPath, forCurrentUserOnly); } public static void LoadSettingsFromFile(string settingsDirectory, bool forCurrentUserOnly) { appSettingsDataset.Clear(); string filename = settingsDirectory + "\\"; if(forCurrentUserOnly) { filename += Environment.UserName + ".settings"; } else { filename += "app.settings"; } if(File.Exists(filename)) { appSettingsDataset.ReadXml(filename, XmlReadMode.Auto); appSettingsDataset.AcceptChanges(); } } public static void SaveSettingsToFile(bool forCurrentUserOnly) { SaveSettingsToFile(Application.StartupPath, forCurrentUserOnly); } public static void SaveSettingsToFile(string settingsDirectory, bool forCurrentUserOnly) { string filename = settingsDirectory + "\\"; if(forCurrentUserOnly) { filename += Environment.UserName + ".settings"; } else { filename += "app.settings"; } appSettingsDataset.WriteXml(filename, XmlWriteMode.IgnoreSchema); } public static void ClearSettings() { appSettingsDataset.Clear(); } public static int GetSetting(string settingGroup, string settingName, int defaultValue) { try { return Convert.ToInt32(GetSetting(settingGroup, settingName, defaultValue.ToString())); } catch { return defaultValue; } } public static bool GetSetting(string settingGroup, string settingName, bool defaultValue) { try { return Convert.ToBoolean(GetSetting(settingGroup, settingName, defaultValue.ToString())); } catch { return defaultValue; } } public static float GetSetting(string settingGroup, string settingName, float defaultValue) { try { return Convert.ToSingle(GetSetting(settingGroup, settingName, defaultValue.ToString())); } catch { return defaultValue; } } public static double GetSetting(string settingGroup, string settingName, double defaultValue) { try { return Convert.ToDouble(GetSetting(settingGroup, settingName, defaultValue.ToString())); } catch { return defaultValue; } } public static string GetSetting(string settingGroup, string settingName, string defaultValue) { try { if(appSettingsDataset != null) { ApplicationSettingsDataset.SettingRow[] settingRows = (ApplicationSettingsDataset.SettingRow[])appSettingsDataset.Setting.Select("GroupName = '" + settingGroup + "' AND Name = '" + settingName + "'"); if(settingRows.Length > 0) { string settingValue = settingRows[0].Value; // Decrypt the string if(settingValue.StartsWith(encryptPrefix)) { settingValue = settingValue.Remove(0, encryptPrefix.Length); settingValue = CryptoUtils.Decrypt(settingValue, asdlfka9098723); } return settingValue; } } } catch(Exception) { } return defaultValue; } public static void SetSetting(string settingGroup, string settingName, int settingValue) { SetSetting(settingGroup, settingName, settingValue.ToString()); } public static void SetSetting(string settingGroup, string settingName, int settingValue, bool encrypt) { SetSetting(settingGroup, settingName, settingValue.ToString(), encrypt); } public static void SetSetting(string settingGroup, string settingName, double settingValue) { SetSetting(settingGroup, settingName, settingValue.ToString()); } public static void SetSetting(string settingGroup, string settingName, double settingValue, bool encrypt) { SetSetting(settingGroup, settingName, settingValue.ToString(), encrypt); } public static void SetSetting(string settingGroup, string settingName, bool settingValue) { SetSetting(settingGroup, settingName, settingValue.ToString()); } public static void SetSetting(string settingGroup, string settingName, bool settingValue, bool encrypt) { SetSetting(settingGroup, settingName, settingValue.ToString(), encrypt); } public static void SetSetting(string settingGroup, string settingName, float settingValue) { SetSetting(settingGroup, settingName, settingValue.ToString()); } public static void SetSetting(string settingGroup, string settingName, float settingValue, bool encrypt) { SetSetting(settingGroup, settingName, settingValue.ToString(), encrypt); } public static void SetSetting(string settingGroup, string settingName, string settingValue) { SetSetting(settingGroup, settingName, settingValue, false); } public static void SetSetting(string settingGroup, string settingName, string settingValue, bool encrypt) { if(appSettingsDataset != null) { string sValue = settingValue; if(encrypt) sValue = encryptPrefix + CryptoUtils.Encrypt(sValue, asdlfka9098723); // Check to see if the group already exists ApplicationSettingsDataset.SettingsGroupRow settingsGroup = appSettingsDataset.SettingsGroup.FindByGroupName(settingGroup); if(settingsGroup == null) { settingsGroup = appSettingsDataset.SettingsGroup.AddSettingsGroupRow(settingGroup); } // Check to see if the value already exists ApplicationSettingsDataset.SettingRow[] settings = (ApplicationSettingsDataset.SettingRow[])appSettingsDataset.Setting.Select("GroupName = '" + settingGroup + "' AND Name = '" + settingName + "'"); if(settings.Length > 0) { settings[0].Value = sValue; } else { appSettingsDataset.Setting.AddSettingRow(settingName, sValue, settingsGroup); } } } public static void AddRecentlyUsedFile(string filename, int maxCount) { AddRecentlyUsedFile(filename, maxCount, false); } public static void AddRecentlyUsedFile(string filename, int maxCount, bool encrypt) { if(encrypt) filename = encryptPrefix + CryptoUtils.Encrypt(filename, asdlfka9098723); // If the file already exists in the menu, delete it ApplicationSettingsDataset.RecentlyUsedFilesRow existingFilename = appSettingsDataset.RecentlyUsedFiles.FindByFilename(filename); if(existingFilename != null) appSettingsDataset.RecentlyUsedFiles.RemoveRecentlyUsedFilesRow(existingFilename); appSettingsDataset.RecentlyUsedFiles.AddRecentlyUsedFilesRow(filename); // Trim the recently used files list if(maxCount < appSettingsDataset.RecentlyUsedFiles.Count) { for(int index = 0; index < appSettingsDataset.RecentlyUsedFiles.Count - maxCount; index++) { appSettingsDataset.RecentlyUsedFiles.RemoveRecentlyUsedFilesRow(appSettingsDataset.RecentlyUsedFiles[0]); } } } public static void CreateRecentlyUsedFileSubmenu(MenuItem parentMenu, bool includeNumber) { for(int index = appSettingsDataset.RecentlyUsedFiles.Count - 1; index >= 0; index--) { string menuText = appSettingsDataset.RecentlyUsedFiles[index].Filename; if(includeNumber) menuText = "&" + (appSettingsDataset.RecentlyUsedFiles.Count - index) + " " + menuText; RecentlyUsedFileMenuItem menuItem = new RecentlyUsedFileMenuItem(menuText); menuItem.Tag = appSettingsDataset.RecentlyUsedFiles[index].Filename; menuItem.Click += new EventHandler(menuItem_Click); parentMenu.MenuItems.Add(menuItem); } } public void ClearRecentlyUsedFiles() { appSettingsDataset.RecentlyUsedFiles.Clear(); } public static string[] GetRecentlyUsedFiles() { string[] fileNames = new string[appSettingsDataset.RecentlyUsedFiles.Count]; for(int index = 0; index < appSettingsDataset.RecentlyUsedFiles.Count; index++) { fileNames[index] = appSettingsDataset.RecentlyUsedFiles[index].Filename; try { if(fileNames[index].StartsWith(encryptPrefix)) { fileNames[index] = fileNames[index].Remove(0, encryptPrefix.Length); fileNames[index] = CryptoUtils.Decrypt(fileNames[index], asdlfka9098723); } } catch { } } return fileNames; } private static void menuItem_Click(object sender, EventArgs e) { if(RecentlyUsedFileMenuClicked != null) { RecentlyUsedFileMenuClicked(null, new FilenameEventArgs((string)((RecentlyUsedFileMenuItem)sender).Tag)); } } } }
namespace Petstore { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// Extension methods for SwaggerPetstore. /// </summary> public static partial class SwaggerPetstoreExtensions { /// <summary> /// Fake endpoint to test byte array in body parameter for adding a new pet to /// the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object in the form of byte array /// </param> public static void AddPetUsingByteArray(this ISwaggerPetstore operations, string body = default(string)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).AddPetUsingByteArrayAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Fake endpoint to test byte array in body parameter for adding a new pet to /// the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object in the form of byte array /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task AddPetUsingByteArrayAsync(this ISwaggerPetstore operations, string body = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.AddPetUsingByteArrayWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Add a new pet to the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> public static void AddPet(this ISwaggerPetstore operations, Pet body = default(Pet)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).AddPetAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Add a new pet to the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task AddPetAsync(this ISwaggerPetstore operations, Pet body = default(Pet), CancellationToken cancellationToken = default(CancellationToken)) { await operations.AddPetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Update an existing pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> public static void UpdatePet(this ISwaggerPetstore operations, Pet body = default(Pet)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).UpdatePetAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update an existing pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdatePetAsync(this ISwaggerPetstore operations, Pet body = default(Pet), CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdatePetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Finds Pets by status /// </summary> /// Multiple status values can be provided with comma seperated strings /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> public static IList<Pet> FindPetsByStatus(this ISwaggerPetstore operations, IList<string> status = default(IList<string>)) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).FindPetsByStatusAsync(status), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by status /// </summary> /// Multiple status values can be provided with comma seperated strings /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Pet>> FindPetsByStatusAsync(this ISwaggerPetstore operations, IList<string> status = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.FindPetsByStatusWithHttpMessagesAsync(status, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Finds Pets by tags /// </summary> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='tags'> /// Tags to filter by /// </param> public static IList<Pet> FindPetsByTags(this ISwaggerPetstore operations, IList<string> tags = default(IList<string>)) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).FindPetsByTagsAsync(tags), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by tags /// </summary> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='tags'> /// Tags to filter by /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Pet>> FindPetsByTagsAsync(this ISwaggerPetstore operations, IList<string> tags = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.FindPetsByTagsWithHttpMessagesAsync(tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Fake endpoint to test byte array return by 'Find pet by ID' /// </summary> /// Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate /// API error conditions /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be fetched /// </param> public static string FindPetsWithByteArray(this ISwaggerPetstore operations, long petId) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).FindPetsWithByteArrayAsync(petId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Fake endpoint to test byte array return by 'Find pet by ID' /// </summary> /// Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate /// API error conditions /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be fetched /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> FindPetsWithByteArrayAsync(this ISwaggerPetstore operations, long petId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.FindPetsWithByteArrayWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Find pet by ID /// </summary> /// Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate /// API error conditions /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be fetched /// </param> public static Pet GetPetById(this ISwaggerPetstore operations, long petId) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).GetPetByIdAsync(petId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Find pet by ID /// </summary> /// Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate /// API error conditions /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be fetched /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Pet> GetPetByIdAsync(this ISwaggerPetstore operations, long petId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be updated /// </param> /// <param name='name'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> public static void UpdatePetWithForm(this ISwaggerPetstore operations, string petId, string name = default(string), string status = default(string)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).UpdatePetWithFormAsync(petId, name, status), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be updated /// </param> /// <param name='name'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdatePetWithFormAsync(this ISwaggerPetstore operations, string petId, string name = default(string), string status = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdatePetWithFormWithHttpMessagesAsync(petId, name, status, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> public static void DeletePet(this ISwaggerPetstore operations, long petId, string apiKey = default(string)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).DeletePetAsync(petId, apiKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeletePetAsync(this ISwaggerPetstore operations, long petId, string apiKey = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeletePetWithHttpMessagesAsync(petId, apiKey, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// uploads an image /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet to update /// </param> /// <param name='additionalMetadata'> /// Additional data to pass to server /// </param> /// <param name='file'> /// file to upload /// </param> public static void UploadFile(this ISwaggerPetstore operations, long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).UploadFileAsync(petId, additionalMetadata, file), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// uploads an image /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet to update /// </param> /// <param name='additionalMetadata'> /// Additional data to pass to server /// </param> /// <param name='file'> /// file to upload /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UploadFileAsync(this ISwaggerPetstore operations, long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), CancellationToken cancellationToken = default(CancellationToken)) { await operations.UploadFileWithHttpMessagesAsync(petId, additionalMetadata, file, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Returns pet inventories by status /// </summary> /// Returns a map of status codes to quantities /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IDictionary<string, int?> GetInventory(this ISwaggerPetstore operations) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).GetInventoryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns pet inventories by status /// </summary> /// Returns a map of status codes to quantities /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IDictionary<string, int?>> GetInventoryAsync(this ISwaggerPetstore operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetInventoryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Place an order for a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> public static Order PlaceOrder(this ISwaggerPetstore operations, Order body = default(Order)) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).PlaceOrderAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Place an order for a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Order> PlaceOrderAsync(this ISwaggerPetstore operations, Order body = default(Order), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PlaceOrderWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Find purchase order by ID /// </summary> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// ID of pet that needs to be fetched /// </param> public static Order GetOrderById(this ISwaggerPetstore operations, string orderId) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).GetOrderByIdAsync(orderId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Find purchase order by ID /// </summary> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// ID of pet that needs to be fetched /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Order> GetOrderByIdAsync(this ISwaggerPetstore operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetOrderByIdWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete purchase order by ID /// </summary> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// ID of the order that needs to be deleted /// </param> public static void DeleteOrder(this ISwaggerPetstore operations, string orderId) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).DeleteOrderAsync(orderId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete purchase order by ID /// </summary> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// ID of the order that needs to be deleted /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteOrderAsync(this ISwaggerPetstore operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteOrderWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Create user /// </summary> /// This can only be done by the logged in user. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Created user object /// </param> public static void CreateUser(this ISwaggerPetstore operations, User body = default(User)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).CreateUserAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create user /// </summary> /// This can only be done by the logged in user. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Created user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUserAsync(this ISwaggerPetstore operations, User body = default(User), CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUserWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> public static void CreateUsersWithArrayInput(this ISwaggerPetstore operations, IList<User> body = default(IList<User>)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).CreateUsersWithArrayInputAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUsersWithArrayInputAsync(this ISwaggerPetstore operations, IList<User> body = default(IList<User>), CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> public static void CreateUsersWithListInput(this ISwaggerPetstore operations, IList<User> body = default(IList<User>)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).CreateUsersWithListInputAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUsersWithListInputAsync(this ISwaggerPetstore operations, IList<User> body = default(IList<User>), CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUsersWithListInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Logs user into the system /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> public static string LoginUser(this ISwaggerPetstore operations, string username = default(string), string password = default(string)) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).LoginUserAsync(username, password), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Logs user into the system /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> LoginUserAsync(this ISwaggerPetstore operations, string username = default(string), string password = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.LoginUserWithHttpMessagesAsync(username, password, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void LogoutUser(this ISwaggerPetstore operations) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).LogoutUserAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task LogoutUserAsync(this ISwaggerPetstore operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.LogoutUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get user by user name /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> public static User GetUserByName(this ISwaggerPetstore operations, string username) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).GetUserByNameAsync(username), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get user by user name /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<User> GetUserByNameAsync(this ISwaggerPetstore operations, string username, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetUserByNameWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updated user /// </summary> /// This can only be done by the logged in user. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> public static void UpdateUser(this ISwaggerPetstore operations, string username, User body = default(User)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).UpdateUserAsync(username, body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updated user /// </summary> /// This can only be done by the logged in user. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateUserAsync(this ISwaggerPetstore operations, string username, User body = default(User), CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdateUserWithHttpMessagesAsync(username, body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete user /// </summary> /// This can only be done by the logged in user. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> public static void DeleteUser(this ISwaggerPetstore operations, string username) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).DeleteUserAsync(username), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete user /// </summary> /// This can only be done by the logged in user. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteUserAsync(this ISwaggerPetstore operations, string username, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteUserWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Automation; using AcceptanceTestLibrary.Common.Desktop; using AcceptanceTestLibrary.Common; using AcceptanceTestLibrary.UIAWrapper; namespace AcceptanceTestLibrary.ApplicationHelper { public static class UIAExtensions { private static List<AutomationElement> automationElementList = new List<AutomationElement>(); #region Find Element Methods public static AutomationElement FindElementById(this AutomationElement ae, string automationId) { if (ae == null || String.IsNullOrEmpty(automationId)) { throw new InvalidOperationException("invalid operation"); } // Set a property condition that will be used to find the control. Condition c = new PropertyCondition( AutomationElement.AutomationIdProperty, automationId, PropertyConditionFlags.IgnoreCase); // Find the element. TreeWalker tw = new TreeWalker(c); return tw.GetFirstChild(ae); } public static AutomationElementCollection FindAllChildElements(this AutomationElement ae, AutomationElement parent) { if (parent == null || ae == null) { throw new InvalidOperationException("invalid operation"); } Condition c1 = new PropertyCondition(AutomationElement.IsControlElementProperty, true); // Find all children that match the specified conditions. return parent.FindAll(TreeScope.Children, c1); } public static AutomationElementCollection FindElementByControlType(this AutomationElement ae, string controlType) { Condition c = null; AutomationElement elementList = null; if (ae == null || String.IsNullOrEmpty(controlType)) { throw new InvalidOperationException("invalid operation"); } // Set up the CacheRequest. CacheRequest cacheRequest = new CacheRequest(); cacheRequest.Add(AutomationElement.ControlTypeProperty); cacheRequest.TreeScope = TreeScope.Element | TreeScope.Children; using (cacheRequest.Activate()) { switch(controlType) { case "List": // Set a property condition that will be used to find the control. c = new PropertyCondition( AutomationElement.ControlTypeProperty, ControlType.List); elementList = ae.FindFirst(TreeScope.Descendants, c); break; case "Tree": // Set a property condition that will be used to find the control. c = new PropertyCondition( AutomationElement.ControlTypeProperty, ControlType.Tree); elementList = ae.FindFirst(TreeScope.Descendants, c); break; case "Grid": // Set a property condition that will be used to find the control. c = new PropertyCondition( AutomationElement.ControlTypeProperty, ControlType.DataGrid); elementList = ae.FindFirst(TreeScope.Descendants, c); break; case "Tab": // Set a property condition that will be used to find the control. c = new PropertyCondition( AutomationElement.ControlTypeProperty, ControlType.Tab); elementList = ae.FindFirst(TreeScope.Descendants, c); break; case "Combo": // Set a property condition that will be used to find the control. c = new PropertyCondition( AutomationElement.ControlTypeProperty, ControlType.ComboBox); elementList = ae.FindFirst(TreeScope.Descendants, c); elementList.Expand(); return elementList.FindAllChildElements(elementList); default: break; } // Find the element. return elementList.CachedChildren; } } public static AutomationElementCollection FindAllElementsById(this AutomationElement ae, string automationid) { if (ae == null || String.IsNullOrEmpty(automationid)) { throw new InvalidOperationException("invalid operation"); } // Set a property condition that will be used to find the control. Condition c = new PropertyCondition( AutomationElement.AutomationIdProperty, automationid, PropertyConditionFlags.IgnoreCase); // Find the element. return ae.FindAll(TreeScope.Descendants, c); } public static AutomationElement FindElementByContent(this AutomationElement ae, string content) { if (ae == null || String.IsNullOrEmpty(content)) { throw new InvalidOperationException("invalid operation"); } // Set a property condition that will be used to find the control. Condition c = new PropertyCondition( AutomationElement.NameProperty, content); // Find the element. TreeWalker tw = new TreeWalker(c); return tw.GetFirstChild(ae); } public static AutomationElementCollection FindAllElementsByContent(this AutomationElement ae, string content) { if (ae == null || String.IsNullOrEmpty(content)) { throw new InvalidOperationException("invalid operation"); } // Set a property condition that will be used to find the control. Condition c = new PropertyCondition( AutomationElement.NameProperty, content); // Find the element. return ae.FindAll(TreeScope.Descendants, c); } public static List<AutomationElement> FindSiblingsInTreeByName(this AutomationElement rootElement, string name) { // Clear the automation element list. automationElementList.Clear(); AutomationElement parentElement = rootElement; WalkThroughRawTreeAndPopulateAEList(parentElement, name); return automationElementList; } public static AutomationElement SearchInRawTreeByName(this AutomationElement rootElement, string name) { AutomationElement elementNode = TreeWalker.RawViewWalker.GetFirstChild(rootElement); while (elementNode != null) { if (name.Equals(elementNode.Current.Name, StringComparison.OrdinalIgnoreCase) || (name.Equals(elementNode.Current.AutomationId, StringComparison.OrdinalIgnoreCase))) { return elementNode; } AutomationElement returnedAutomationElement = elementNode.SearchInRawTreeByName(name); if (returnedAutomationElement != null) { return returnedAutomationElement; } elementNode = TreeWalker.RawViewWalker.GetNextSibling(elementNode); } return null; } #endregion #region Get Handle Methods public static AutomationElement GetHandleById(this AutomationElement ae, string controlId) { if (ae == null || String.IsNullOrEmpty(controlId)) { throw new InvalidOperationException("invalid operation"); } return ae.FindElementById( new ResXConfigHandler(ConfigHandler.GetValue("ControlIdentifiersFile")).GetValue(controlId)); } public static AutomationElementCollection GetHandleByParent(this AutomationElement ae, AutomationElement parent) { if (parent == null || ae == null) { throw new InvalidOperationException("invalid operation"); } return ae.FindAllChildElements(parent); } public static AutomationElementCollection GetHandleByControlType(this AutomationElement ae, string controlType) { if (ae == null || String.IsNullOrEmpty(controlType)) { throw new InvalidOperationException("invalid operation"); } return ae.FindElementByControlType( new ResXConfigHandler(ConfigHandler.GetValue("ControlIdentifiersFile")).GetValue(controlType)); } public static AutomationElementCollection GetAllHandlesById(this AutomationElement ae, string controlId) { if (ae == null || String.IsNullOrEmpty(controlId)) { throw new InvalidOperationException("invalid operation"); } return ae.FindAllElementsById( new ResXConfigHandler(ConfigHandler.GetValue("ControlIdentifiersFile")).GetValue(controlId)); } public static AutomationElement GetHandleById<TApp>(this AutomationElement ae, string controlId) where TApp : AppLauncherBase { if (ae == null || String.IsNullOrEmpty(controlId)) { throw new InvalidOperationException("invalid operation"); } controlId = GetAppSpecificString<TApp>(controlId); return ae.GetHandleById(controlId); } public static AutomationElementCollection GetHandleByParent<TApp>(this AutomationElement ae, AutomationElement parent) where TApp : AppLauncherBase { if (ae == null || parent == null) { throw new InvalidOperationException("invalid operation"); } // controlId = GetAppSpecificString<TApp>(controlId); return ae.GetHandleByParent(parent); } public static AutomationElementCollection GetHandleByControlType<TApp>(this AutomationElement ae, string controlType) where TApp : AppLauncherBase { if (ae == null || String.IsNullOrEmpty(controlType)) { throw new InvalidOperationException("invalid operation"); } controlType = GetAppSpecificString<TApp>(controlType); return ae.GetHandleByControlType(controlType); } public static AutomationElementCollection GetAllHandlesById<TApp>(this AutomationElement ae, string controlId) where TApp : AppLauncherBase { if (ae == null || String.IsNullOrEmpty(controlId)) { throw new InvalidOperationException("invalid operation"); } controlId = GetAppSpecificString<TApp>(controlId); return ae.GetAllHandlesById(controlId); } public static AutomationElement GetHandleByContent(this AutomationElement ae, string content) { if (ae == null || String.IsNullOrEmpty(content)) { throw new InvalidOperationException("invalid operation"); } return ae.FindElementByContent( new ResXConfigHandler(ConfigHandler.GetValue("ControlIdentifiersFile")).GetValue(content)); } public static AutomationElementCollection GetAllHandlesByContent(this AutomationElement ae, string content) { if (ae == null || String.IsNullOrEmpty(content)) { throw new InvalidOperationException("invalid operation"); } return ae.FindAllElementsByContent( new ResXConfigHandler(ConfigHandler.GetValue("ControlIdentifiersFile")).GetValue(content)); } public static AutomationElement GetHandleByContent<TApp>(this AutomationElement ae, string content) where TApp : AppLauncherBase { if (ae == null || String.IsNullOrEmpty(content)) { throw new InvalidOperationException("invalid operation"); } content = GetAppSpecificString<TApp>(content); return ae.GetHandleByContent(content); } public static AutomationElementCollection GetAllHandlesByContent<TApp>(this AutomationElement ae, string content) where TApp : AppLauncherBase { if (ae == null || String.IsNullOrEmpty(content)) { throw new InvalidOperationException("invalid operation"); } content = GetAppSpecificString<TApp>(content); return ae.GetAllHandlesByContent(content); } #endregion #region Private Helper Methods private static void WalkThroughRawTreeAndPopulateAEList(AutomationElement parentElement, string name) { AutomationElement element = SearchInRawTreeByName(parentElement, name); AutomationElement elementNode = null; if (element != null) { // Add the element to the list; automationElementList.Add(element); elementNode = TreeWalker.RawViewWalker.GetNextSibling(element); while (elementNode != null) { // Add the elementNode to the list if (elementNode.Current.AutomationId.Equals(name)) automationElementList.Add(elementNode); else { WalkThroughRawTreeAndPopulateAEList(elementNode, name); } elementNode = TreeWalker.RawViewWalker.GetNextSibling(elementNode); } } } /// <summary> /// Private helper method for modifying the string (resource file key string) based on the app type /// </summary> /// <typeparam name="TApp"></typeparam> /// <param name="controlId"></param> /// <returns></returns> private static string GetAppSpecificString<TApp>(string controlId) where TApp : AppLauncherBase { if (typeof(WpfAppLauncher).Equals(typeof(TApp))) { controlId += "_Wpf"; } return controlId; } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyrightD * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OMV = OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { public class BSActorMoveToTarget : BSActor { private BSVMotor m_targetMotor; public BSActorMoveToTarget(BSScene physicsScene, BSPhysObject pObj, string actorName) : base(physicsScene, pObj, actorName) { m_targetMotor = null; m_physicsScene.DetailLog("{0},BSActorMoveToTarget,constructor", m_controllingPrim.LocalID); } // BSActor.isActive public override bool isActive { // MoveToTarget only works on physical prims get { return Enabled && m_controllingPrim.IsPhysicallyActive; } } // Release any connections and resources used by the actor. // BSActor.Dispose() public override void Dispose() { Enabled = false; } // Called when physical parameters (properties set in Bullet) need to be re-applied. // Called at taint-time. // BSActor.Refresh() public override void Refresh() { m_physicsScene.DetailLog("{0},BSActorMoveToTarget,refresh,enabled={1},active={2},target={3},tau={4}", m_controllingPrim.LocalID, Enabled, m_controllingPrim.MoveToTargetActive, m_controllingPrim.MoveToTargetTarget, m_controllingPrim.MoveToTargetTau); // If not active any more... if (!m_controllingPrim.MoveToTargetActive) { Enabled = false; } if (isActive) { ActivateMoveToTarget(); } else { DeactivateMoveToTarget(); } } // The object's physical representation is being rebuilt so pick up any physical dependencies (constraints, ...). // Register a prestep action to restore physical requirements before the next simulation step. // Called at taint-time. // BSActor.RemoveDependencies() public override void RemoveDependencies() { // Nothing to do for the moveToTarget since it is all software at pre-step action time. } // If a hover motor has not been created, create one and start the hovering. private void ActivateMoveToTarget() { if (m_targetMotor == null) { // We're taking over after this. m_controllingPrim.ZeroMotion(true); /* Someday use the PID controller m_targetMotor = new BSPIDVMotor("BSActorMoveToTarget-" + m_controllingPrim.LocalID.ToString()); m_targetMotor.TimeScale = m_controllingPrim.MoveToTargetTau; m_targetMotor.Efficiency = 1f; */ m_targetMotor = new BSVMotor("BSActorMoveToTarget-" + m_controllingPrim.LocalID.ToString(), m_controllingPrim.MoveToTargetTau, // timeScale BSMotor.Infinite, // decay time scale 1f // efficiency ); m_targetMotor.PhysicsScene = m_physicsScene; // DEBUG DEBUG so motor will output detail log messages. m_targetMotor.SetTarget(m_controllingPrim.MoveToTargetTarget); m_targetMotor.SetCurrent(m_controllingPrim.RawPosition); // m_physicsScene.BeforeStep += Mover; m_physicsScene.BeforeStep += Mover2; } else { // If already allocated, make sure the target and other paramters are current m_targetMotor.SetTarget(m_controllingPrim.MoveToTargetTarget); m_targetMotor.SetCurrent(m_controllingPrim.RawPosition); } } private void DeactivateMoveToTarget() { if (m_targetMotor != null) { // m_physicsScene.BeforeStep -= Mover; m_physicsScene.BeforeStep -= Mover2; m_targetMotor = null; } } // Origional mover that set the objects position to move to the target. // The problem was that gravity would keep trying to push the object down so // the overall downward velocity would increase to infinity. // Called just before the simulation step. private void Mover(float timeStep) { // Don't do hovering while the object is selected. if (!isActive) return; OMV.Vector3 origPosition = m_controllingPrim.RawPosition; // DEBUG DEBUG (for printout below) // 'movePosition' is where we'd like the prim to be at this moment. OMV.Vector3 movePosition = m_controllingPrim.RawPosition + m_targetMotor.Step(timeStep); // If we are very close to our target, turn off the movement motor. if (m_targetMotor.ErrorIsZero()) { m_physicsScene.DetailLog("{0},BSActorMoveToTarget.Mover,zeroMovement,movePos={1},pos={2},mass={3}", m_controllingPrim.LocalID, movePosition, m_controllingPrim.RawPosition, m_controllingPrim.Mass); m_controllingPrim.ForcePosition = m_targetMotor.TargetValue; m_controllingPrim.ForceVelocity = OMV.Vector3.Zero; // Setting the position does not cause the physics engine to generate a property update. Force it. m_physicsScene.PE.PushUpdate(m_controllingPrim.PhysBody); } else { m_controllingPrim.ForcePosition = movePosition; // Setting the position does not cause the physics engine to generate a property update. Force it. m_physicsScene.PE.PushUpdate(m_controllingPrim.PhysBody); } m_physicsScene.DetailLog("{0},BSActorMoveToTarget.Mover,move,fromPos={1},movePos={2}", m_controllingPrim.LocalID, origPosition, movePosition); } // Version of mover that applies forces to move the physical object to the target. // Also overcomes gravity so the object doesn't just drop to the ground. // Called just before the simulation step. private void Mover2(float timeStep) { // Don't do hovering while the object is selected. if (!isActive) return; OMV.Vector3 origPosition = m_controllingPrim.RawPosition; // DEBUG DEBUG (for printout below) OMV.Vector3 addedForce = OMV.Vector3.Zero; // CorrectionVector is the movement vector required this step OMV.Vector3 correctionVector = m_targetMotor.Step(timeStep, m_controllingPrim.RawPosition); // If we are very close to our target, turn off the movement motor. if (m_targetMotor.ErrorIsZero()) { m_physicsScene.DetailLog("{0},BSActorMoveToTarget.Mover3,zeroMovement,pos={1},mass={2}", m_controllingPrim.LocalID, m_controllingPrim.RawPosition, m_controllingPrim.Mass); m_controllingPrim.ForcePosition = m_targetMotor.TargetValue; m_controllingPrim.ForceVelocity = OMV.Vector3.Zero; // Setting the position does not cause the physics engine to generate a property update. Force it. m_physicsScene.PE.PushUpdate(m_controllingPrim.PhysBody); } else { // First force to move us there -- the motor return a timestep scaled value. addedForce = correctionVector / timeStep; // Remove the existing velocity (only the moveToTarget force counts) addedForce -= m_controllingPrim.RawVelocity; // Overcome gravity. addedForce -= m_controllingPrim.Gravity; // Add enough force to overcome the mass of the object addedForce *= m_controllingPrim.Mass; m_controllingPrim.AddForce(addedForce, false /* pushForce */, true /* inTaintTime */); } m_physicsScene.DetailLog("{0},BSActorMoveToTarget.Mover3,move,fromPos={1},addedForce={2}", m_controllingPrim.LocalID, origPosition, addedForce); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureReport { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Test Infrastructure for AutoRest /// </summary> public partial class AutoRestReportServiceForAzure : Microsoft.Rest.ServiceClient<AutoRestReportServiceForAzure>, IAutoRestReportServiceForAzure, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzure class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestReportServiceForAzure(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzure class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestReportServiceForAzure(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzure class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestReportServiceForAzure(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzure class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestReportServiceForAzure(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzure class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportServiceForAzure(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzure class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportServiceForAzure(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzure class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportServiceForAzure(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzure class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportServiceForAzure(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new System.Uri("http://localhost"); this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter()); } /// <summary> /// Get test coverage report /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IDictionary<string, int?>>> GetReportWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetReport", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "report/azure").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IDictionary<string, int?>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IDictionary<string, int?>>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// CRC32.cs // ------------------------------------------------------------------ // // Copyright (c) 2011 Dino Chiesa. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // Last Saved: <2011-August-02 18:25:54> // // ------------------------------------------------------------------ // // This module defines the CRC32 class, which can do the CRC32 algorithm, using // arbitrary starting polynomials, and bit reversal. The bit reversal is what // distinguishes this CRC-32 used in BZip2 from the CRC-32 that is used in PKZIP // files, or GZIP files. This class does both. // // ------------------------------------------------------------------ using System; using Interop = System.Runtime.InteropServices; namespace Ionic.Crc { /// <summary> /// Computes a CRC-32. The CRC-32 algorithm is parameterized - you /// can set the polynomial and enable or disable bit /// reversal. This can be used for GZIP, BZip2, or ZIP. /// </summary> /// <remarks> /// This type is used internally by DotNetZip; it is generally not used /// directly by applications wishing to create, read, or manipulate zip /// archive files. /// </remarks> #if !PCL [Interop.GuidAttribute("ebc25cf6-9120-4283-b972-0e5520d0000C")] [Interop.ComVisible(true)] #if !NETCF [Interop.ClassInterface(Interop.ClassInterfaceType.AutoDispatch)] #endif #endif public class CRC32 { /// <summary> /// Indicates the total number of bytes applied to the CRC. /// </summary> public Int64 TotalBytesRead { get { return _TotalBytesRead; } } /// <summary> /// Indicates the current CRC for all blocks slurped in. /// </summary> public Int32 Crc32Result { get { return unchecked((Int32)(~_register)); } } /// <summary> /// Returns the CRC32 for the specified stream. /// </summary> /// <param name="input">The stream over which to calculate the CRC32</param> /// <returns>the CRC32 calculation</returns> public Int32 GetCrc32(System.IO.Stream input) { return GetCrc32AndCopy(input, null); } /// <summary> /// Returns the CRC32 for the specified stream, and writes the input into the /// output stream. /// </summary> /// <param name="input">The stream over which to calculate the CRC32</param> /// <param name="output">The stream into which to deflate the input</param> /// <returns>the CRC32 calculation</returns> public Int32 GetCrc32AndCopy(System.IO.Stream input, System.IO.Stream output) { if (input == null) throw new Exception("The input stream must not be null."); unchecked { byte[] buffer = new byte[BUFFER_SIZE]; int readSize = BUFFER_SIZE; _TotalBytesRead = 0; int count = input.Read(buffer, 0, readSize); if (output != null) output.Write(buffer, 0, count); _TotalBytesRead += count; while (count > 0) { SlurpBlock(buffer, 0, count); count = input.Read(buffer, 0, readSize); if (output != null) output.Write(buffer, 0, count); _TotalBytesRead += count; } return (Int32)(~_register); } } /// <summary> /// Get the CRC32 for the given (word,byte) combo. This is a /// computation defined by PKzip for PKZIP 2.0 (weak) encryption. /// </summary> /// <param name="W">The word to start with.</param> /// <param name="B">The byte to combine it with.</param> /// <returns>The CRC-ized result.</returns> public Int32 ComputeCrc32(Int32 W, byte B) { return _InternalComputeCrc32((UInt32)W, B); } internal Int32 _InternalComputeCrc32(UInt32 W, byte B) { return (Int32)(crc32Table[(W ^ B) & 0xFF] ^ (W >> 8)); } /// <summary> /// Update the value for the running CRC32 using the given block of bytes. /// This is useful when using the CRC32() class in a Stream. /// </summary> /// <param name="block">block of bytes to slurp</param> /// <param name="offset">starting point in the block</param> /// <param name="count">how many bytes within the block to slurp</param> public void SlurpBlock(byte[] block, int offset, int count) { if (block == null) throw new Exception("The data buffer must not be null."); // bzip algorithm for (int i = 0; i < count; i++) { int x = offset + i; byte b = block[x]; if (this.reverseBits) { UInt32 temp = (_register >> 24) ^ b; _register = (_register << 8) ^ crc32Table[temp]; } else { UInt32 temp = (_register & 0x000000FF) ^ b; _register = (_register >> 8) ^ crc32Table[temp]; } } _TotalBytesRead += count; } /// <summary> /// Process one byte in the CRC. /// </summary> /// <param name = "b">the byte to include into the CRC . </param> public void UpdateCRC(byte b) { if (this.reverseBits) { UInt32 temp = (_register >> 24) ^ b; _register = (_register << 8) ^ crc32Table[temp]; } else { UInt32 temp = (_register & 0x000000FF) ^ b; _register = (_register >> 8) ^ crc32Table[temp]; } } /// <summary> /// Process a run of N identical bytes into the CRC. /// </summary> /// <remarks> /// <para> /// This method serves as an optimization for updating the CRC when a /// run of identical bytes is found. Rather than passing in a buffer of /// length n, containing all identical bytes b, this method accepts the /// byte value and the length of the (virtual) buffer - the length of /// the run. /// </para> /// </remarks> /// <param name = "b">the byte to include into the CRC. </param> /// <param name = "n">the number of times that byte should be repeated. </param> public void UpdateCRC(byte b, int n) { while (n-- > 0) { if (this.reverseBits) { uint temp = (_register >> 24) ^ b; _register = (_register << 8) ^ crc32Table[(temp >= 0) ? temp : (temp + 256)]; } else { UInt32 temp = (_register & 0x000000FF) ^ b; _register = (_register >> 8) ^ crc32Table[(temp >= 0) ? temp : (temp + 256)]; } } } private static uint ReverseBits(uint data) { unchecked { uint ret = data; ret = (ret & 0x55555555) << 1 | (ret >> 1) & 0x55555555; ret = (ret & 0x33333333) << 2 | (ret >> 2) & 0x33333333; ret = (ret & 0x0F0F0F0F) << 4 | (ret >> 4) & 0x0F0F0F0F; ret = (ret << 24) | ((ret & 0xFF00) << 8) | ((ret >> 8) & 0xFF00) | (ret >> 24); return ret; } } private static byte ReverseBits(byte data) { unchecked { uint u = (uint)data * 0x00020202; uint m = 0x01044010; uint s = u & m; uint t = (u << 2) & (m << 1); return (byte)((0x01001001 * (s + t)) >> 24); } } private void GenerateLookupTable() { crc32Table = new UInt32[256]; unchecked { UInt32 dwCrc; byte i = 0; do { dwCrc = i; for (byte j = 8; j > 0; j--) { if ((dwCrc & 1) == 1) { dwCrc = (dwCrc >> 1) ^ dwPolynomial; } else { dwCrc >>= 1; } } if (reverseBits) { crc32Table[ReverseBits(i)] = ReverseBits(dwCrc); } else { crc32Table[i] = dwCrc; } i++; } while (i!=0); } #if VERBOSE Console.WriteLine(); Console.WriteLine("private static readonly UInt32[] crc32Table = {"); for (int i = 0; i < crc32Table.Length; i+=4) { Console.Write(" "); for (int j=0; j < 4; j++) { Console.Write(" 0x{0:X8}U,", crc32Table[i+j]); } Console.WriteLine(); } Console.WriteLine("};"); Console.WriteLine(); #endif } private uint gf2_matrix_times(uint[] matrix, uint vec) { uint sum = 0; int i=0; while (vec != 0) { if ((vec & 0x01)== 0x01) sum ^= matrix[i]; vec >>= 1; i++; } return sum; } private void gf2_matrix_square(uint[] square, uint[] mat) { for (int i = 0; i < 32; i++) square[i] = gf2_matrix_times(mat, mat[i]); } /// <summary> /// Combines the given CRC32 value with the current running total. /// </summary> /// <remarks> /// This is useful when using a divide-and-conquer approach to /// calculating a CRC. Multiple threads can each calculate a /// CRC32 on a segment of the data, and then combine the /// individual CRC32 values at the end. /// </remarks> /// <param name="crc">the crc value to be combined with this one</param> /// <param name="length">the length of data the CRC value was calculated on</param> public void Combine(int crc, int length) { uint[] even = new uint[32]; // even-power-of-two zeros operator uint[] odd = new uint[32]; // odd-power-of-two zeros operator if (length == 0) return; uint crc1= ~_register; uint crc2= (uint) crc; // put operator for one zero bit in odd odd[0] = this.dwPolynomial; // the CRC-32 polynomial uint row = 1; for (int i = 1; i < 32; i++) { odd[i] = row; row <<= 1; } // put operator for two zero bits in even gf2_matrix_square(even, odd); // put operator for four zero bits in odd gf2_matrix_square(odd, even); uint len2 = (uint) length; // apply len2 zeros to crc1 (first square will put the operator for one // zero byte, eight zero bits, in even) do { // apply zeros operator for this bit of len2 gf2_matrix_square(even, odd); if ((len2 & 1)== 1) crc1 = gf2_matrix_times(even, crc1); len2 >>= 1; if (len2 == 0) break; // another iteration of the loop with odd and even swapped gf2_matrix_square(odd, even); if ((len2 & 1)==1) crc1 = gf2_matrix_times(odd, crc1); len2 >>= 1; } while (len2 != 0); crc1 ^= crc2; _register= ~crc1; //return (int) crc1; return; } /// <summary> /// Create an instance of the CRC32 class using the default settings: no /// bit reversal, and a polynomial of 0xEDB88320. /// </summary> public CRC32() : this(false) { } /// <summary> /// Create an instance of the CRC32 class, specifying whether to reverse /// data bits or not. /// </summary> /// <param name='reverseBits'> /// specify true if the instance should reverse data bits. /// </param> /// <remarks> /// <para> /// In the CRC-32 used by BZip2, the bits are reversed. Therefore if you /// want a CRC32 with compatibility with BZip2, you should pass true /// here. In the CRC-32 used by GZIP and PKZIP, the bits are not /// reversed; Therefore if you want a CRC32 with compatibility with /// those, you should pass false. /// </para> /// </remarks> public CRC32(bool reverseBits) : this( unchecked((int)0xEDB88320), reverseBits) { } /// <summary> /// Create an instance of the CRC32 class, specifying the polynomial and /// whether to reverse data bits or not. /// </summary> /// <param name='polynomial'> /// The polynomial to use for the CRC, expressed in the reversed (LSB) /// format: the highest ordered bit in the polynomial value is the /// coefficient of the 0th power; the second-highest order bit is the /// coefficient of the 1 power, and so on. Expressed this way, the /// polynomial for the CRC-32C used in IEEE 802.3, is 0xEDB88320. /// </param> /// <param name='reverseBits'> /// specify true if the instance should reverse data bits. /// </param> /// /// <remarks> /// <para> /// In the CRC-32 used by BZip2, the bits are reversed. Therefore if you /// want a CRC32 with compatibility with BZip2, you should pass true /// here for the <c>reverseBits</c> parameter. In the CRC-32 used by /// GZIP and PKZIP, the bits are not reversed; Therefore if you want a /// CRC32 with compatibility with those, you should pass false for the /// <c>reverseBits</c> parameter. /// </para> /// </remarks> public CRC32(int polynomial, bool reverseBits) { this.reverseBits = reverseBits; this.dwPolynomial = (uint) polynomial; this.GenerateLookupTable(); } /// <summary> /// Reset the CRC-32 class - clear the CRC "remainder register." /// </summary> /// <remarks> /// <para> /// Use this when employing a single instance of this class to compute /// multiple, distinct CRCs on multiple, distinct data blocks. /// </para> /// </remarks> public void Reset() { _register = 0xFFFFFFFFU; } // private member vars private UInt32 dwPolynomial; private Int64 _TotalBytesRead; private bool reverseBits; private UInt32[] crc32Table; private const int BUFFER_SIZE = 8192; private UInt32 _register = 0xFFFFFFFFU; } /// <summary> /// A Stream that calculates a CRC32 (a checksum) on all bytes read, /// or on all bytes written. /// </summary> /// /// <remarks> /// <para> /// This class can be used to verify the CRC of a ZipEntry when /// reading from a stream, or to calculate a CRC when writing to a /// stream. The stream should be used to either read, or write, but /// not both. If you intermix reads and writes, the results are not /// defined. /// </para> /// /// <para> /// This class is intended primarily for use internally by the /// DotNetZip library. /// </para> /// </remarks> public class CrcCalculatorStream : System.IO.Stream, IDisposable { static readonly Int64 UnsetLengthLimit = -99; readonly System.IO.Stream _innerStream; readonly CRC32 _crc32; readonly Int64 _lengthLimit = -99; bool _leaveOpen; /// <summary> /// The default constructor. /// </summary> /// <remarks> /// <para> /// Instances returned from this constructor will leave the underlying /// stream open upon Close(). The stream uses the default CRC32 /// algorithm, which implies a polynomial of 0xEDB88320. /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> public CrcCalculatorStream(System.IO.Stream stream) : this(true, UnsetLengthLimit, stream, null) { } /// <summary> /// The constructor allows the caller to specify how to handle the /// underlying stream at close. /// </summary> /// <remarks> /// <para> /// The stream uses the default CRC32 algorithm, which implies a /// polynomial of 0xEDB88320. /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> /// <param name="leaveOpen">true to leave the underlying stream /// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param> public CrcCalculatorStream(System.IO.Stream stream, bool leaveOpen) : this(leaveOpen, UnsetLengthLimit, stream, null) { } /// <summary> /// A constructor allowing the specification of the length of the stream /// to read. /// </summary> /// <remarks> /// <para> /// The stream uses the default CRC32 algorithm, which implies a /// polynomial of 0xEDB88320. /// </para> /// <para> /// Instances returned from this constructor will leave the underlying /// stream open upon Close(). /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> /// <param name="length">The length of the stream to slurp</param> public CrcCalculatorStream(System.IO.Stream stream, Int64 length) : this(true, length, stream, null) { if (length < 0) throw new ArgumentException("length"); } /// <summary> /// A constructor allowing the specification of the length of the stream /// to read, as well as whether to keep the underlying stream open upon /// Close(). /// </summary> /// <remarks> /// <para> /// The stream uses the default CRC32 algorithm, which implies a /// polynomial of 0xEDB88320. /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> /// <param name="length">The length of the stream to slurp</param> /// <param name="leaveOpen">true to leave the underlying stream /// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param> public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen) : this(leaveOpen, length, stream, null) { if (length < 0) throw new ArgumentException("length"); } /// <summary> /// A constructor allowing the specification of the length of the stream /// to read, as well as whether to keep the underlying stream open upon /// Close(), and the CRC32 instance to use. /// </summary> /// <remarks> /// <para> /// The stream uses the specified CRC32 instance, which allows the /// application to specify how the CRC gets calculated. /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> /// <param name="length">The length of the stream to slurp</param> /// <param name="leaveOpen">true to leave the underlying stream /// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param> /// <param name="crc32">the CRC32 instance to use to calculate the CRC32</param> public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen, CRC32 crc32) : this(leaveOpen, length, stream, crc32) { if (length < 0) throw new ArgumentException("length"); } // This ctor is private - no validation except null is done here. // This is to allow the use // of a (specific) negative value for the _lengthLimit, to indicate that there // is no length set. So we validate the length limit in those ctors that use an // explicit param, otherwise we don't validate, because it could be our special // value. CrcCalculatorStream(bool leaveOpen, Int64 length, System.IO.Stream stream, CRC32 crc32) { if (stream == null) throw new ArgumentNullException("stream"); _innerStream = stream; _crc32 = crc32 ?? new CRC32(); _lengthLimit = length; _leaveOpen = leaveOpen; } /// <summary> /// Gets the total number of bytes run through the CRC32 calculator. /// </summary> /// /// <remarks> /// This is either the total number of bytes read, or the total number of /// bytes written, depending on the direction of this stream. /// </remarks> public Int64 TotalBytesSlurped { get { return _crc32.TotalBytesRead; } } /// <summary> /// Provides the current CRC for all blocks slurped in. /// </summary> /// <remarks> /// <para> /// The running total of the CRC is kept as data is written or read /// through the stream. read this property after all reads or writes to /// get an accurate CRC for the entire stream. /// </para> /// </remarks> public Int32 Crc { get { return _crc32.Crc32Result; } } /// <summary> /// Indicates whether the underlying stream will be left open when the /// <c>CrcCalculatorStream</c> is Closed. /// </summary> /// <remarks> /// <para> /// Set this at any point before calling <see cref="Close()"/>. /// </para> /// </remarks> public bool LeaveOpen { get { return _leaveOpen; } set { _leaveOpen = value; } } /// <summary> /// Read from the stream /// </summary> /// <param name="buffer">the buffer to read</param> /// <param name="offset">the offset at which to start</param> /// <param name="count">the number of bytes to read</param> /// <returns>the number of bytes actually read</returns> public override int Read(byte[] buffer, int offset, int count) { int bytesToRead = count; // Need to limit the # of bytes returned, if the stream is intended to have // a definite length. This is especially useful when returning a stream for // the uncompressed data directly to the application. The app won't // necessarily read only the UncompressedSize number of bytes. For example // wrapping the stream returned from OpenReader() into a StreadReader() and // calling ReadToEnd() on it, We can "over-read" the zip data and get a // corrupt string. The length limits that, prevents that problem. if (_lengthLimit != CrcCalculatorStream.UnsetLengthLimit) { if (_crc32.TotalBytesRead >= _lengthLimit) return 0; // EOF Int64 bytesRemaining = _lengthLimit - _crc32.TotalBytesRead; if (bytesRemaining < count) bytesToRead = (int)bytesRemaining; } int n = _innerStream.Read(buffer, offset, bytesToRead); if (n > 0) _crc32.SlurpBlock(buffer, offset, n); return n; } /// <summary> /// Write to the stream. /// </summary> /// <param name="buffer">the buffer from which to write</param> /// <param name="offset">the offset at which to start writing</param> /// <param name="count">the number of bytes to write</param> public override void Write(byte[] buffer, int offset, int count) { if (count > 0) _crc32.SlurpBlock(buffer, offset, count); _innerStream.Write(buffer, offset, count); } /// <summary> /// Indicates whether the stream supports reading. /// </summary> public override bool CanRead { get { return _innerStream.CanRead; } } /// <summary> /// Indicates whether the stream supports seeking. /// </summary> /// <remarks> /// <para> /// Always returns false. /// </para> /// </remarks> public override bool CanSeek { get { return false; } } /// <summary> /// Indicates whether the stream supports writing. /// </summary> public override bool CanWrite { get { return _innerStream.CanWrite; } } /// <summary> /// Flush the stream. /// </summary> public override void Flush() { _innerStream.Flush(); } /// <summary> /// Returns the length of the underlying stream. /// </summary> public override long Length { get { if (_lengthLimit == CrcCalculatorStream.UnsetLengthLimit) return _innerStream.Length; else return _lengthLimit; } } /// <summary> /// The getter for this property returns the total bytes read. /// If you use the setter, it will throw /// <see cref="NotSupportedException"/>. /// </summary> public override long Position { get { return _crc32.TotalBytesRead; } set { throw new NotSupportedException(); } } /// <summary> /// Seeking is not supported on this stream. This method always throws /// <see cref="NotSupportedException"/> /// </summary> /// <param name="offset">N/A</param> /// <param name="origin">N/A</param> /// <returns>N/A</returns> public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// This method always throws /// <see cref="NotSupportedException"/> /// </summary> /// <param name="value">N/A</param> public override void SetLength(long value) { throw new NotSupportedException(); } void IDisposable.Dispose() { InnerClose(); } private void InnerClose() { if (!_leaveOpen) { #if !PCL _innerStream.Close(); #else _innerStream.Dispose(); #endif } } /// <summary> /// Closes the stream. /// </summary> #if !PCL public override void Close() { base.Close(); InnerClose(); } #endif } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime; using System.Threading; namespace System.ServiceModel.Channels { internal enum LifetimeState { Opened, Closing, Closed } internal class LifetimeManager { private bool _aborted; private int _busyCount; private ICommunicationWaiter _busyWaiter; private int _busyWaiterCount; private object _mutex; private LifetimeState _state; public LifetimeManager(object mutex) { _mutex = mutex; _state = LifetimeState.Opened; } public int BusyCount { get { return _busyCount; } } protected LifetimeState State { get { return _state; } } protected object ThisLock { get { return _mutex; } } public void Abort() { lock (this.ThisLock) { if (this.State == LifetimeState.Closed || _aborted) return; _aborted = true; _state = LifetimeState.Closing; } this.OnAbort(); _state = LifetimeState.Closed; } private void ThrowIfNotOpened() { if (!_aborted && _state != LifetimeState.Opened) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().ToString())); } } public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { lock (this.ThisLock) { this.ThrowIfNotOpened(); _state = LifetimeState.Closing; } return this.OnBeginClose(timeout, callback, state); } public void Close(TimeSpan timeout) { lock (this.ThisLock) { this.ThrowIfNotOpened(); _state = LifetimeState.Closing; } this.OnClose(timeout); _state = LifetimeState.Closed; } private CommunicationWaitResult CloseCore(TimeSpan timeout, bool aborting) { ICommunicationWaiter busyWaiter = null; CommunicationWaitResult result = CommunicationWaitResult.Succeeded; lock (this.ThisLock) { if (_busyCount > 0) { if (_busyWaiter != null) { if (!aborting && _aborted) return CommunicationWaitResult.Aborted; busyWaiter = _busyWaiter; } else { busyWaiter = new SyncCommunicationWaiter(this.ThisLock); _busyWaiter = busyWaiter; } Interlocked.Increment(ref _busyWaiterCount); } } if (busyWaiter != null) { result = busyWaiter.Wait(timeout, aborting); if (Interlocked.Decrement(ref _busyWaiterCount) == 0) { busyWaiter.Dispose(); _busyWaiter = null; } } return result; } protected void DecrementBusyCount() { ICommunicationWaiter busyWaiter = null; bool empty = false; lock (this.ThisLock) { if (_busyCount <= 0) { throw Fx.AssertAndThrow("LifetimeManager.DecrementBusyCount: (this.busyCount > 0)"); } if (--_busyCount == 0) { if (_busyWaiter != null) { busyWaiter = _busyWaiter; Interlocked.Increment(ref _busyWaiterCount); } empty = true; } } if (busyWaiter != null) { busyWaiter.Signal(); if (Interlocked.Decrement(ref _busyWaiterCount) == 0) { busyWaiter.Dispose(); _busyWaiter = null; } } if (empty && this.State == LifetimeState.Opened) OnEmpty(); } public void EndClose(IAsyncResult result) { this.OnEndClose(result); _state = LifetimeState.Closed; } protected virtual void IncrementBusyCount() { lock (this.ThisLock) { Fx.Assert(this.State == LifetimeState.Opened, "LifetimeManager.IncrementBusyCount: (this.State == LifetimeState.Opened)"); _busyCount++; } } protected virtual void IncrementBusyCountWithoutLock() { Fx.Assert(this.State == LifetimeState.Opened, "LifetimeManager.IncrementBusyCountWithoutLock: (this.State == LifetimeState.Opened)"); _busyCount++; } protected virtual void OnAbort() { // We have decided not to make this configurable CloseCore(TimeSpan.FromSeconds(1), true); } protected virtual IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { CloseCommunicationAsyncResult closeResult = null; lock (this.ThisLock) { if (_busyCount > 0) { if (_busyWaiter != null) { Fx.Assert(_aborted, "LifetimeManager.OnBeginClose: (this.aborted == true)"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().ToString())); } else { closeResult = new CloseCommunicationAsyncResult(timeout, callback, state, this.ThisLock); Fx.Assert(_busyWaiter == null, "LifetimeManager.OnBeginClose: (this.busyWaiter == null)"); _busyWaiter = closeResult; Interlocked.Increment(ref _busyWaiterCount); } } } if (closeResult != null) { return closeResult; } else { return new CompletedAsyncResult(callback, state); } } protected virtual void OnClose(TimeSpan timeout) { switch (CloseCore(timeout, false)) { case CommunicationWaitResult.Expired: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(SR.SFxCloseTimedOut1, timeout))); case CommunicationWaitResult.Aborted: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().ToString())); } } protected virtual void OnEmpty() { } protected virtual void OnEndClose(IAsyncResult result) { if (result is CloseCommunicationAsyncResult) { CloseCommunicationAsyncResult.End(result); if (Interlocked.Decrement(ref _busyWaiterCount) == 0) { _busyWaiter.Dispose(); _busyWaiter = null; } } else CompletedAsyncResult.End(result); } } internal enum CommunicationWaitResult { Waiting, Succeeded, Expired, Aborted } internal interface ICommunicationWaiter : IDisposable { void Signal(); CommunicationWaitResult Wait(TimeSpan timeout, bool aborting); } internal class CloseCommunicationAsyncResult : AsyncResult, ICommunicationWaiter { private object _mutex; private CommunicationWaitResult _result; private Timer _timer; private TimeoutHelper _timeoutHelper; private TimeSpan _timeout; public CloseCommunicationAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, object mutex) : base(callback, state) { _timeout = timeout; _timeoutHelper = new TimeoutHelper(timeout); _mutex = mutex; if (timeout < TimeSpan.Zero) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(SR.SFxCloseTimedOut1, timeout))); _timer = new Timer(new TimerCallback(new Action<object>(TimeoutCallback)), this, timeout, TimeSpan.FromMilliseconds(-1)); } private object ThisLock { get { return _mutex; } } public void Dispose() { } public static void End(IAsyncResult result) { AsyncResult.End<CloseCommunicationAsyncResult>(result); } public void Signal() { lock (this.ThisLock) { if (_result != CommunicationWaitResult.Waiting) return; _result = CommunicationWaitResult.Succeeded; } _timer.Change(TimeSpan.FromMilliseconds(-1), TimeSpan.FromMilliseconds(-1)); this.Complete(false); } private void Timeout() { lock (this.ThisLock) { if (_result != CommunicationWaitResult.Waiting) return; _result = CommunicationWaitResult.Expired; } this.Complete(false, new TimeoutException(SR.Format(SR.SFxCloseTimedOut1, _timeout))); } private static void TimeoutCallback(object state) { CloseCommunicationAsyncResult closeResult = (CloseCommunicationAsyncResult)state; closeResult.Timeout(); } public CommunicationWaitResult Wait(TimeSpan timeout, bool aborting) { if (timeout < TimeSpan.Zero) { return CommunicationWaitResult.Expired; } // Synchronous Wait on AsyncResult should only be called in Abort code-path Fx.Assert(aborting, "CloseCommunicationAsyncResult.Wait: (aborting == true)"); lock (this.ThisLock) { if (_result != CommunicationWaitResult.Waiting) { return _result; } _result = CommunicationWaitResult.Aborted; } _timer.Change(TimeSpan.FromMilliseconds(-1), TimeSpan.FromMilliseconds(-1)); TimeoutHelper.WaitOne(this.AsyncWaitHandle, timeout); this.Complete(false, new ObjectDisposedException(this.GetType().ToString())); return _result; } } internal class SyncCommunicationWaiter : ICommunicationWaiter { private bool _closed; private object _mutex; private CommunicationWaitResult _result; private ManualResetEvent _waitHandle; public SyncCommunicationWaiter(object mutex) { _mutex = mutex; _waitHandle = new ManualResetEvent(false); } private object ThisLock { get { return _mutex; } } public void Dispose() { lock (this.ThisLock) { if (_closed) return; _closed = true; _waitHandle.Dispose(); } } public void Signal() { lock (this.ThisLock) { if (_closed) return; _waitHandle.Set(); } } public CommunicationWaitResult Wait(TimeSpan timeout, bool aborting) { if (_closed) { return CommunicationWaitResult.Aborted; } if (timeout < TimeSpan.Zero) { return CommunicationWaitResult.Expired; } if (aborting) { _result = CommunicationWaitResult.Aborted; } bool expired = !TimeoutHelper.WaitOne(_waitHandle, timeout); lock (this.ThisLock) { if (_result == CommunicationWaitResult.Waiting) { _result = (expired ? CommunicationWaitResult.Expired : CommunicationWaitResult.Succeeded); } } lock (this.ThisLock) { if (!_closed) _waitHandle.Set(); // unblock other waiters if there are any } return _result; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace Southwind{ /// <summary> /// Strongly-typed collection for the Invoice class. /// </summary> [Serializable] public partial class InvoiceCollection : ReadOnlyList<Invoice, InvoiceCollection> { public InvoiceCollection() {} } /// <summary> /// This is Read-only wrapper class for the invoices view. /// </summary> [Serializable] public partial class Invoice : ReadOnlyRecord<Invoice>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("invoices", TableType.View, DataService.GetInstance("Southwind")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @""; //columns TableSchema.TableColumn colvarShipName = new TableSchema.TableColumn(schema); colvarShipName.ColumnName = "ShipName"; colvarShipName.DataType = DbType.String; colvarShipName.MaxLength = 40; colvarShipName.AutoIncrement = false; colvarShipName.IsNullable = true; colvarShipName.IsPrimaryKey = false; colvarShipName.IsForeignKey = false; colvarShipName.IsReadOnly = false; schema.Columns.Add(colvarShipName); TableSchema.TableColumn colvarShipAddress = new TableSchema.TableColumn(schema); colvarShipAddress.ColumnName = "ShipAddress"; colvarShipAddress.DataType = DbType.String; colvarShipAddress.MaxLength = 60; colvarShipAddress.AutoIncrement = false; colvarShipAddress.IsNullable = true; colvarShipAddress.IsPrimaryKey = false; colvarShipAddress.IsForeignKey = false; colvarShipAddress.IsReadOnly = false; schema.Columns.Add(colvarShipAddress); TableSchema.TableColumn colvarShipCity = new TableSchema.TableColumn(schema); colvarShipCity.ColumnName = "ShipCity"; colvarShipCity.DataType = DbType.String; colvarShipCity.MaxLength = 15; colvarShipCity.AutoIncrement = false; colvarShipCity.IsNullable = true; colvarShipCity.IsPrimaryKey = false; colvarShipCity.IsForeignKey = false; colvarShipCity.IsReadOnly = false; schema.Columns.Add(colvarShipCity); TableSchema.TableColumn colvarShipRegion = new TableSchema.TableColumn(schema); colvarShipRegion.ColumnName = "ShipRegion"; colvarShipRegion.DataType = DbType.String; colvarShipRegion.MaxLength = 15; colvarShipRegion.AutoIncrement = false; colvarShipRegion.IsNullable = true; colvarShipRegion.IsPrimaryKey = false; colvarShipRegion.IsForeignKey = false; colvarShipRegion.IsReadOnly = false; schema.Columns.Add(colvarShipRegion); TableSchema.TableColumn colvarShipPostalCode = new TableSchema.TableColumn(schema); colvarShipPostalCode.ColumnName = "ShipPostalCode"; colvarShipPostalCode.DataType = DbType.String; colvarShipPostalCode.MaxLength = 10; colvarShipPostalCode.AutoIncrement = false; colvarShipPostalCode.IsNullable = true; colvarShipPostalCode.IsPrimaryKey = false; colvarShipPostalCode.IsForeignKey = false; colvarShipPostalCode.IsReadOnly = false; schema.Columns.Add(colvarShipPostalCode); TableSchema.TableColumn colvarShipCountry = new TableSchema.TableColumn(schema); colvarShipCountry.ColumnName = "ShipCountry"; colvarShipCountry.DataType = DbType.String; colvarShipCountry.MaxLength = 15; colvarShipCountry.AutoIncrement = false; colvarShipCountry.IsNullable = true; colvarShipCountry.IsPrimaryKey = false; colvarShipCountry.IsForeignKey = false; colvarShipCountry.IsReadOnly = false; schema.Columns.Add(colvarShipCountry); TableSchema.TableColumn colvarCustomerID = new TableSchema.TableColumn(schema); colvarCustomerID.ColumnName = "CustomerID"; colvarCustomerID.DataType = DbType.AnsiStringFixedLength; colvarCustomerID.MaxLength = 5; colvarCustomerID.AutoIncrement = false; colvarCustomerID.IsNullable = true; colvarCustomerID.IsPrimaryKey = false; colvarCustomerID.IsForeignKey = false; colvarCustomerID.IsReadOnly = false; schema.Columns.Add(colvarCustomerID); TableSchema.TableColumn colvarCustomerName = new TableSchema.TableColumn(schema); colvarCustomerName.ColumnName = "CustomerName"; colvarCustomerName.DataType = DbType.String; colvarCustomerName.MaxLength = 40; colvarCustomerName.AutoIncrement = false; colvarCustomerName.IsNullable = false; colvarCustomerName.IsPrimaryKey = false; colvarCustomerName.IsForeignKey = false; colvarCustomerName.IsReadOnly = false; schema.Columns.Add(colvarCustomerName); TableSchema.TableColumn colvarAddress = new TableSchema.TableColumn(schema); colvarAddress.ColumnName = "Address"; colvarAddress.DataType = DbType.String; colvarAddress.MaxLength = 60; colvarAddress.AutoIncrement = false; colvarAddress.IsNullable = true; colvarAddress.IsPrimaryKey = false; colvarAddress.IsForeignKey = false; colvarAddress.IsReadOnly = false; schema.Columns.Add(colvarAddress); TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema); colvarCity.ColumnName = "City"; colvarCity.DataType = DbType.String; colvarCity.MaxLength = 15; colvarCity.AutoIncrement = false; colvarCity.IsNullable = true; colvarCity.IsPrimaryKey = false; colvarCity.IsForeignKey = false; colvarCity.IsReadOnly = false; schema.Columns.Add(colvarCity); TableSchema.TableColumn colvarRegion = new TableSchema.TableColumn(schema); colvarRegion.ColumnName = "Region"; colvarRegion.DataType = DbType.String; colvarRegion.MaxLength = 15; colvarRegion.AutoIncrement = false; colvarRegion.IsNullable = true; colvarRegion.IsPrimaryKey = false; colvarRegion.IsForeignKey = false; colvarRegion.IsReadOnly = false; schema.Columns.Add(colvarRegion); TableSchema.TableColumn colvarPostalCode = new TableSchema.TableColumn(schema); colvarPostalCode.ColumnName = "PostalCode"; colvarPostalCode.DataType = DbType.String; colvarPostalCode.MaxLength = 10; colvarPostalCode.AutoIncrement = false; colvarPostalCode.IsNullable = true; colvarPostalCode.IsPrimaryKey = false; colvarPostalCode.IsForeignKey = false; colvarPostalCode.IsReadOnly = false; schema.Columns.Add(colvarPostalCode); TableSchema.TableColumn colvarCountry = new TableSchema.TableColumn(schema); colvarCountry.ColumnName = "Country"; colvarCountry.DataType = DbType.String; colvarCountry.MaxLength = 15; colvarCountry.AutoIncrement = false; colvarCountry.IsNullable = true; colvarCountry.IsPrimaryKey = false; colvarCountry.IsForeignKey = false; colvarCountry.IsReadOnly = false; schema.Columns.Add(colvarCountry); TableSchema.TableColumn colvarSalesperson = new TableSchema.TableColumn(schema); colvarSalesperson.ColumnName = "Salesperson"; colvarSalesperson.DataType = DbType.Decimal; colvarSalesperson.MaxLength = 0; colvarSalesperson.AutoIncrement = false; colvarSalesperson.IsNullable = false; colvarSalesperson.IsPrimaryKey = false; colvarSalesperson.IsForeignKey = false; colvarSalesperson.IsReadOnly = false; schema.Columns.Add(colvarSalesperson); TableSchema.TableColumn colvarOrderID = new TableSchema.TableColumn(schema); colvarOrderID.ColumnName = "OrderID"; colvarOrderID.DataType = DbType.Int32; colvarOrderID.MaxLength = 10; colvarOrderID.AutoIncrement = false; colvarOrderID.IsNullable = false; colvarOrderID.IsPrimaryKey = false; colvarOrderID.IsForeignKey = false; colvarOrderID.IsReadOnly = false; schema.Columns.Add(colvarOrderID); TableSchema.TableColumn colvarOrderDate = new TableSchema.TableColumn(schema); colvarOrderDate.ColumnName = "OrderDate"; colvarOrderDate.DataType = DbType.DateTime; colvarOrderDate.MaxLength = 0; colvarOrderDate.AutoIncrement = false; colvarOrderDate.IsNullable = true; colvarOrderDate.IsPrimaryKey = false; colvarOrderDate.IsForeignKey = false; colvarOrderDate.IsReadOnly = false; schema.Columns.Add(colvarOrderDate); TableSchema.TableColumn colvarRequiredDate = new TableSchema.TableColumn(schema); colvarRequiredDate.ColumnName = "RequiredDate"; colvarRequiredDate.DataType = DbType.DateTime; colvarRequiredDate.MaxLength = 0; colvarRequiredDate.AutoIncrement = false; colvarRequiredDate.IsNullable = true; colvarRequiredDate.IsPrimaryKey = false; colvarRequiredDate.IsForeignKey = false; colvarRequiredDate.IsReadOnly = false; schema.Columns.Add(colvarRequiredDate); TableSchema.TableColumn colvarShippedDate = new TableSchema.TableColumn(schema); colvarShippedDate.ColumnName = "ShippedDate"; colvarShippedDate.DataType = DbType.DateTime; colvarShippedDate.MaxLength = 0; colvarShippedDate.AutoIncrement = false; colvarShippedDate.IsNullable = true; colvarShippedDate.IsPrimaryKey = false; colvarShippedDate.IsForeignKey = false; colvarShippedDate.IsReadOnly = false; schema.Columns.Add(colvarShippedDate); TableSchema.TableColumn colvarShipperName = new TableSchema.TableColumn(schema); colvarShipperName.ColumnName = "ShipperName"; colvarShipperName.DataType = DbType.String; colvarShipperName.MaxLength = 40; colvarShipperName.AutoIncrement = false; colvarShipperName.IsNullable = false; colvarShipperName.IsPrimaryKey = false; colvarShipperName.IsForeignKey = false; colvarShipperName.IsReadOnly = false; schema.Columns.Add(colvarShipperName); TableSchema.TableColumn colvarProductID = new TableSchema.TableColumn(schema); colvarProductID.ColumnName = "ProductID"; colvarProductID.DataType = DbType.Int32; colvarProductID.MaxLength = 10; colvarProductID.AutoIncrement = false; colvarProductID.IsNullable = false; colvarProductID.IsPrimaryKey = false; colvarProductID.IsForeignKey = false; colvarProductID.IsReadOnly = false; schema.Columns.Add(colvarProductID); TableSchema.TableColumn colvarProductName = new TableSchema.TableColumn(schema); colvarProductName.ColumnName = "ProductName"; colvarProductName.DataType = DbType.String; colvarProductName.MaxLength = 40; colvarProductName.AutoIncrement = false; colvarProductName.IsNullable = false; colvarProductName.IsPrimaryKey = false; colvarProductName.IsForeignKey = false; colvarProductName.IsReadOnly = false; schema.Columns.Add(colvarProductName); TableSchema.TableColumn colvarUnitPrice = new TableSchema.TableColumn(schema); colvarUnitPrice.ColumnName = "UnitPrice"; colvarUnitPrice.DataType = DbType.Decimal; colvarUnitPrice.MaxLength = 0; colvarUnitPrice.AutoIncrement = false; colvarUnitPrice.IsNullable = false; colvarUnitPrice.IsPrimaryKey = false; colvarUnitPrice.IsForeignKey = false; colvarUnitPrice.IsReadOnly = false; schema.Columns.Add(colvarUnitPrice); TableSchema.TableColumn colvarQuantity = new TableSchema.TableColumn(schema); colvarQuantity.ColumnName = "Quantity"; colvarQuantity.DataType = DbType.Int16; colvarQuantity.MaxLength = 5; colvarQuantity.AutoIncrement = false; colvarQuantity.IsNullable = false; colvarQuantity.IsPrimaryKey = false; colvarQuantity.IsForeignKey = false; colvarQuantity.IsReadOnly = false; schema.Columns.Add(colvarQuantity); TableSchema.TableColumn colvarDiscount = new TableSchema.TableColumn(schema); colvarDiscount.ColumnName = "Discount"; colvarDiscount.DataType = DbType.Decimal; colvarDiscount.MaxLength = 0; colvarDiscount.AutoIncrement = false; colvarDiscount.IsNullable = false; colvarDiscount.IsPrimaryKey = false; colvarDiscount.IsForeignKey = false; colvarDiscount.IsReadOnly = false; schema.Columns.Add(colvarDiscount); TableSchema.TableColumn colvarExtendedPrice = new TableSchema.TableColumn(schema); colvarExtendedPrice.ColumnName = "ExtendedPrice"; colvarExtendedPrice.DataType = DbType.Decimal; colvarExtendedPrice.MaxLength = 0; colvarExtendedPrice.AutoIncrement = false; colvarExtendedPrice.IsNullable = true; colvarExtendedPrice.IsPrimaryKey = false; colvarExtendedPrice.IsForeignKey = false; colvarExtendedPrice.IsReadOnly = false; schema.Columns.Add(colvarExtendedPrice); TableSchema.TableColumn colvarFreight = new TableSchema.TableColumn(schema); colvarFreight.ColumnName = "Freight"; colvarFreight.DataType = DbType.Decimal; colvarFreight.MaxLength = 0; colvarFreight.AutoIncrement = false; colvarFreight.IsNullable = true; colvarFreight.IsPrimaryKey = false; colvarFreight.IsForeignKey = false; colvarFreight.IsReadOnly = false; schema.Columns.Add(colvarFreight); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["Southwind"].AddSchema("invoices",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public Invoice() { SetSQLProps(); SetDefaults(); MarkNew(); } public Invoice(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public Invoice(object keyID) { SetSQLProps(); LoadByKey(keyID); } public Invoice(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("ShipName")] [Bindable(true)] public string ShipName { get { return GetColumnValue<string>("ShipName"); } set { SetColumnValue("ShipName", value); } } [XmlAttribute("ShipAddress")] [Bindable(true)] public string ShipAddress { get { return GetColumnValue<string>("ShipAddress"); } set { SetColumnValue("ShipAddress", value); } } [XmlAttribute("ShipCity")] [Bindable(true)] public string ShipCity { get { return GetColumnValue<string>("ShipCity"); } set { SetColumnValue("ShipCity", value); } } [XmlAttribute("ShipRegion")] [Bindable(true)] public string ShipRegion { get { return GetColumnValue<string>("ShipRegion"); } set { SetColumnValue("ShipRegion", value); } } [XmlAttribute("ShipPostalCode")] [Bindable(true)] public string ShipPostalCode { get { return GetColumnValue<string>("ShipPostalCode"); } set { SetColumnValue("ShipPostalCode", value); } } [XmlAttribute("ShipCountry")] [Bindable(true)] public string ShipCountry { get { return GetColumnValue<string>("ShipCountry"); } set { SetColumnValue("ShipCountry", value); } } [XmlAttribute("CustomerID")] [Bindable(true)] public string CustomerID { get { return GetColumnValue<string>("CustomerID"); } set { SetColumnValue("CustomerID", value); } } [XmlAttribute("CustomerName")] [Bindable(true)] public string CustomerName { get { return GetColumnValue<string>("CustomerName"); } set { SetColumnValue("CustomerName", value); } } [XmlAttribute("Address")] [Bindable(true)] public string Address { get { return GetColumnValue<string>("Address"); } set { SetColumnValue("Address", value); } } [XmlAttribute("City")] [Bindable(true)] public string City { get { return GetColumnValue<string>("City"); } set { SetColumnValue("City", value); } } [XmlAttribute("Region")] [Bindable(true)] public string Region { get { return GetColumnValue<string>("Region"); } set { SetColumnValue("Region", value); } } [XmlAttribute("PostalCode")] [Bindable(true)] public string PostalCode { get { return GetColumnValue<string>("PostalCode"); } set { SetColumnValue("PostalCode", value); } } [XmlAttribute("Country")] [Bindable(true)] public string Country { get { return GetColumnValue<string>("Country"); } set { SetColumnValue("Country", value); } } [XmlAttribute("Salesperson")] [Bindable(true)] public decimal Salesperson { get { return GetColumnValue<decimal>("Salesperson"); } set { SetColumnValue("Salesperson", value); } } [XmlAttribute("OrderID")] [Bindable(true)] public int OrderID { get { return GetColumnValue<int>("OrderID"); } set { SetColumnValue("OrderID", value); } } [XmlAttribute("OrderDate")] [Bindable(true)] public DateTime? OrderDate { get { return GetColumnValue<DateTime?>("OrderDate"); } set { SetColumnValue("OrderDate", value); } } [XmlAttribute("RequiredDate")] [Bindable(true)] public DateTime? RequiredDate { get { return GetColumnValue<DateTime?>("RequiredDate"); } set { SetColumnValue("RequiredDate", value); } } [XmlAttribute("ShippedDate")] [Bindable(true)] public DateTime? ShippedDate { get { return GetColumnValue<DateTime?>("ShippedDate"); } set { SetColumnValue("ShippedDate", value); } } [XmlAttribute("ShipperName")] [Bindable(true)] public string ShipperName { get { return GetColumnValue<string>("ShipperName"); } set { SetColumnValue("ShipperName", value); } } [XmlAttribute("ProductID")] [Bindable(true)] public int ProductID { get { return GetColumnValue<int>("ProductID"); } set { SetColumnValue("ProductID", value); } } [XmlAttribute("ProductName")] [Bindable(true)] public string ProductName { get { return GetColumnValue<string>("ProductName"); } set { SetColumnValue("ProductName", value); } } [XmlAttribute("UnitPrice")] [Bindable(true)] public decimal UnitPrice { get { return GetColumnValue<decimal>("UnitPrice"); } set { SetColumnValue("UnitPrice", value); } } [XmlAttribute("Quantity")] [Bindable(true)] public short Quantity { get { return GetColumnValue<short>("Quantity"); } set { SetColumnValue("Quantity", value); } } [XmlAttribute("Discount")] [Bindable(true)] public decimal Discount { get { return GetColumnValue<decimal>("Discount"); } set { SetColumnValue("Discount", value); } } [XmlAttribute("ExtendedPrice")] [Bindable(true)] public decimal? ExtendedPrice { get { return GetColumnValue<decimal?>("ExtendedPrice"); } set { SetColumnValue("ExtendedPrice", value); } } [XmlAttribute("Freight")] [Bindable(true)] public decimal? Freight { get { return GetColumnValue<decimal?>("Freight"); } set { SetColumnValue("Freight", value); } } #endregion #region Columns Struct public struct Columns { public static string ShipName = @"ShipName"; public static string ShipAddress = @"ShipAddress"; public static string ShipCity = @"ShipCity"; public static string ShipRegion = @"ShipRegion"; public static string ShipPostalCode = @"ShipPostalCode"; public static string ShipCountry = @"ShipCountry"; public static string CustomerID = @"CustomerID"; public static string CustomerName = @"CustomerName"; public static string Address = @"Address"; public static string City = @"City"; public static string Region = @"Region"; public static string PostalCode = @"PostalCode"; public static string Country = @"Country"; public static string Salesperson = @"Salesperson"; public static string OrderID = @"OrderID"; public static string OrderDate = @"OrderDate"; public static string RequiredDate = @"RequiredDate"; public static string ShippedDate = @"ShippedDate"; public static string ShipperName = @"ShipperName"; public static string ProductID = @"ProductID"; public static string ProductName = @"ProductName"; public static string UnitPrice = @"UnitPrice"; public static string Quantity = @"Quantity"; public static string Discount = @"Discount"; public static string ExtendedPrice = @"ExtendedPrice"; public static string Freight = @"Freight"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
// <copyright file="SelectElement.cs" company="WebDriver Committers"> // Copyright 2007-2011 WebDriver committers // Copyright 2007-2011 Google Inc. // Portions copyright 2007 ThoughtWorks, Inc // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Globalization; namespace OpenQA.Selenium.Support.UI { /// <summary> /// Provides a convenience method for manipulating selections of options in an HTML select element. /// </summary> public class SelectElement { private readonly IWebElement element; /// <summary> /// Initializes a new instance of the SelectElement class. /// </summary> /// <param name="element">The element to be wrapped</param> public SelectElement(IWebElement element) { if (element == null) { throw new ArgumentNullException("element", "element cannot be null"); } if (string.IsNullOrEmpty(element.TagName) || string.Compare(element.TagName, "select", StringComparison.OrdinalIgnoreCase) != 0) { throw new UnexpectedTagNameException("select", element.TagName); } this.element = element; // let check if it's a multiple string attribute = element.GetAttribute("multiple"); this.IsMultiple = attribute != null; } /// <summary> /// Gets a value indicating whether the parent element supports multiple selections. /// </summary> public bool IsMultiple { get; private set; } /// <summary> /// Gets the list of options for the select element. /// </summary> public IList<IWebElement> Options { get { return this.element.FindElements(By.TagName("option")); } } /// <summary> /// Gets the selected item within the select element. Returns <see langword="null"/> if no option is selected. /// </summary> /// <remarks>If more than one item is selected this will return the first item.</remarks> public IWebElement SelectedOption { get { foreach (IWebElement option in this.Options) { if (option.Selected) { return option; } } return null; } } /// <summary> /// Gets all of the selected options within the select element. /// </summary> public IList<IWebElement> AllSelectedOptions { get { List<IWebElement> returnValue = new List<IWebElement>(); foreach (IWebElement option in this.Options) { if (option.Selected) { returnValue.Add(option); } } return returnValue; } } /// <summary> /// Select the option by the text displayed. /// </summary> /// <param name="text">The text of the option to be selected.</param> public void SelectByText(string text) { foreach (IWebElement option in this.Options) { if (option.Text == text) { option.Click(); if (!this.IsMultiple) { return; } } } } /// <summary> /// Select an option by the value. /// </summary> /// <param name="value">The value of the option to be selected.</param> public void SelectByValue(string value) { foreach (IWebElement option in this.Options) { if (option.GetAttribute("value") == value) { option.Click(); if (!this.IsMultiple) { return; } } } } /// <summary> /// Select the option by the index. /// </summary> /// <param name="index">The index of the option to be selected.</param> public void SelectByIndex(int index) { foreach (IWebElement option in this.Options) { if (option.GetAttribute("index").Equals(index.ToString(CultureInfo.InvariantCulture))) { option.Click(); if (!this.IsMultiple) { return; } } } } /// <summary> /// Deselect the option by the text displayed. /// </summary> /// <param name="text">The text of the option to be deselected.</param> public void DeselectByText(string text) { foreach (IWebElement option in this.Options) { if (option.Text.Equals(text)) { if (option.Selected) { option.Click(); } if (!this.IsMultiple) { return; } } } } /// <summary> /// Deselect the option by the value. /// </summary> /// <param name="value">The value of the option to deselect.</param> public void DeselectByValue(string value) { foreach (IWebElement option in this.Options) { if (option.GetAttribute("value").Equals(value)) { if (option.Selected) { option.Click(); } if (!this.IsMultiple) { return; } } } } /// <summary> /// Deselect the option by the index. /// </summary> /// <param name="index">The index of the option to deselect.</param> public void DeselectByIndex(int index) { foreach (IWebElement option in this.Options) { if (option.GetAttribute("index").Equals(index.ToString(CultureInfo.InvariantCulture))) { if (option.Selected) { option.Click(); } if (!this.IsMultiple) { return; } } } } /// <summary> /// Clear all selected entries. This is only valid when the SELECT supports multiple selections. /// </summary> public void DeselectAll() { if (!this.IsMultiple) { throw new WebDriverException("You may only deselect all options if multi-select is supported"); } foreach (IWebElement webElement in this.Options) { if (webElement.Selected) { webElement.Click(); } } } } }
using System; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using log4net; using NetGore.IO; namespace NetGore.Content { /// <summary> /// An immutable string that represents the name, or virtual path, to a content asset. /// </summary> [TypeConverter(typeof(ContentAssetNameConverter))] public class ContentAssetName : IEquatable<ContentAssetName>, IComparable<ContentAssetName> { static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The string used to separate the directories. /// </summary> public const string PathSeparator = "/"; readonly string _assetName; /// <summary> /// Initializes a new instance of the <see cref="ContentAssetName"/> class. /// </summary> /// <param name="assetName">Name of the asset.</param> public ContentAssetName(string assetName) { _assetName = Sanitize(assetName); } /// <summary> /// Gets the complete name of the asset. This differs from <see cref="ToString"/> as this will always /// be the complete name of the asset, while <see cref="ToString"/> may only be a partial path in /// derived classes. /// </summary> public string Value { get { return _assetName; } } /// <summary> /// Checks if the content with the given name exists. /// </summary> /// <returns>True if the content exists in the build; otherwise false.</returns> public bool ContentExists() { var filePath = ContentPaths.Build.Root.Join(GetFileName()); return File.Exists(filePath); } /// <summary> /// Checks if this object is equal to another object. /// </summary> /// <param name="obj">The other object.</param> /// <returns>True if the two are equal; otherwise false.</returns> public override bool Equals(object obj) { return obj is ContentAssetName && this == (ContentAssetName)obj; } /// <summary> /// Creates a <see cref="ContentAssetName"/> from an absolute file path. /// </summary> /// <param name="filePath">The absolute file path to the asset.</param> /// <param name="contentRoot">The root path to the content directory.</param> /// <returns>The <see cref="ContentAssetName"/> from the <paramref name="filePath"/>.</returns> public static ContentAssetName FromAbsoluteFilePath(string filePath, string contentRoot) { var start = contentRoot.Length; if (!contentRoot.EndsWith("/") && !contentRoot.EndsWith("\\") && !contentRoot.EndsWith(Path.DirectorySeparatorChar.ToString())) ++start; var len = filePath.Length - start; if (ContentPaths.ContentFileSuffix.Length > 0 && filePath.EndsWith(ContentPaths.ContentFileSuffix, StringComparison.OrdinalIgnoreCase)) len -= ContentPaths.ContentFileSuffix.Length; var substr = filePath.Substring(start, len); return new ContentAssetName(substr); } /// <summary> /// Gets the absolute file path for the content asset. /// </summary> /// <param name="rootPath">The root content path.</param> /// <returns>The absolute file path for the content asset.</returns> /// <exception cref="ArgumentException">Either zero or more than one files matching this <see cref="ContentAssetName"/> /// were found in the <paramref name="rootPath"/>.</exception> public string GetAbsoluteFilePath(ContentPaths rootPath) { var sb = new StringBuilder(); // Get the root path string rootPathStr = rootPath.Root.ToString(); sb.Append(rootPathStr); // Get the relative file path string relFilePathStr = GetFileName(); // Get all of the files in the directory that this file lives in string dirPath = Path.GetDirectoryName(Path.Combine(rootPathStr, relFilePathStr)); string[] dirFiles = Directory.GetFiles(dirPath, "*.*", SearchOption.TopDirectoryOnly); // Take all the files in the directory, filter out the markup and suffix, and find which file names match ours string targetFileName = Path.GetFileName(relFilePathStr); targetFileName = RemoveFileTagsFromFileName(targetFileName); string[] contentFilePaths = dirFiles.Where(x => { string xFileName = Path.GetFileNameWithoutExtension(x); xFileName = RemoveFileTagsFromFileName(xFileName); return StringComparer.OrdinalIgnoreCase.Equals(xFileName, targetFileName); }) .ToArray(); // Verify we found exactly 1 match if (contentFilePaths.Length == 0) { throw new ArgumentException(string.Format( "Could not find a file named (without the [] markup and suffix) `{0}` in path `{1}`.", targetFileName, dirPath)); } if (contentFilePaths.Length > 1) { throw new ArgumentException(string.Format( "Found multiple potential matches for the file named (without the [] markup and suffix) `{0}` in path `{1}`. Was expecting just one.", targetFileName, dirPath)); } return contentFilePaths[0]; } /// <summary> /// Removes the file tags from a file name. /// </summary> /// <param name="fileName">The file name only (no directories, no suffix).</param> static string RemoveFileTagsFromFileName(string fileName) { int splitIndex = fileName.IndexOf('['); if (splitIndex > 0) fileName = fileName.Substring(0, splitIndex); return fileName; } /// <summary> /// Gets the relative file path and name for the content asset. This must still be prefixed by a path created /// with the <see cref="ContentPaths"/> to generate an absolute path. /// </summary> /// <returns>The relative file path and name for the content asset..</returns> public string GetFileName() { return _assetName + ContentPaths.ContentFileSuffix; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures /// like a hash table. </returns> public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(Value); } /// <summary> /// Recycles the actual content file. The file located in the <see cref="ContentPaths.Dev"/> path (if exists) will be moved /// to the <see cref="ContentPaths.Recycled"/>. Other instances of the file will just be deleted from the system. /// </summary> public void RecycleFile() { if (log.IsInfoEnabled) log.InfoFormat("Recycling `{0}`.", this); // Delete file in build path var buildPath = GetAbsoluteFilePath(ContentPaths.Build); TryDeleteFile(buildPath); // Check for recycle folder var recycled = ContentPaths.Recycled; if (recycled == null) { const string errmsg = "Cannot recycle `{0}` - ContentPaths.Recycled returned null."; if (log.IsWarnEnabled) log.WarnFormat(errmsg, this); Debug.Fail(string.Format(errmsg, this)); return; } // Copy from dev to recycling, then delete from dev var srcPath = GetAbsoluteFilePath(ContentPaths.Dev); if (File.Exists(srcPath)) { // Get the relative file path by taking the source path and chopping off the ContentPath's root directory prefix var relPath = srcPath.Substring(ContentPaths.Dev.Root.ToString().Length); // Get the destination path by joining the relative path with the recycled path var destPath = ContentPaths.Recycled.Join(relPath); // Create directory if it doesn't already exist var destPathDir = Path.GetDirectoryName(destPath); if (destPathDir != null && !Directory.Exists(destPathDir)) Directory.CreateDirectory(destPathDir); // Copy file File.Copy(srcPath, destPath, true); // Ensure the file was copied over before deleting if (File.Exists(destPath)) { TryDeleteFile(srcPath); } else { // Failed to copy over? const string errmsg = "File.Copy() from `{0}` to `{1}` seems to have failed - File.Exists() returned false."; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, srcPath, destPath); Debug.Fail(string.Format(errmsg, srcPath, destPath)); } } } /// <summary> /// Sanitizes the asset name. This will fix aspects of the asset name that can be fixed without /// making too large of assumptions. /// </summary> /// <param name="assetName">The asset name.</param> /// <returns>The sanitized asset name.</returns> public static string Sanitize(string assetName) { var suffixLen = ContentPaths.ContentFileSuffix.Length; // Replace \\ with the proper character assetName = assetName.Replace("\\", PathSeparator); // Remove any prefixed or suffixed path separators if (assetName.StartsWith(PathSeparator)) assetName = assetName.Substring(1); if (assetName.EndsWith(PathSeparator)) assetName = assetName.Substring(0, assetName.Length - 1); if (assetName.Length > suffixLen && (ContentPaths.ContentFileSuffix.Length == 0 || assetName.EndsWith(ContentPaths.ContentFileSuffix, StringComparison.OrdinalIgnoreCase))) assetName = assetName.Substring(0, assetName.Length - suffixLen); return assetName; } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns>A <see cref="System.String"/> that represents this instance.</returns> public override string ToString() { return _assetName; } /// <summary> /// Attempts to delete a file. No exceptions are ever thrown. /// </summary> /// <param name="filePath">The path to the file to delete.</param> /// <returns>True if the file at the <paramref name="filePath"/> was deleted; otherwise false.</returns> static bool TryDeleteFile(string filePath) { try { if (!File.Exists(filePath)) return false; File.Delete(filePath); return true; } catch (Exception ex) { const string errmsg = "Failed to delete file at `{0}`. Exception: {1}"; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, filePath, ex); return false; } } #region IComparable<ContentAssetName> Members /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>. /// </returns> /// <param name="other">An object to compare with this object.</param> public int CompareTo(ContentAssetName other) { return StringComparer.OrdinalIgnoreCase.Compare(Value, other.Value); } #endregion #region IEquatable<ContentAssetName> Members /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> /// <param name="other">An object to compare with this object.</param> public bool Equals(ContentAssetName other) { return Value.Equals(other.Value, StringComparison.OrdinalIgnoreCase); } #endregion /// <summary> /// Implements the operator ==. /// </summary> /// <param name="a">A.</param> /// <param name="b">The b.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(ContentAssetName a, ContentAssetName b) { if (ReferenceEquals(a, null) || ReferenceEquals(b, null)) return ReferenceEquals(a, b); return a.Equals(b); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="a">A.</param> /// <param name="b">The b.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(ContentAssetName a, ContentAssetName b) { return !(a == b); } /// <summary> /// Performs an implicit conversion from <see cref="System.String"/> to <see cref="ContentAssetName"/>. /// </summary> /// <param name="assetName">The asset name.</param> /// <returns>The result of the conversion.</returns> public static implicit operator ContentAssetName(string assetName) { return new ContentAssetName(assetName); } } }
using System; using UnityEngine; namespace RuntimeGizmos { //Currently doesnt really handle TransformType.All public class TransformGizmoCustomGizmo : MonoBehaviour { public bool autoFindTransformGizmo = true; public TransformGizmo transformGizmo; public CustomTransformGizmos customTranslationGizmos = new CustomTransformGizmos(); public CustomTransformGizmos customRotationGizmos = new CustomTransformGizmos(); public CustomTransformGizmos customScaleGizmos = new CustomTransformGizmos(); public bool scaleBasedOnDistance = true; public float scaleMultiplier = .4f; public int gizmoLayer = 2; //2 is the ignoreRaycast layer. Set to whatever you want. LayerMask mask; void Awake() { if(transformGizmo == null && autoFindTransformGizmo) { transformGizmo = GameObject.FindObjectOfType<TransformGizmo>(); } transformGizmo.manuallyHandleGizmo = true; //Since we are using a mesh, rotating can get weird due to how the rotation method works, //so we use a different rotation method that will let us rotate by acting like our custom rotation gizmo is a wheel. //Can still give weird results depending on camera angle, but I think its more understanding for the user as to why its messing up. transformGizmo.circularRotationMethod = true; mask = LayerMask.GetMask(LayerMask.LayerToName(gizmoLayer)); customTranslationGizmos.Init(gizmoLayer); customRotationGizmos.Init(gizmoLayer); customScaleGizmos.Init(gizmoLayer); } void OnEnable() { transformGizmo.onCheckForSelectedAxis += CheckForSelectedAxis; transformGizmo.onDrawCustomGizmo += OnDrawCustomGizmos; } void OnDisable() { transformGizmo.onCheckForSelectedAxis -= CheckForSelectedAxis; transformGizmo.onDrawCustomGizmo -= OnDrawCustomGizmos; } void CheckForSelectedAxis() { ShowProperGizmoType(); if(Input.GetMouseButtonDown(0)) { RaycastHit hitInfo; if(Physics.Raycast(transformGizmo.myCamera.ScreenPointToRay(Input.mousePosition), out hitInfo, Mathf.Infinity, mask)) { Axis selectedAxis = Axis.None; TransformType type = transformGizmo.transformType; if(selectedAxis == Axis.None && transformGizmo.TransformTypeContains(TransformType.Move)) { selectedAxis = customTranslationGizmos.GetSelectedAxis(hitInfo.collider); type = TransformType.Move; } if(selectedAxis == Axis.None && transformGizmo.TransformTypeContains(TransformType.Rotate)) { selectedAxis = customRotationGizmos.GetSelectedAxis(hitInfo.collider); type = TransformType.Rotate; } if(selectedAxis == Axis.None && transformGizmo.TransformTypeContains(TransformType.Scale)) { selectedAxis = customScaleGizmos.GetSelectedAxis(hitInfo.collider); type = TransformType.Scale; } transformGizmo.SetTranslatingAxis(type, selectedAxis); } } } void OnDrawCustomGizmos() { if(transformGizmo.TranslatingTypeContains(TransformType.Move)) DrawCustomGizmo(customTranslationGizmos); if(transformGizmo.TranslatingTypeContains(TransformType.Rotate)) DrawCustomGizmo(customRotationGizmos); if(transformGizmo.TranslatingTypeContains(TransformType.Scale)) DrawCustomGizmo(customScaleGizmos); } void DrawCustomGizmo(CustomTransformGizmos customGizmo) { AxisInfo axisInfo = transformGizmo.GetAxisInfo(); customGizmo.SetAxis(axisInfo); customGizmo.SetPosition(transformGizmo.pivotPoint); Vector4 totalScaleMultiplier = Vector4.one; if(scaleBasedOnDistance) { totalScaleMultiplier.w *= (scaleMultiplier * transformGizmo.GetDistanceMultiplier()); } if(transformGizmo.transformingType == TransformType.Scale) { float totalScaleAmount = 1f + transformGizmo.totalScaleAmount; if(transformGizmo.translatingAxis == Axis.Any) totalScaleMultiplier += (Vector4.one * totalScaleAmount); else if(transformGizmo.translatingAxis == Axis.X) totalScaleMultiplier.x *= totalScaleAmount; else if(transformGizmo.translatingAxis == Axis.Y) totalScaleMultiplier.y *= totalScaleAmount; else if(transformGizmo.translatingAxis == Axis.Z) totalScaleMultiplier.z *= totalScaleAmount; } customGizmo.ScaleMultiply(totalScaleMultiplier); } void ShowProperGizmoType() { bool hasSelection = transformGizmo.mainTargetRoot != null; customTranslationGizmos.SetEnable(hasSelection && transformGizmo.TranslatingTypeContains(TransformType.Move)); customRotationGizmos.SetEnable(hasSelection && transformGizmo.TranslatingTypeContains(TransformType.Rotate)); customScaleGizmos.SetEnable(hasSelection && transformGizmo.TranslatingTypeContains(TransformType.Scale)); } } [Serializable] public class CustomTransformGizmos { public Transform xAxisGizmo; public Transform yAxisGizmo; public Transform zAxisGizmo; public Transform anyAxisGizmo; Collider xAxisGizmoCollider; Collider yAxisGizmoCollider; Collider zAxisGizmoCollider; Collider anyAxisGizmoCollider; Vector3 originalXAxisScale; Vector3 originalYAxisScale; Vector3 originalZAxisScale; Vector3 originalAnyAxisScale; public void Init(int layer) { if(xAxisGizmo != null) { SetLayerRecursively(xAxisGizmo.gameObject, layer); xAxisGizmoCollider = xAxisGizmo.GetComponentInChildren<Collider>(); originalXAxisScale = xAxisGizmo.localScale; } if(yAxisGizmo != null) { SetLayerRecursively(yAxisGizmo.gameObject, layer); yAxisGizmoCollider = yAxisGizmo.GetComponentInChildren<Collider>(); originalYAxisScale = yAxisGizmo.localScale; } if(zAxisGizmo != null) { SetLayerRecursively(zAxisGizmo.gameObject, layer); zAxisGizmoCollider = zAxisGizmo.GetComponentInChildren<Collider>(); originalZAxisScale = zAxisGizmo.localScale; } if(anyAxisGizmo != null) { SetLayerRecursively(anyAxisGizmo.gameObject, layer); anyAxisGizmoCollider = anyAxisGizmo.GetComponentInChildren<Collider>(); originalAnyAxisScale = anyAxisGizmo.localScale; } } public void SetEnable(bool enable) { if(xAxisGizmo != null && xAxisGizmo.gameObject.activeSelf != enable) xAxisGizmo.gameObject.SetActive(enable); if(yAxisGizmo != null && yAxisGizmo.gameObject.activeSelf != enable) yAxisGizmo.gameObject.SetActive(enable); if(zAxisGizmo != null && zAxisGizmo.gameObject.activeSelf != enable) zAxisGizmo.gameObject.SetActive(enable); if(anyAxisGizmo != null && anyAxisGizmo.gameObject.activeSelf != enable) anyAxisGizmo.gameObject.SetActive(enable); } public void SetAxis(AxisInfo axisInfo) { Quaternion lookRotation = Quaternion.LookRotation(axisInfo.zDirection, axisInfo.yDirection); if(xAxisGizmo != null) xAxisGizmo.rotation = lookRotation; if(yAxisGizmo != null) yAxisGizmo.rotation = lookRotation; if(zAxisGizmo != null) zAxisGizmo.rotation = lookRotation; if(anyAxisGizmo != null) anyAxisGizmo.rotation = lookRotation; } public void SetPosition(Vector3 position) { if(xAxisGizmo != null) xAxisGizmo.position = position; if(yAxisGizmo != null) yAxisGizmo.position = position; if(zAxisGizmo != null) zAxisGizmo.position = position; if(anyAxisGizmo != null) anyAxisGizmo.position = position; } public void ScaleMultiply(Vector4 scaleMultiplier) { if(xAxisGizmo != null) xAxisGizmo.localScale = Vector3.Scale(originalXAxisScale, new Vector3(scaleMultiplier.w + scaleMultiplier.x, scaleMultiplier.w, scaleMultiplier.w)); if(yAxisGizmo != null) yAxisGizmo.localScale = Vector3.Scale(originalYAxisScale, new Vector3(scaleMultiplier.w, scaleMultiplier.w + scaleMultiplier.y, scaleMultiplier.w)); if(zAxisGizmo != null) zAxisGizmo.localScale = Vector3.Scale(originalZAxisScale, new Vector3(scaleMultiplier.w, scaleMultiplier.w, scaleMultiplier.w + scaleMultiplier.z)); if(anyAxisGizmo != null) anyAxisGizmo.localScale = originalAnyAxisScale * scaleMultiplier.w; } public Axis GetSelectedAxis(Collider selectedCollider) { if(xAxisGizmoCollider != null && xAxisGizmoCollider == selectedCollider) return Axis.X; if(yAxisGizmoCollider != null && yAxisGizmoCollider == selectedCollider) return Axis.Y; if(zAxisGizmoCollider != null && zAxisGizmoCollider == selectedCollider) return Axis.Z; if(anyAxisGizmoCollider != null && anyAxisGizmoCollider == selectedCollider) return Axis.Any; return Axis.None; } void SetLayerRecursively(GameObject gameObject, int layer) { Transform[] selfAndChildren = gameObject.GetComponentsInChildren<Transform>(true); for(int i = 0; i < selfAndChildren.Length; i++) { selfAndChildren[i].gameObject.layer = layer; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Datastream { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Data streamer batch. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] internal class DataStreamerBatch<TK, TV> { /** Queue. */ private readonly ConcurrentQueue<object> _queue = new ConcurrentQueue<object>(); /** Lock for concurrency. */ private readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim(); /** Previous batch. */ private volatile DataStreamerBatch<TK, TV> _prev; /** Current queue size.*/ private volatile int _size; /** Send guard. */ private bool _sndGuard; /** */ private readonly Future<object> _fut = new Future<object>(); /// <summary> /// Constructor. /// </summary> public DataStreamerBatch() : this(null) { // No-op. } /// <summary> /// Constructor. /// </summary> /// <param name="prev">Previous batch.</param> public DataStreamerBatch(DataStreamerBatch<TK, TV> prev) { _prev = prev; if (prev != null) Thread.MemoryBarrier(); // Prevent "prev" field escape. _fut.Task.ContWith(x => ParentsCompleted()); } /// <summary> /// Gets the task. /// </summary> public Task Task { get { return _fut.Task; } } /// <summary> /// Add object to the batch. /// </summary> /// <param name="val">Value.</param> /// <param name="cnt">Items count.</param> /// <returns>Positive value in case batch is active, -1 in case no more additions are allowed.</returns> public int Add(object val, int cnt) { // If we cannot enter read-lock immediately, then send is scheduled and batch is definetely blocked. if (!_rwLock.TryEnterReadLock(0)) return -1; try { // 1. Ensure additions are possible if (_sndGuard) return -1; // 2. Add data and increase size. _queue.Enqueue(val); #pragma warning disable 0420 int newSize = Interlocked.Add(ref _size, cnt); #pragma warning restore 0420 return newSize; } finally { _rwLock.ExitReadLock(); } } /// <summary> /// Internal send routine. /// </summary> /// <param name="ldr">streamer.</param> /// <param name="plc">Policy.</param> public void Send(DataStreamerImpl<TK, TV> ldr, int plc) { // 1. Delegate to the previous batch first. DataStreamerBatch<TK, TV> prev0 = _prev; if (prev0 != null) prev0.Send(ldr, DataStreamerImpl<TK, TV>.PlcContinue); // 2. Set guard. _rwLock.EnterWriteLock(); try { if (_sndGuard) return; else _sndGuard = true; } finally { _rwLock.ExitWriteLock(); } var handleRegistry = ldr.Marshaller.Ignite.HandleRegistry; long futHnd = 0; // 3. Actual send. try { ldr.Update(writer => { writer.WriteInt(plc); if (plc != DataStreamerImpl<TK, TV>.PlcCancelClose) { futHnd = handleRegistry.Allocate(_fut); writer.WriteLong(futHnd); WriteTo(writer); } }); } catch (Exception) { if (futHnd != 0) { handleRegistry.Release(futHnd); } throw; } if (plc == DataStreamerImpl<TK, TV>.PlcCancelClose || _size == 0) { ThreadPool.QueueUserWorkItem(_ => _fut.OnNullResult()); handleRegistry.Release(futHnd); } } /// <summary> /// Gets the task to await completion of current and all previous loads. /// </summary> public Task GetThisAndPreviousCompletionTask() { var curBatch = this; var tasks = new List<Task>(); while (curBatch != null) { if (curBatch.Task.Status != TaskStatus.RanToCompletion) { tasks.Add(curBatch.Task); } curBatch = curBatch._prev; } return TaskRunner.WhenAll(tasks.ToArray()); } /// <summary> /// Write batch content. /// </summary> /// <param name="writer">Writer.</param> private void WriteTo(BinaryWriter writer) { writer.WriteInt(_size); object val; while (_queue.TryDequeue(out val)) { // 1. Is it a collection? ICollection<KeyValuePair<TK, TV>> entries = val as ICollection<KeyValuePair<TK, TV>>; if (entries != null) { foreach (KeyValuePair<TK, TV> item in entries) { writer.WriteObjectDetached(item.Key); writer.WriteObjectDetached(item.Value); } continue; } // 2. Is it a single entry? DataStreamerEntry<TK, TV> entry = val as DataStreamerEntry<TK, TV>; if (entry != null) { writer.WriteObjectDetached(entry.Key); writer.WriteObjectDetached(entry.Value); continue; } // 3. Is it remove merker? DataStreamerRemoveEntry<TK> rmvEntry = val as DataStreamerRemoveEntry<TK>; if (rmvEntry != null) { writer.WriteObjectDetached(rmvEntry.Key); writer.Write<object>(null); } } } /// <summary> /// Checck whether all previous batches are completed. /// </summary> /// <returns></returns> private bool ParentsCompleted() { DataStreamerBatch<TK, TV> prev0 = _prev; if (prev0 != null) { if (prev0.ParentsCompleted()) _prev = null; else return false; } return _fut.Task.IsCompleted; } } }
// Stubs for the namespace Microsoft.SqlServer.Management.Smo. Used for mocking in tests. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Security; using System.Runtime.InteropServices; namespace Microsoft.SqlServer.Management.Smo { #region Public Enums // TypeName: Microsoft.SqlServer.Management.Smo.LoginCreateOptions // Used by: // MSFT_xSQLServerLogin.Tests.ps1 public enum LoginCreateOptions { None = 0, IsHashed = 1, MustChange = 2 } // TypeName: Microsoft.SqlServer.Management.Smo.LoginType // BaseType: Microsoft.SqlServer.Management.Smo.ScriptNameObjectBase // Used by: // MSFT_xSQLServerLogin public enum LoginType { AsymmetricKey = 4, Certificate = 3, ExternalGroup = 6, ExternalUser = 5, SqlLogin = 2, WindowsGroup = 1, WindowsUser = 0, Unknown = -1 // Added for verification (mock) purposes, to verify that a login type is passed } // TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityReplicaFailoverMode // Used by: // MSFT_xSQLAOGroupEnsure.Tests public enum AvailabilityReplicaFailoverMode { Automatic, Manual, Unknown } // TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityReplicaAvailabilityMode // Used by: // MSFT_xSQLAOGroupEnsure.Tests public enum AvailabilityReplicaAvailabilityMode { AsynchronousCommit, SynchronousCommit, Unknown } // TypeName: Microsoft.SqlServer.Management.Smo.EndpointType // Used by: // xSQLServerEndpoint public enum EndpointType { DatabaseMirroring, ServiceBroker, Soap, TSql } // TypeName: Microsoft.SqlServer.Management.Smo.ProtocolType // Used by: // xSQLServerEndpoint public enum ProtocolType { Http, NamedPipes, SharedMemory, Tcp, Via } // TypeName: Microsoft.SqlServer.Management.Smo.ServerMirroringRole // Used by: // xSQLServerEndpoint public enum ServerMirroringRole { All, None, Partner, Witness } // TypeName: Microsoft.SqlServer.Management.Smo.EndpointEncryption // Used by: // xSQLServerEndpoint public enum EndpointEncryption { Disabled, Required, Supported } // TypeName: Microsoft.SqlServer.Management.Smo.EndpointEncryptionAlgorithm // Used by: // xSQLServerEndpoint public enum EndpointEncryptionAlgorithm { Aes, AesRC4, None, RC4, RC4Aes } #endregion Public Enums #region Public Classes public class Globals { // Static property that is switched on or off by tests if data should be mocked (true) or not (false). public static bool GenerateMockData = false; } // Typename: Microsoft.SqlServer.Management.Smo.ObjectPermissionSet // BaseType: Microsoft.SqlServer.Management.Smo.PermissionSetBase // Used by: // xSQLServerEndpointPermission.Tests.ps1 public class ObjectPermissionSet { public ObjectPermissionSet(){} public ObjectPermissionSet( bool connect ) { this.Connect = connect; } public bool Connect = false; } // TypeName: Microsoft.SqlServer.Management.Smo.ServerPermissionSet // BaseType: Microsoft.SqlServer.Management.Smo.PermissionSetBase // Used by: // xSQLServerPermission.Tests.ps1 public class ServerPermissionSet { public ServerPermissionSet(){} public ServerPermissionSet( bool alterAnyAvailabilityGroup, bool alterAnyEndpoint, bool connectSql, bool viewServerState ) { this.AlterAnyAvailabilityGroup = alterAnyAvailabilityGroup; this.AlterAnyEndpoint = alterAnyEndpoint; this.ConnectSql = connectSql; this.ViewServerState = viewServerState; } public bool AlterAnyAvailabilityGroup = false; public bool AlterAnyEndpoint = false; public bool ConnectSql = false; public bool ViewServerState = false; } // TypeName: Microsoft.SqlServer.Management.Smo.ServerPermissionInfo // BaseType: Microsoft.SqlServer.Management.Smo.PermissionInfo // Used by: // xSQLServerPermission.Tests.ps1 public class ServerPermissionInfo { public ServerPermissionInfo() { Microsoft.SqlServer.Management.Smo.ServerPermissionSet[] permissionSet = { new Microsoft.SqlServer.Management.Smo.ServerPermissionSet() }; this.PermissionType = permissionSet; } public ServerPermissionInfo( Microsoft.SqlServer.Management.Smo.ServerPermissionSet[] permissionSet ) { this.PermissionType = permissionSet; } public Microsoft.SqlServer.Management.Smo.ServerPermissionSet[] PermissionType; public string PermissionState = "Grant"; } // TypeName: Microsoft.SqlServer.Management.Smo.DatabasePermissionSet // BaseType: Microsoft.SqlServer.Management.Smo.PermissionSetBase // Used by: // xSQLServerDatabasePermission.Tests.ps1 public class DatabasePermissionSet { public DatabasePermissionSet(){} public DatabasePermissionSet( bool connect, bool update ) { this.Connect = connect; this.Update = update; } public bool Connect = false; public bool Update = false; } // TypeName: Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo // BaseType: Microsoft.SqlServer.Management.Smo.PermissionInfo // Used by: // xSQLServerDatabasePermission.Tests.ps1 public class DatabasePermissionInfo { public DatabasePermissionInfo() { Microsoft.SqlServer.Management.Smo.DatabasePermissionSet[] permissionSet = { new Microsoft.SqlServer.Management.Smo.DatabasePermissionSet() }; this.PermissionType = permissionSet; } public DatabasePermissionInfo( Microsoft.SqlServer.Management.Smo.DatabasePermissionSet[] permissionSet ) { this.PermissionType = permissionSet; } public Microsoft.SqlServer.Management.Smo.DatabasePermissionSet[] PermissionType; public string PermissionState = "Grant"; } // TypeName: Microsoft.SqlServer.Management.Smo.Server // BaseType: Microsoft.SqlServer.Management.Smo.SqlSmoObject // Used by: // xSQLServerPermission // MSFT_xSQLServerLogin public class Server { public string MockGranteeName; public AvailabilityGroupCollection AvailabilityGroups = new AvailabilityGroupCollection(); public ConnectionContext ConnectionContext; public string ComputerNamePhysicalNetBIOS; public DatabaseCollection Databases = new DatabaseCollection(); public string DisplayName; public string DomainInstanceName; public EndpointCollection Endpoints = new EndpointCollection(); public string FilestreamLevel = "Disabled"; public string InstanceName; public string ServiceName; public string DefaultFile; public string DefaultLog; public string BackupDirectory; public bool IsClustered = false; public bool IsHadrEnabled = false; public bool IsMemberOfWsfcCluster = false; public Hashtable Logins = new Hashtable(); public string Name; public string NetName; public Hashtable Roles = new Hashtable(); public Hashtable Version = new Hashtable(); public Server(){} public Server(string name) { this.Name = name; } public Server Clone() { return new Server() { MockGranteeName = this.MockGranteeName, AvailabilityGroups = this.AvailabilityGroups, ConnectionContext = this.ConnectionContext, ComputerNamePhysicalNetBIOS = this.ComputerNamePhysicalNetBIOS, Databases = this.Databases, DisplayName = this.DisplayName, DomainInstanceName = this.DomainInstanceName, Endpoints = this.Endpoints, FilestreamLevel = this.FilestreamLevel, InstanceName = this.InstanceName, IsClustered = this.IsClustered, IsHadrEnabled = this.IsHadrEnabled, Logins = this.Logins, Name = this.Name, NetName = this.NetName, Roles = this.Roles, ServiceName = this.ServiceName, Version = this.Version }; } public Microsoft.SqlServer.Management.Smo.ServerPermissionInfo[] EnumServerPermissions( string principal, Microsoft.SqlServer.Management.Smo.ServerPermissionSet permissionSetQuery ) { Microsoft.SqlServer.Management.Smo.ServerPermissionInfo[] permissionInfo = null; List<Microsoft.SqlServer.Management.Smo.ServerPermissionInfo> listOfServerPermissionInfo = null; if( Globals.GenerateMockData ) { listOfServerPermissionInfo = new List<Microsoft.SqlServer.Management.Smo.ServerPermissionInfo>(); Microsoft.SqlServer.Management.Smo.ServerPermissionSet[] permissionSet = { // AlterAnyEndpoint is set to false to test when permissions are missing. // AlterAnyAvailabilityGroup is set to true. new Microsoft.SqlServer.Management.Smo.ServerPermissionSet( true, false, false, false ), // ConnectSql is set to true. new Microsoft.SqlServer.Management.Smo.ServerPermissionSet( false, false, true, false ), // ViewServerState is set to true. new Microsoft.SqlServer.Management.Smo.ServerPermissionSet( false, false, false, true ) }; listOfServerPermissionInfo.Add( new Microsoft.SqlServer.Management.Smo.ServerPermissionInfo( permissionSet ) ); } if( listOfServerPermissionInfo != null ) { permissionInfo = listOfServerPermissionInfo.ToArray(); } return permissionInfo; } public void Grant( Microsoft.SqlServer.Management.Smo.ServerPermissionSet permission, string granteeName ) { if( granteeName != this.MockGranteeName ) { string errorMessage = "Expected to get granteeName == '" + this.MockGranteeName + "'. But got '" + granteeName + "'"; throw new System.ArgumentException(errorMessage, "granteeName"); } } public void Revoke( Microsoft.SqlServer.Management.Smo.ServerPermissionSet permission, string granteeName ) { if( granteeName != this.MockGranteeName ) { string errorMessage = "Expected to get granteeName == '" + this.MockGranteeName + "'. But got '" + granteeName + "'"; throw new System.ArgumentException(errorMessage, "granteeName"); } } } // TypeName: Microsoft.SqlServer.Management.Smo.Login // BaseType: Microsoft.SqlServer.Management.Smo.ScriptNameObjectBase // Used by: // MSFT_xSQLServerLogin public class Login { private bool _mockPasswordPassed = false; public string Name; public LoginType LoginType = LoginType.Unknown; public bool MustChangePassword = false; public bool PasswordPolicyEnforced = false; public bool PasswordExpirationEnabled = false; public bool IsDisabled = false; public string MockName; public LoginType MockLoginType; public Login( string name ) { this.Name = name; } public Login( Server server, string name ) { this.Name = name; } public Login( Object server, string name ) { this.Name = name; } public void Alter() { if( !( String.IsNullOrEmpty(this.MockName) ) ) { if(this.MockName != this.Name) { throw new Exception(); } } if( !( String.IsNullOrEmpty(this.MockLoginType.ToString()) ) ) { if( this.MockLoginType != this.LoginType ) { throw new Exception(this.MockLoginType.ToString()); } } } public void ChangePassword( SecureString secureString ) { IntPtr valuePtr = IntPtr.Zero; try { valuePtr = Marshal.SecureStringToGlobalAllocUnicode(secureString); if ( Marshal.PtrToStringUni(valuePtr) == "pw" ) { throw new FailedOperationException ( "FailedOperationException", new SmoException ( "SmoException", new SqlServerManagementException ( "SqlServerManagementException", new Exception ( "Password validation failed. The password does not meet Windows policy requirements because it is too short." ) ) ) ); } else if ( Marshal.PtrToStringUni(valuePtr) == "reused" ) { throw new FailedOperationException (); } else if ( Marshal.PtrToStringUni(valuePtr) == "other" ) { throw new Exception (); } } finally { Marshal.ZeroFreeGlobalAllocUnicode(valuePtr); } } public void Create() { if( this.LoginType == LoginType.Unknown ) { throw new System.Exception( "Called Create() method without a value for LoginType." ); } if( this.LoginType == LoginType.SqlLogin && _mockPasswordPassed != true ) { throw new System.Exception( "Called Create() method for the LoginType 'SqlLogin' but called with the wrong overloaded method. Did not pass the password with the Create() method." ); } if( !( String.IsNullOrEmpty(this.MockName) ) ) { if(this.MockName != this.Name) { throw new Exception(); } } if( !( String.IsNullOrEmpty(this.MockLoginType.ToString()) ) ) { if( this.MockLoginType != this.LoginType ) { throw new Exception(this.MockLoginType.ToString()); } } } public void Create( SecureString secureString ) { _mockPasswordPassed = true; this.Create(); } public void Create( SecureString password, LoginCreateOptions options ) { IntPtr valuePtr = IntPtr.Zero; try { valuePtr = Marshal.SecureStringToGlobalAllocUnicode(password); if ( Marshal.PtrToStringUni(valuePtr) == "pw" ) { throw new FailedOperationException ( "FailedOperationException", new SmoException ( "SmoException", new SqlServerManagementException ( "SqlServerManagementException", new Exception ( "Password validation failed. The password does not meet Windows policy requirements because it is too short." ) ) ) ); } else if ( this.Name == "Existing" ) { throw new FailedOperationException ( "The login already exists" ); } else if ( this.Name == "Unknown" ) { throw new Exception (); } else { _mockPasswordPassed = true; this.Create(); } } finally { Marshal.ZeroFreeGlobalAllocUnicode(valuePtr); } } public void Drop() { if( !( String.IsNullOrEmpty(this.MockName) ) ) { if(this.MockName != this.Name) { throw new Exception(); } } if( !( String.IsNullOrEmpty(this.MockLoginType.ToString()) ) ) { if( this.MockLoginType != this.LoginType ) { throw new Exception(this.MockLoginType.ToString()); } } } } // TypeName: Microsoft.SqlServer.Management.Smo.ServerRole // BaseType: Microsoft.SqlServer.Management.Smo.ScriptNameObjectBase // Used by: // MSFT_xSQLServerRole public class ServerRole { public ServerRole( Server server, string name ) { this.Name = name; } public ServerRole( Object server, string name ) { this.Name = name; } public string Name; } // TypeName: Microsoft.SqlServer.Management.Smo.Database // BaseType: Microsoft.SqlServer.Management.Smo.ScriptNameObjectBase // Used by: // MSFT_xSQLServerAlwaysOnAvailabilityGroupDatabaseMembership // MSFT_xSQLServerDatabase // MSFT_xSQLServerDatabasePermission public class Database { public bool AutoClose = false; public string AvailabilityGroupName = ""; public Certificate[] Certificates; public string ContainmentType = "None"; public DatabaseEncryptionKey DatabaseEncryptionKey; public string DefaultFileStreamFileGroup; public bool EncryptionEnabled = false; public Hashtable FileGroups; public string FilestreamDirectoryName; public string FilestreamNonTransactedAccess = "Off"; public int ID = 6; public bool IsMirroringEnabled = false; public DateTime LastBackupDate = DateTime.Now; public Hashtable LogFiles; public string MockGranteeName; public string Owner = "sa"; public bool ReadOnly = false; public string RecoveryModel = "Full"; public string UserAccess = "Multiple"; public Database( Server server, string name ) { this.Name = name; } public Database( Object server, string name ) { this.Name = name; } public Database() {} public string Name; public void Create() { } public void Drop() { } public Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo[] EnumDatabasePermissions( string granteeName ) { List<Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo> listOfDatabasePermissionInfo = new List<Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo>(); if( Globals.GenerateMockData ) { Microsoft.SqlServer.Management.Smo.DatabasePermissionSet[] permissionSet = { new Microsoft.SqlServer.Management.Smo.DatabasePermissionSet( true, false ), new Microsoft.SqlServer.Management.Smo.DatabasePermissionSet( false, true ) }; listOfDatabasePermissionInfo.Add( new Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo( permissionSet ) ); } else { listOfDatabasePermissionInfo.Add( new Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo() ); } Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo[] permissionInfo = listOfDatabasePermissionInfo.ToArray(); return permissionInfo; } public void Grant( Microsoft.SqlServer.Management.Smo.DatabasePermissionSet permission, string granteeName ) { if( granteeName != this.MockGranteeName ) { string errorMessage = "Expected to get granteeName == '" + this.MockGranteeName + "'. But got '" + granteeName + "'"; throw new System.ArgumentException(errorMessage, "granteeName"); } } public void Deny( Microsoft.SqlServer.Management.Smo.DatabasePermissionSet permission, string granteeName ) { if( granteeName != this.MockGranteeName ) { string errorMessage = "Expected to get granteeName == '" + this.MockGranteeName + "'. But got '" + granteeName + "'"; throw new System.ArgumentException(errorMessage, "granteeName"); } } } // TypeName: Microsoft.SqlServer.Management.Smo.User // BaseType: Microsoft.SqlServer.Management.Smo.ScriptNameObjectBase // Used by: // xSQLServerDatabaseRole.Tests.ps1 public class User { public User( Server server, string name ) { this.Name = name; } public User( Object server, string name ) { this.Name = name; } public string Name; public string Login; public void Create() { } public void Drop() { } } // TypeName: Microsoft.SqlServer.Management.Smo.SqlServerManagementException // BaseType: System.Exception // Used by: // xSqlServerLogin.Tests.ps1 public class SqlServerManagementException : Exception { public SqlServerManagementException () : base () {} public SqlServerManagementException (string message) : base (message) {} public SqlServerManagementException (string message, Exception inner) : base (message, inner) {} } // TypeName: Microsoft.SqlServer.Management.Smo.SmoException // BaseType: Microsoft.SqlServer.Management.Smo.SqlServerManagementException // Used by: // xSqlServerLogin.Tests.ps1 public class SmoException : SqlServerManagementException { public SmoException () : base () {} public SmoException (string message) : base (message) {} public SmoException (string message, SqlServerManagementException inner) : base (message, inner) {} } // TypeName: Microsoft.SqlServer.Management.Smo.FailedOperationException // BaseType: Microsoft.SqlServer.Management.Smo.SmoException // Used by: // xSqlServerLogin.Tests.ps1 public class FailedOperationException : SmoException { public FailedOperationException () : base () {} public FailedOperationException (string message) : base (message) {} public FailedOperationException (string message, SmoException inner) : base (message, inner) {} } // TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityGroup // BaseType: Microsoft.SqlServer.Management.Smo.NamedSmoObject // Used by: // xSQLServerAlwaysOnAvailabilityGroup public class AvailabilityGroup { public AvailabilityGroup() {} public AvailabilityGroup( Server server, string name ) {} public string AutomatedBackupPreference; public AvailabilityDatabaseCollection AvailabilityDatabases = new AvailabilityDatabaseCollection(); public AvailabilityReplicaCollection AvailabilityReplicas = new AvailabilityReplicaCollection(); public bool BasicAvailabilityGroup; public bool DatabaseHealthTrigger; public bool DtcSupportEnabled; public string FailureConditionLevel; public string HealthCheckTimeout; public string Name; public string PrimaryReplicaServerName; public string LocalReplicaRole = "Secondary"; public void Alter() { if ( this.Name == "AlterFailed" ) { throw new System.Exception( "Alter Availability Group failed" ); } } public AvailabilityGroup Clone() { return new AvailabilityGroup() { AutomatedBackupPreference = this.AutomatedBackupPreference, AvailabilityDatabases = this.AvailabilityDatabases, AvailabilityReplicas = this.AvailabilityReplicas, BasicAvailabilityGroup = this.BasicAvailabilityGroup, DatabaseHealthTrigger = this.DatabaseHealthTrigger, DtcSupportEnabled = this.DtcSupportEnabled, FailureConditionLevel = this.FailureConditionLevel, HealthCheckTimeout = this.HealthCheckTimeout, Name = this.Name, PrimaryReplicaServerName = this.PrimaryReplicaServerName, LocalReplicaRole = this.LocalReplicaRole }; } } // TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityReplica // BaseType: Microsoft.SqlServer.Management.Smo.NamedSmoObject // Used by: // xSQLServerAlwaysOnAvailabilityGroup public class AvailabilityReplica { public AvailabilityReplica() {} public AvailabilityReplica( AvailabilityGroup availabilityGroup, string name ) {} public string AvailabilityMode; public string BackupPriority; public string ConnectionModeInPrimaryRole; public string ConnectionModeInSecondaryRole; public string EndpointUrl; public string FailoverMode; public string Name; public string ReadOnlyRoutingConnectionUrl; public string[] ReadOnlyRoutingList; public string Role = "Secondary"; public void Alter() { if ( this.Name == "AlterFailed" ) { throw new System.Exception( "Alter Availability Group Replica failed" ); } } public void Create() {} } // TypeName: Microsoft.SqlServer.Management.Common.ServerConnection // Used by: // xSQLServerAlwaysOnAvailabilityGroupDatabaseMembership public class ConnectionContext { public string TrueLogin; public void Create() {} } // TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityDatabase // Used by: // xSQLServerAlwaysOnAvailabilityGroupDatabaseMembership public class AvailabilityDatabase { public string Name; public void Create() {} } // TypeName: Microsoft.SqlServer.Management.Smo.DatabaseCollection // Used by: // xSQLServerAlwaysOnAvailabilityGroupDatabaseMembership public class DatabaseCollection : Collection<Database> { public Database this[string name] { get { foreach ( Database database in this ) { if ( name == database.Name ) { return database; } } return null; } } } // TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityReplicaCollection // Used by: // xSQLServerAlwaysOnAvailabilityGroupDatabaseMembership public class AvailabilityReplicaCollection : Collection<AvailabilityReplica> { public AvailabilityReplica this[string name] { get { foreach ( AvailabilityReplica availabilityReplica in this ) { if ( name == availabilityReplica.Name ) { return availabilityReplica; } } return null; } } } // TypeName: Microsoft.SqlServer.Management.Smo.DatabaseEncryptionKey // Used by: // xSQLServerAlwaysOnAvailabilityGroupDatabaseMembership public class DatabaseEncryptionKey { public string EncryptorName; public byte[] Thumbprint; } // TypeName: Microsoft.SqlServer.Management.Smo.Certificate // Used by: // xSQLServerAlwaysOnAvailabilityGroupDatabaseMembership public class Certificate { public byte[] Thumbprint; } // TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityDatabaseCollection // Used by: // xSQLServerAlwaysOnAvailabilityGroupDatabaseMembership public class AvailabilityDatabaseCollection : Collection<AvailabilityDatabase> { public AvailabilityDatabase this[string name] { get { foreach ( AvailabilityDatabase availabilityDatabase in this ) { if ( name == availabilityDatabase.Name ) { return availabilityDatabase; } } return null; } } } // TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityGroupCollection // Used by: // xSQLServerAlwaysOnAvailabilityGroup public class AvailabilityGroupCollection : Collection<AvailabilityGroup> { public AvailabilityGroup this[string name] { get { foreach ( AvailabilityGroup availabilityGroup in this ) { if ( name == availabilityGroup.Name ) { return availabilityGroup; } } return null; } } } // TypeName: Microsoft.SqlServer.Management.Smo.Endpoint // Used by: // xSQLServerAlwaysOnAvailabilityGroup public class Endpoint { public string Name; public string EndpointType; public Hashtable Protocol; } // TypeName: Microsoft.SqlServer.Management.Smo.EndpointCollection // Used by: // xSQLServerAlwaysOnAvailabilityGroup public class EndpointCollection : Collection<Endpoint> { public Endpoint this[string name] { get { foreach ( Endpoint endpoint in this ) { if ( name == endpoint.Name ) { return endpoint; } } return null; } } } #endregion Public Classes } namespace Microsoft.SqlServer.Management.Smo.Wmi { #region Public Enums // TypeName: Microsoft.SqlServer.Management.Smo.Wmi.ManagedServiceType // Used by: // MSFT_xSQLServerServiceAccount.Tests.ps1 public enum ManagedServiceType { SqlServer = 1, SqlAgent = 2, Search = 3, SqlServerIntegrationService = 4, AnalysisServer = 5, ReportServer = 6, SqlBrowser = 7, NotificationServer = 8 } #endregion }
using System; using System.Collections.Generic; using System.Linq; using Signum.Entities.MachineLearning; using Signum.Entities.DynamicQuery; using Signum.Utilities; using Signum.Entities; using System.Diagnostics; using Signum.Engine.Files; using Signum.Engine.Operations; using Signum.Entities.UserAssets; using System.IO; using static Tensorflow.Binding; using Tensorflow; using Tensorflow.Keras.Optimizers; using Tensorflow.NumPy; namespace Signum.Engine.MachineLearning.TensorFlow { public class TensorFlowNeuralNetworkPredictor : IPredictorAlgorithm { public static Func<PredictorEntity, int, string> TrainingModelDirectory = (PredictorEntity p, int miniBatchIndex) => $"TensorFlowModels/{p.Id}/Training/{miniBatchIndex}"; public static Func<PredictorEntity, string> PredictorDirectory = (PredictorEntity p) => $"TensorFlowModels/{p.Id}"; public string ModelFileName = "Model"; public Dictionary<PredictorColumnEncodingSymbol, ITensorFlowEncoding> Encodings = new Dictionary<PredictorColumnEncodingSymbol, ITensorFlowEncoding> { { DefaultColumnEncodings.None, new NoneTFEncoding() }, { DefaultColumnEncodings.OneHot, new OneHotTFEncoding() }, { DefaultColumnEncodings.NormalizeZScore, new NormalizeZScoreTFEncoding() }, { DefaultColumnEncodings.NormalizeMinMax, new NormalizeMinMaxTFEncoding() }, { DefaultColumnEncodings.NormalizeLog, new NormalizeLogTFEncoding() }, { DefaultColumnEncodings.SplitWords, new SplitWordsTFEncoding() }, }; public void InitialSetup() { } public string? ValidateEncodingProperty(PredictorEntity predictor, PredictorSubQueryEntity? subQuery, PredictorColumnEncodingSymbol encoding, PredictorColumnUsage usage, QueryTokenEmbedded token) { return Encodings.GetOrThrow(encoding).ValidateEncodingProperty(predictor, subQuery, encoding, usage, token); } public List<PredictorCodification> GenerateCodifications(PredictorColumnEncodingSymbol encoding, ResultColumn resultColumn, PredictorColumnBase column) { return Encodings.GetOrThrow(encoding).GenerateCodifications(resultColumn, column); } public IEnumerable<PredictorColumnEncodingSymbol> GetRegisteredEncodingSymbols() { return Encodings.Keys; } //Errors with CNTK: https://github.com/Microsoft/CNTK/issues/2614 public void Train(PredictorTrainingContext ctx) { InitialSetup(); tf.compat.v1.disable_eager_execution(); var p = ctx.Predictor; var nn = (NeuralNetworkSettingsEntity)p.AlgorithmSettings; Tensor inputPlaceholder = tf.placeholder(tf.float32, new[] { -1, ctx.InputCodifications.Count }, "inputPlaceholder"); Tensor outputPlaceholder = tf.placeholder(tf.float32, new[] { -1, ctx.OutputCodifications.Count }, "outputPlaceholder"); Tensor currentTensor = inputPlaceholder; nn.HiddenLayers.ForEach((layer, i) => { currentTensor = NetworkBuilder.DenseLayer(currentTensor, layer.Size, layer.Activation, layer.Initializer, p.Settings.Seed ?? 0, "hidden" + i); }); Tensor output = NetworkBuilder.DenseLayer(currentTensor, ctx.OutputCodifications.Count, nn.OutputActivation, nn.OutputInitializer, p.Settings.Seed ?? 0, "output"); Tensor calculatedOutput = tf.identity(output, "calculatedOutput"); Tensor loss = NetworkBuilder.GetEvalFunction(nn.LossFunction, outputPlaceholder, calculatedOutput); Tensor accuracy = NetworkBuilder.GetEvalFunction(nn.EvalErrorFunction, outputPlaceholder, calculatedOutput); // prepare for training Optimizer optimizer = NetworkBuilder.GetOptimizer(nn); Operation trainOperation = optimizer.minimize(loss); Random rand = p.Settings.Seed == null ? new Random() : new Random(p.Settings.Seed.Value); var (training, validation) = ctx.SplitTrainValidation(rand); var minibachtSize = nn.MinibatchSize; var numMinibatches = nn.NumMinibatches; Stopwatch sw = Stopwatch.StartNew(); List<FinalCandidate> candidate = new List<FinalCandidate>(); var config = new ConfigProto { IntraOpParallelismThreads = 1, InterOpParallelismThreads = 1, LogDevicePlacement = true }; ctx.ReportProgress($"Deleting Files"); var dir = PredictorDirectory(ctx.Predictor); if (Directory.Exists(dir)) Directory.Delete(dir, true); Directory.CreateDirectory(dir); ctx.ReportProgress($"Starting training..."); var saver = tf.train.Saver(); using (var sess = tf.Session(config)) { sess.run(tf.global_variables_initializer()); for (int i = 0; i < numMinibatches; i++) { using (HeavyProfiler.Log("MiniBatch", () => i.ToString())) { var trainMinibatch = 0.To(minibachtSize).Select(_ => rand.NextElement(training)).ToList(); var inputValue = CreateNDArray(ctx, trainMinibatch, ctx.InputCodifications.Count, ctx.InputCodificationsByColumn); var outputValue = CreateNDArray(ctx, trainMinibatch, ctx.OutputCodifications.Count, ctx.OutputCodificationsByColumn); using (HeavyProfiler.Log("TrainMinibatch", () => i.ToString())) { sess.run(trainOperation, (inputPlaceholder, inputValue), (outputPlaceholder, outputValue)); } if (ctx.StopTraining) p = ctx.Predictor = ctx.Predictor.ToLite().RetrieveAndRemember(); var isLast = numMinibatches - nn.BestResultFromLast <= i; if (isLast || (i % nn.SaveProgressEvery) == 0 || ctx.StopTraining) { float loss_val; float accuracy_val; using (HeavyProfiler.Log("EvalTraining", () => i.ToString())) { (loss_val, accuracy_val) = sess.run((loss, accuracy), (inputPlaceholder, inputValue), (outputPlaceholder, outputValue)); } var ep = new EpochProgress { Ellapsed = sw.ElapsedMilliseconds, Epoch = i, TrainingExamples = i * minibachtSize, LossTraining = loss_val, AccuracyTraining = accuracy_val, LossValidation = null, AccuracyValidation = null, }; ctx.ReportProgress($"Training Minibatches Loss:{loss_val} / Accuracy:{accuracy_val}", (i + 1) / (decimal)numMinibatches); ctx.Progresses.Enqueue(ep); if (isLast || (i % nn.SaveValidationProgressEvery) == 0 || ctx.StopTraining) { using (HeavyProfiler.LogNoStackTrace("EvalValidation")) { var validateMinibatch = 0.To(minibachtSize).Select(_ => rand.NextElement(validation)).ToList(); var inputValValue = CreateNDArray(ctx, validateMinibatch, ctx.InputCodifications.Count, ctx.InputCodificationsByColumn); var outputValValue = CreateNDArray(ctx, validateMinibatch, ctx.OutputCodifications.Count, ctx.OutputCodificationsByColumn); (loss_val, accuracy_val) = sess.run((loss, accuracy), (inputPlaceholder, inputValValue), (outputPlaceholder, outputValValue)); ep.LossValidation = loss_val; ep.AccuracyValidation = accuracy_val; } } var progress = ep.SaveEntity(ctx.Predictor); if (isLast || ctx.StopTraining) { Directory.CreateDirectory(TrainingModelDirectory(ctx.Predictor, i)); var save = saver.save(sess, Path.Combine(TrainingModelDirectory(ctx.Predictor, i), ModelFileName)); using (HeavyProfiler.LogNoStackTrace("FinalCandidate")) { candidate.Add(new FinalCandidate { ModelIndex = i, ResultTraining = new PredictorMetricsEmbedded { Accuracy = progress.AccuracyTraining, Loss = progress.LossTraining }, ResultValidation = new PredictorMetricsEmbedded { Accuracy = progress.AccuracyValidation, Loss = progress.LossValidation }, }); } } } if (ctx.StopTraining) break; } } } var best = candidate.WithMin(a => a.ResultValidation.Loss!.Value); p.ResultTraining = best.ResultTraining; p.ResultValidation = best.ResultValidation; var files = Directory.GetFiles(TrainingModelDirectory(ctx.Predictor, best.ModelIndex)); p.Files.AddRange(files.Select(p => new Entities.Files.FilePathEmbedded(PredictorFileType.PredictorFile, p))); using (OperationLogic.AllowSave<PredictorEntity>()) p.Save(); } #pragma warning disable CS8618 // Non-nullable field is uninitialized. public class FinalCandidate { public int ModelIndex; public PredictorMetricsEmbedded ResultTraining; public PredictorMetricsEmbedded ResultValidation; } #pragma warning restore CS8618 // Non-nullable field is uninitialized. NDArray CreateNDArray(PredictorTrainingContext ctx, List<ResultRow> rows, int codificationCount, Dictionary<PredictorColumnBase, List<PredictorCodification>> codificationByColumn) { using (HeavyProfiler.Log("CreateValue", () => $"Rows {rows.Count} Codifications {codificationCount}")) { float[] inputValues = new float[rows.Count * codificationCount]; for (int i = 0; i < rows.Count; i++) { ResultRow mainRow = rows[i]; var mainKey = ctx.MainQuery.GetParentKey(mainRow); int offset = i * codificationCount; foreach (var kvp in codificationByColumn) { PredictorColumnBase col = kvp.Key; object? value; if (col is PredictorColumnMain pcm) { value = mainRow[pcm.PredictorColumnIndex]; } else if (col is PredictorColumnSubQuery pcsq) { SubQuery sq = ctx.SubQueries.GetOrThrow(pcsq.SubQuery); object?[]? rowValues = sq.GroupedValues.TryGetC(mainKey)?.TryGetC(pcsq.Keys); value = rowValues == null ? null : rowValues[sq.ColumnIndexToValueIndex[pcsq.PredictorColumnIndex]]; } else { throw new UnexpectedValueException(col); } using (HeavyProfiler.LogNoStackTrace("EncodeValue")) { ITensorFlowEncoding encoding = Encodings.GetOrThrow(col.Encoding); encoding.EncodeValue(value ?? TensorFlowDefault.GetDefaultValue(kvp.Value.FirstEx()), col, kvp.Value, inputValues, offset); } } } using (HeavyProfiler.LogNoStackTrace("CreateBatch")) return np.array(inputValues).reshape((rows.Count, codificationCount)); } } public PredictDictionary Predict(PredictorPredictContext ctx, PredictDictionary input) { using (HeavyProfiler.LogNoStackTrace("Predict")) { lock (lockKey) { var model = (TensorFlowModel)ctx.Model!; model.Session.as_default(); model.Graph.as_default(); NDArray inputValue = GetValueForPredict(ctx, input); NDArray outputValuesND = model.Session.run(model.CalculatedOutput, (model.InputPlaceholder, inputValue)); float[] outputValues = outputValuesND.ToArray<float>(); PredictDictionary dic = GetPredictionDictionary(outputValues, ctx, input.Options!); return dic; } } } public List<PredictDictionary> PredictMultiple(PredictorPredictContext ctx, List<PredictDictionary> inputs) { using (HeavyProfiler.LogNoStackTrace("PredictMultiple")) { lock (lockKey) { var model = (TensorFlowModel)ctx.Model!; tf.compat.v1.disable_eager_execution(); model.Session.as_default(); model.Graph.as_default(); var result = new List<PredictDictionary>(); foreach (var input in inputs) { NDArray inputValue = GetValueForPredict(ctx, input); NDArray outputValuesND = model.Session.run(model.CalculatedOutput, (model.InputPlaceholder, inputValue)); float[] outputValues = outputValuesND.ToArray<float>(); PredictDictionary dic = GetPredictionDictionary(outputValues, ctx, input.Options!); result.Add(dic); } return result; } } } private PredictDictionary GetPredictionDictionary(float[] outputValues, PredictorPredictContext ctx, PredictionOptions options) { using (HeavyProfiler.LogNoStackTrace("GetPredictionDictionary")) { return new PredictDictionary(ctx.Predictor, options, null) { MainQueryValues = ctx.MainOutputCodifications.SelectDictionary(col => col, (col, list) => Encodings.GetOrThrow(col.Encoding).DecodeValue(list.First().Column, list, outputValues, options)), SubQueries = ctx.Predictor.SubQueries.ToDictionary(sq => sq, sq => new PredictSubQueryDictionary(sq) { SubQueryGroups = ctx.SubQueryOutputCodifications.TryGetC(sq)?.Groups.ToDictionary( kvp => kvp.Key, kvp => kvp.Value .Where(a => a.Key.Usage == PredictorSubQueryColumnUsage.Output) .ToDictionary(a => a.Key, a => Encodings.GetOrThrow(a.Key.Encoding).DecodeValue(a.Value.FirstEx().Column, a.Value, outputValues, options)), ObjectArrayComparer.Instance ) ?? new Dictionary<object?[], Dictionary<PredictorSubQueryColumnEmbedded, object?>>(ObjectArrayComparer.Instance), }) }; } } private NDArray GetValueForPredict(PredictorPredictContext ctx, PredictDictionary input) { using (HeavyProfiler.Log("GetValueForPredict", () => $"Inputs Codifications {ctx.InputCodifications.Count}")) { if (input.SubQueries.Values.Any(a => a.SubQueryGroups.Comparer != ObjectArrayComparer.Instance)) throw new Exception("Unexpected dictionary comparer"); float[] inputValues = new float[ctx.InputCodifications.Count]; var groups = ctx.InputCodificationsByColumn; foreach (var kvp in groups) { PredictorColumnBase col = kvp.Key; object? value; if (col is PredictorColumnMain pcm) { value = input.MainQueryValues.GetOrThrow(pcm.PredictorColumn); } else if (col is PredictorColumnSubQuery pcsq) { var sq = input.SubQueries.GetOrThrow(pcsq.SubQuery); var dic = sq.SubQueryGroups.TryGetC(pcsq.Keys); value = dic == null ? null : dic.GetOrThrow(pcsq.PredictorSubQueryColumn); } else { throw new UnexpectedValueException(col); } using (HeavyProfiler.LogNoStackTrace("EncodeValue")) { var enc = Encodings.GetOrThrow(col.Encoding); enc.EncodeValue(value ?? TensorFlowDefault.GetDefaultValue(kvp.Value.FirstEx()), col, kvp.Value, inputValues, 0); } } using (HeavyProfiler.LogNoStackTrace("CreateBatch")) return np.array(inputValues).reshape((-1, inputValues.Length)); } } static object lockKey = new object(); public void LoadModel(PredictorPredictContext ctx) { lock (lockKey) { this.InitialSetup(); var nnSettings = (NeuralNetworkSettingsEntity)ctx.Predictor.AlgorithmSettings; var dir = Path.Combine(PredictorDirectory(ctx.Predictor)); if (Directory.Exists(dir)) Directory.Delete(dir, true); Directory.CreateDirectory(dir); foreach (var item in ctx.Predictor.Files) { using (var fileStream = File.Create(Path.Combine(dir, item.FileName))) { using (var readStream = item.OpenRead()) { readStream.CopyTo(fileStream); } } } var graph = tf.Graph(); var sess = tf.Session(graph); { var saver = tf.train.import_meta_graph(Path.Combine(dir, $"{ModelFileName}.meta")); saver.restore(sess, Path.Combine(dir, ModelFileName)); var array = graph.get_operations().Select(a=>a.name).ToArray(); var inputPlaceholder = graph.get_operation_by_name("inputPlaceholder"); var calculatedOutput = graph.get_operation_by_name("calculatedOutput"); ctx.Model = new TensorFlowModel { InputPlaceholder = inputPlaceholder, CalculatedOutput = calculatedOutput, Graph = graph, Session = sess, }; } //ctx.Model = Function.Load(ctx.Predictor.Files.SingleEx().GetByteArray()); } } } #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. class TensorFlowModel { public Tensor InputPlaceholder { get; internal set; } public Tensor CalculatedOutput { get; internal set; } public Graph Graph { get; internal set; } public Session Session { get; internal set; } } #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. }
using Lucene.Net.Attributes; using Lucene.Net.Documents; using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Text; namespace Lucene.Net.Index { using Lucene.Net.Randomized.Generators; using Lucene.Net.Util; using NUnit.Framework; using BytesRef = Lucene.Net.Util.BytesRef; using CharsRef = Lucene.Net.Util.CharsRef; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using UnicodeUtil = Lucene.Net.Util.UnicodeUtil; [TestFixture] public class TestIndexWriterUnicode : LuceneTestCase { internal readonly string[] Utf8Data = new string[] { "ab\udc17cd", "ab\ufffdcd", "\udc17abcd", "\ufffdabcd", "\udc17", "\ufffd", "ab\udc17\udc17cd", "ab\ufffd\ufffdcd", "\udc17\udc17abcd", "\ufffd\ufffdabcd", "\udc17\udc17", "\ufffd\ufffd", "ab\ud917cd", "ab\ufffdcd", "\ud917abcd", "\ufffdabcd", "\ud917", "\ufffd", "ab\ud917\ud917cd", "ab\ufffd\ufffdcd", "\ud917\ud917abcd", "\ufffd\ufffdabcd", "\ud917\ud917", "\ufffd\ufffd", "ab\udc17\ud917cd", "ab\ufffd\ufffdcd", "\udc17\ud917abcd", "\ufffd\ufffdabcd", "\udc17\ud917", "\ufffd\ufffd", "ab\udc17\ud917\udc17\ud917cd", "ab\ufffd\ud917\udc17\ufffdcd", "\udc17\ud917\udc17\ud917abcd", "\ufffd\ud917\udc17\ufffdabcd", "\udc17\ud917\udc17\ud917", "\ufffd\ud917\udc17\ufffd" }; private int NextInt(int lim) { return Random().Next(lim); } private int NextInt(int start, int end) { return start + NextInt(end - start); } private bool FillUnicode(char[] buffer, char[] expected, int offset, int count) { int len = offset + count; bool hasIllegal = false; if (offset > 0 && buffer[offset] >= 0xdc00 && buffer[offset] < 0xe000) // Don't start in the middle of a valid surrogate pair { offset--; } for (int i = offset; i < len; i++) { int t = NextInt(6); if (0 == t && i < len - 1) { // Make a surrogate pair // High surrogate expected[i] = buffer[i++] = (char)NextInt(0xd800, 0xdc00); // Low surrogate expected[i] = buffer[i] = (char)NextInt(0xdc00, 0xe000); } else if (t <= 1) { expected[i] = buffer[i] = (char)NextInt(0x80); } else if (2 == t) { expected[i] = buffer[i] = (char)NextInt(0x80, 0x800); } else if (3 == t) { expected[i] = buffer[i] = (char)NextInt(0x800, 0xd800); } else if (4 == t) { expected[i] = buffer[i] = (char)NextInt(0xe000, 0xffff); } else if (5 == t && i < len - 1) { // Illegal unpaired surrogate if (NextInt(10) == 7) { if (Random().NextBoolean()) { buffer[i] = (char)NextInt(0xd800, 0xdc00); } else { buffer[i] = (char)NextInt(0xdc00, 0xe000); } expected[i++] = (char)0xfffd; expected[i] = buffer[i] = (char)NextInt(0x800, 0xd800); hasIllegal = true; } else { expected[i] = buffer[i] = (char)NextInt(0x800, 0xd800); } } else { expected[i] = buffer[i] = ' '; } } return hasIllegal; } // both start & end are inclusive private int GetInt(Random r, int start, int end) { return start + r.Next(1 + end - start); } private string AsUnicodeChar(char c) { return "U+" + ((int)c).ToString("x"); } private string TermDesc(string s) { string s0; Assert.IsTrue(s.Length <= 2); if (s.Length == 1) { s0 = AsUnicodeChar(s[0]); } else { s0 = AsUnicodeChar(s[0]) + "," + AsUnicodeChar(s[1]); } return s0; } private void CheckTermsOrder(IndexReader r, ISet<string> allTerms, bool isTop) { TermsEnum terms = MultiFields.GetFields(r).Terms("f").Iterator(null); BytesRef last = new BytesRef(); HashSet<string> seenTerms = new HashSet<string>(); while (true) { BytesRef term = terms.Next(); if (term == null) { break; } Assert.IsTrue(last.CompareTo(term) < 0); last.CopyBytes(term); string s = term.Utf8ToString(); Assert.IsTrue(allTerms.Contains(s), "term " + TermDesc(s) + " was not added to index (count=" + allTerms.Count + ")"); seenTerms.Add(s); } if (isTop) { Assert.IsTrue(allTerms.SetEquals(seenTerms)); } // Test seeking: IEnumerator<string> it = seenTerms.GetEnumerator(); while (it.MoveNext()) { BytesRef tr = new BytesRef(it.Current); Assert.AreEqual(TermsEnum.SeekStatus.FOUND, terms.SeekCeil(tr), "seek failed for term=" + TermDesc(tr.Utf8ToString())); } } // LUCENE-510 [Test, LongRunningTest] public virtual void TestRandomUnicodeStrings() { char[] buffer = new char[20]; char[] expected = new char[20]; BytesRef utf8 = new BytesRef(20); CharsRef utf16 = new CharsRef(20); int num = AtLeast(100000); for (int iter = 0; iter < num; iter++) { bool hasIllegal = FillUnicode(buffer, expected, 0, 20); UnicodeUtil.UTF16toUTF8(buffer, 0, 20, utf8); if (!hasIllegal) { var b = (new string(buffer, 0, 20)).GetBytes(IOUtils.CHARSET_UTF_8); Assert.AreEqual(b.Length, utf8.Length); for (int i = 0; i < b.Length; i++) { Assert.AreEqual(b[i], utf8.Bytes[i]); } } UnicodeUtil.UTF8toUTF16(utf8.Bytes, 0, utf8.Length, utf16); Assert.AreEqual(utf16.Length, 20); for (int i = 0; i < 20; i++) { Assert.AreEqual(expected[i], utf16.Chars[i]); } } } // LUCENE-510 [Test] public virtual void TestAllUnicodeChars() { BytesRef utf8 = new BytesRef(10); CharsRef utf16 = new CharsRef(10); char[] chars = new char[2]; for (int ch = 0; ch < 0x0010FFFF; ch++) { if (ch == 0xd800) // Skip invalid code points { ch = 0xe000; } int len = 0; if (ch <= 0xffff) { chars[len++] = (char)ch; } else { chars[len++] = (char)(((ch - 0x0010000) >> 10) + UnicodeUtil.UNI_SUR_HIGH_START); chars[len++] = (char)(((ch - 0x0010000) & 0x3FFL) + UnicodeUtil.UNI_SUR_LOW_START); } UnicodeUtil.UTF16toUTF8(chars, 0, len, utf8); string s1 = new string(chars, 0, len); string s2 = Encoding.UTF8.GetString(utf8.Bytes, utf8.Offset, utf8.Length); Assert.AreEqual(s1, s2, "codepoint " + ch); UnicodeUtil.UTF8toUTF16(utf8.Bytes, 0, utf8.Length, utf16); Assert.AreEqual(s1, new string(utf16.Chars, 0, utf16.Length), "codepoint " + ch); var b = s1.GetBytes(Encoding.UTF8); Assert.AreEqual(utf8.Length, b.Length); for (int j = 0; j < utf8.Length; j++) { Assert.AreEqual(utf8.Bytes[j], b[j]); } } } [Test] public virtual void TestEmbeddedFFFF() { Directory d = NewDirectory(); IndexWriter w = new IndexWriter(d, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); Document doc = new Document(); doc.Add(NewTextField("field", "a a\uffffb", Field.Store.NO)); w.AddDocument(doc); doc = new Document(); doc.Add(NewTextField("field", "a", Field.Store.NO)); w.AddDocument(doc); IndexReader r = w.Reader; Assert.AreEqual(1, r.DocFreq(new Term("field", "a\uffffb"))); r.Dispose(); w.Dispose(); d.Dispose(); } // LUCENE-510 [Ignore] [Test] public virtual void TestInvalidUTF16() { Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new TestIndexWriter.StringSplitAnalyzer())); Document doc = new Document(); int count = Utf8Data.Length / 2; for (int i = 0; i < count; i++) { doc.Add(NewTextField("f" + i, Utf8Data[2 * i], Field.Store.YES)); } w.AddDocument(doc); w.Dispose(); IndexReader ir = DirectoryReader.Open(dir); Document doc2 = ir.Document(0); for (int i = 0; i < count; i++) { Assert.AreEqual(1, ir.DocFreq(new Term("f" + i, Utf8Data[2 * i + 1])), "field " + i + " was not indexed correctly"); Assert.AreEqual(Utf8Data[2 * i + 1], doc2.GetField("f" + i).StringValue, "field " + i + " is incorrect"); } ir.Dispose(); dir.Dispose(); } // Make sure terms, including ones with surrogate pairs, // sort in codepoint sort order by default [Test] public virtual void TestTermUTF16SortOrder() { Random rnd = Random(); Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(rnd, dir); Document d = new Document(); // Single segment Field f = NewStringField("f", "", Field.Store.NO); d.Add(f); char[] chars = new char[2]; HashSet<string> allTerms = new HashSet<string>(); int num = AtLeast(200); for (int i = 0; i < num; i++) { string s; if (rnd.NextBoolean()) { // Single char if (rnd.NextBoolean()) { // Above surrogates chars[0] = (char)GetInt(rnd, 1 + UnicodeUtil.UNI_SUR_LOW_END, 0xffff); } else { // Below surrogates chars[0] = (char)GetInt(rnd, 0, UnicodeUtil.UNI_SUR_HIGH_START - 1); } s = new string(chars, 0, 1); } else { // Surrogate pair chars[0] = (char)GetInt(rnd, UnicodeUtil.UNI_SUR_HIGH_START, UnicodeUtil.UNI_SUR_HIGH_END); Assert.IsTrue(((int)chars[0]) >= UnicodeUtil.UNI_SUR_HIGH_START && ((int)chars[0]) <= UnicodeUtil.UNI_SUR_HIGH_END); chars[1] = (char)GetInt(rnd, UnicodeUtil.UNI_SUR_LOW_START, UnicodeUtil.UNI_SUR_LOW_END); s = new string(chars, 0, 2); } allTerms.Add(s); f.StringValue = s; writer.AddDocument(d); if ((1 + i) % 42 == 0) { writer.Commit(); } } IndexReader r = writer.Reader; // Test each sub-segment foreach (AtomicReaderContext ctx in r.Leaves) { CheckTermsOrder(ctx.Reader, allTerms, false); } CheckTermsOrder(r, allTerms, true); // Test multi segment r.Dispose(); writer.ForceMerge(1); // Test single segment r = writer.Reader; CheckTermsOrder(r, allTerms, true); r.Dispose(); writer.Dispose(); dir.Dispose(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.CoreModules.Framework.InterfaceCommander; using OpenSim.Region.CoreModules.World.Terrain.FileLoaders; using OpenSim.Region.CoreModules.World.Terrain.FloodBrushes; using OpenSim.Region.CoreModules.World.Terrain.PaintBrushes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.World.Terrain { public class TerrainModule : INonSharedRegionModule, ICommandableModule, ITerrainModule { #region StandardTerrainEffects enum /// <summary> /// A standard set of terrain brushes and effects recognised by viewers /// </summary> public enum StandardTerrainEffects : byte { Flatten = 0, Raise = 1, Lower = 2, Smooth = 3, Noise = 4, Revert = 5, // Extended brushes Erode = 255, Weather = 254, Olsen = 253 } #endregion private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly Commander m_commander = new Commander("terrain"); private readonly Dictionary<StandardTerrainEffects, ITerrainFloodEffect> m_floodeffects = new Dictionary<StandardTerrainEffects, ITerrainFloodEffect>(); private readonly Dictionary<string, ITerrainLoader> m_loaders = new Dictionary<string, ITerrainLoader>(); private readonly Dictionary<StandardTerrainEffects, ITerrainPaintableEffect> m_painteffects = new Dictionary<StandardTerrainEffects, ITerrainPaintableEffect>(); private ITerrainChannel m_channel; private Dictionary<string, ITerrainEffect> m_plugineffects; private ITerrainChannel m_revert; private Scene m_scene; private volatile bool m_tainted; #region ICommandableModule Members public ICommander CommandInterface { get { return m_commander; } } #endregion #region INonSharedRegionModule Members /// <summary> /// Creates and initialises a terrain module for a region /// </summary> /// <param name="scene">Region initialising</param> /// <param name="config">Config for the region</param> public void Initialise(IConfigSource config) { } public void AddRegion(Scene scene) { m_scene = scene; // Install terrain module in the simulator lock (m_scene) { if (m_scene.Heightmap == null) { m_channel = new TerrainChannel(); m_scene.Heightmap = m_channel; m_revert = new TerrainChannel(); UpdateRevertMap(); } else { m_channel = m_scene.Heightmap; m_revert = new TerrainChannel(); UpdateRevertMap(); } m_scene.RegisterModuleInterface<ITerrainModule>(this); m_scene.EventManager.OnNewClient += EventManager_OnNewClient; m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole; m_scene.EventManager.OnTerrainTick += EventManager_OnTerrainTick; InstallInterfaces(); } InstallDefaultEffects(); LoadPlugins(); } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { lock (m_scene) { // remove the commands m_scene.UnregisterModuleCommander(m_commander.Name); // remove the event-handlers m_scene.EventManager.OnTerrainTick -= EventManager_OnTerrainTick; m_scene.EventManager.OnPluginConsole -= EventManager_OnPluginConsole; m_scene.EventManager.OnNewClient -= EventManager_OnNewClient; // remove the interface m_scene.UnregisterModuleInterface<ITerrainModule>(this); } } public void Close() { } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "TerrainModule"; } } #endregion #region ITerrainModule Members /// <summary> /// Loads a terrain file from disk and installs it in the scene. /// </summary> /// <param name="filename">Filename to terrain file. Type is determined by extension.</param> public void LoadFromFile(string filename) { foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders) { if (filename.EndsWith(loader.Key)) { lock (m_scene) { try { ITerrainChannel channel = loader.Value.LoadFile(filename); if (channel.Width != Constants.RegionSize || channel.Height != Constants.RegionSize) { // TerrainChannel expects a RegionSize x RegionSize map, currently throw new ArgumentException(String.Format("wrong size, use a file with size {0} x {1}", Constants.RegionSize, Constants.RegionSize)); } m_log.DebugFormat("[TERRAIN]: Loaded terrain, wd/ht: {0}/{1}", channel.Width, channel.Height); m_scene.Heightmap = channel; m_channel = channel; UpdateRevertMap(); } catch (NotImplementedException) { m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value + " parser does not support file loading. (May be save only)"); throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value)); } catch (FileNotFoundException) { m_log.Error( "[TERRAIN]: Unable to load heightmap, file not found. (A directory permissions error may also cause this)"); throw new TerrainException( String.Format("unable to load heightmap: file {0} not found (or permissions do not allow access", filename)); } catch (ArgumentException e) { m_log.ErrorFormat("[TERRAIN]: Unable to load heightmap: {0}", e.Message); throw new TerrainException( String.Format("Unable to load heightmap: {0}", e.Message)); } } CheckForTerrainUpdates(); m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully"); return; } } m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format."); throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename)); } /// <summary> /// Saves the current heightmap to a specified file. /// </summary> /// <param name="filename">The destination filename</param> public void SaveToFile(string filename) { try { foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders) { if (filename.EndsWith(loader.Key)) { loader.Value.SaveFile(filename, m_channel); return; } } } catch (NotImplementedException) { m_log.Error("Unable to save to " + filename + ", saving of this file format has not been implemented."); throw new TerrainException(String.Format("Unable to save heightmap: saving of this file format not implemented")); } catch (IOException ioe) { m_log.Error(String.Format("[TERRAIN]: Unable to save to {0}, {1}", filename, ioe.Message)); throw new TerrainException(String.Format("Unable to save heightmap: {0}", ioe.Message)); } } /// <summary> /// Loads a terrain file from a stream and installs it in the scene. /// </summary> /// <param name="filename">Filename to terrain file. Type is determined by extension.</param> /// <param name="stream"></param> public void LoadFromStream(string filename, Stream stream) { foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders) { if (@filename.EndsWith(loader.Key)) { lock (m_scene) { try { ITerrainChannel channel = loader.Value.LoadStream(stream); m_scene.Heightmap = channel; m_channel = channel; UpdateRevertMap(); } catch (NotImplementedException) { m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value + " parser does not support file loading. (May be save only)"); throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value)); } } CheckForTerrainUpdates(); m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully"); return; } } m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format."); throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename)); } /// <summary> /// Modify Land /// </summary> /// <param name="pos">Land-position (X,Y,0)</param> /// <param name="size">The size of the brush (0=small, 1=medium, 2=large)</param> /// <param name="action">0=LAND_LEVEL, 1=LAND_RAISE, 2=LAND_LOWER, 3=LAND_SMOOTH, 4=LAND_NOISE, 5=LAND_REVERT</param> /// <param name="agentId">UUID of script-owner</param> public void ModifyTerrain(UUID user, Vector3 pos, byte size, byte action, UUID agentId) { float duration = 0.25f; if (action == 0) duration = 4.0f; client_OnModifyTerrain(user, (float)pos.Z, duration, size, action, pos.Y, pos.X, pos.Y, pos.X, agentId); } /// <summary> /// Saves the current heightmap to a specified stream. /// </summary> /// <param name="filename">The destination filename. Used here only to identify the image type</param> /// <param name="stream"></param> public void SaveToStream(string filename, Stream stream) { try { foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders) { if (filename.EndsWith(loader.Key)) { loader.Value.SaveStream(stream, m_channel); return; } } } catch (NotImplementedException) { m_log.Error("Unable to save to " + filename + ", saving of this file format has not been implemented."); throw new TerrainException(String.Format("Unable to save heightmap: saving of this file format not implemented")); } } public void TaintTerrain () { CheckForTerrainUpdates(); } #region Plugin Loading Methods private void LoadPlugins() { m_plugineffects = new Dictionary<string, ITerrainEffect>(); // Load the files in the Terrain/ dir string[] files = Directory.GetFiles("Terrain"); foreach (string file in files) { m_log.Info("Loading effects in " + file); try { Assembly library = Assembly.LoadFrom(file); foreach (Type pluginType in library.GetTypes()) { try { if (pluginType.IsAbstract || pluginType.IsNotPublic) continue; string typeName = pluginType.Name; if (pluginType.GetInterface("ITerrainEffect", false) != null) { ITerrainEffect terEffect = (ITerrainEffect) Activator.CreateInstance(library.GetType(pluginType.ToString())); InstallPlugin(typeName, terEffect); } else if (pluginType.GetInterface("ITerrainLoader", false) != null) { ITerrainLoader terLoader = (ITerrainLoader) Activator.CreateInstance(library.GetType(pluginType.ToString())); m_loaders[terLoader.FileExtension] = terLoader; m_log.Info("L ... " + typeName); } } catch (AmbiguousMatchException) { } } } catch (BadImageFormatException) { } } } public void InstallPlugin(string pluginName, ITerrainEffect effect) { lock (m_plugineffects) { if (!m_plugineffects.ContainsKey(pluginName)) { m_plugineffects.Add(pluginName, effect); m_log.Info("E ... " + pluginName); } else { m_plugineffects[pluginName] = effect; m_log.Warn("E ... " + pluginName + " (Replaced)"); } } } #endregion #endregion /// <summary> /// Installs into terrain module the standard suite of brushes /// </summary> private void InstallDefaultEffects() { // Draggable Paint Brush Effects m_painteffects[StandardTerrainEffects.Raise] = new RaiseSphere(); m_painteffects[StandardTerrainEffects.Lower] = new LowerSphere(); m_painteffects[StandardTerrainEffects.Smooth] = new SmoothSphere(); m_painteffects[StandardTerrainEffects.Noise] = new NoiseSphere(); m_painteffects[StandardTerrainEffects.Flatten] = new FlattenSphere(); m_painteffects[StandardTerrainEffects.Revert] = new RevertSphere(m_revert); m_painteffects[StandardTerrainEffects.Erode] = new ErodeSphere(); m_painteffects[StandardTerrainEffects.Weather] = new WeatherSphere(); m_painteffects[StandardTerrainEffects.Olsen] = new OlsenSphere(); // Area of effect selection effects m_floodeffects[StandardTerrainEffects.Raise] = new RaiseArea(); m_floodeffects[StandardTerrainEffects.Lower] = new LowerArea(); m_floodeffects[StandardTerrainEffects.Smooth] = new SmoothArea(); m_floodeffects[StandardTerrainEffects.Noise] = new NoiseArea(); m_floodeffects[StandardTerrainEffects.Flatten] = new FlattenArea(); m_floodeffects[StandardTerrainEffects.Revert] = new RevertArea(m_revert); // Filesystem load/save loaders m_loaders[".r32"] = new RAW32(); m_loaders[".f32"] = m_loaders[".r32"]; m_loaders[".ter"] = new Terragen(); m_loaders[".raw"] = new LLRAW(); m_loaders[".jpg"] = new JPEG(); m_loaders[".jpeg"] = m_loaders[".jpg"]; m_loaders[".bmp"] = new BMP(); m_loaders[".png"] = new PNG(); m_loaders[".gif"] = new GIF(); m_loaders[".tif"] = new TIFF(); m_loaders[".tiff"] = m_loaders[".tif"]; } /// <summary> /// Saves the current state of the region into the revert map buffer. /// </summary> public void UpdateRevertMap() { int x; for (x = 0; x < m_channel.Width; x++) { int y; for (y = 0; y < m_channel.Height; y++) { m_revert[x, y] = m_channel[x, y]; } } } /// <summary> /// Loads a tile from a larger terrain file and installs it into the region. /// </summary> /// <param name="filename">The terrain file to load</param> /// <param name="fileWidth">The width of the file in units</param> /// <param name="fileHeight">The height of the file in units</param> /// <param name="fileStartX">Where to begin our slice</param> /// <param name="fileStartY">Where to begin our slice</param> public void LoadFromFile(string filename, int fileWidth, int fileHeight, int fileStartX, int fileStartY) { int offsetX = (int) m_scene.RegionInfo.RegionLocX - fileStartX; int offsetY = (int) m_scene.RegionInfo.RegionLocY - fileStartY; if (offsetX >= 0 && offsetX < fileWidth && offsetY >= 0 && offsetY < fileHeight) { // this region is included in the tile request foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders) { if (filename.EndsWith(loader.Key)) { lock (m_scene) { ITerrainChannel channel = loader.Value.LoadFile(filename, offsetX, offsetY, fileWidth, fileHeight, (int) Constants.RegionSize, (int) Constants.RegionSize); m_scene.Heightmap = channel; m_channel = channel; UpdateRevertMap(); } return; } } } } /// <summary> /// Performs updates to the region periodically, synchronising physics and other heightmap aware sections /// </summary> private void EventManager_OnTerrainTick() { if (m_tainted) { m_tainted = false; m_scene.PhysicsScene.SetTerrain(m_channel.GetFloatsSerialised()); m_scene.SaveTerrain(); // Clients who look at the map will never see changes after they looked at the map, so i've commented this out. //m_scene.CreateTerrainTexture(true); } } /// <summary> /// Processes commandline input. Do not call directly. /// </summary> /// <param name="args">Commandline arguments</param> private void EventManager_OnPluginConsole(string[] args) { if (args[0] == "terrain") { if (args.Length == 1) { m_commander.ProcessConsoleCommand("help", new string[0]); return; } string[] tmpArgs = new string[args.Length - 2]; int i; for (i = 2; i < args.Length; i++) tmpArgs[i - 2] = args[i]; m_commander.ProcessConsoleCommand(args[1], tmpArgs); } } /// <summary> /// Installs terrain brush hook to IClientAPI /// </summary> /// <param name="client"></param> private void EventManager_OnNewClient(IClientAPI client) { client.OnModifyTerrain += client_OnModifyTerrain; client.OnBakeTerrain += client_OnBakeTerrain; } /// <summary> /// Checks to see if the terrain has been modified since last check /// but won't attempt to limit those changes to the limits specified in the estate settings /// currently invoked by the command line operations in the region server only /// </summary> private void CheckForTerrainUpdates() { CheckForTerrainUpdates(false); } /// <summary> /// Checks to see if the terrain has been modified since last check. /// If it has been modified, every all the terrain patches are sent to the client. /// If the call is asked to respect the estate settings for terrain_raise_limit and /// terrain_lower_limit, it will clamp terrain updates between these values /// currently invoked by client_OnModifyTerrain only and not the Commander interfaces /// <param name="respectEstateSettings">should height map deltas be limited to the estate settings limits</param> /// </summary> private void CheckForTerrainUpdates(bool respectEstateSettings) { bool shouldTaint = false; float[] serialised = m_channel.GetFloatsSerialised(); int x; for (x = 0; x < m_channel.Width; x += Constants.TerrainPatchSize) { int y; for (y = 0; y < m_channel.Height; y += Constants.TerrainPatchSize) { if (m_channel.Tainted(x, y)) { // if we should respect the estate settings then // fixup and height deltas that don't respect them if (respectEstateSettings && LimitChannelChanges(x, y)) { // this has been vetoed, so update // what we are going to send to the client serialised = m_channel.GetFloatsSerialised(); } SendToClients(serialised, x, y); shouldTaint = true; } } } if (shouldTaint) { m_tainted = true; } } /// <summary> /// Checks to see height deltas in the tainted terrain patch at xStart ,yStart /// are all within the current estate limits /// <returns>true if changes were limited, false otherwise</returns> /// </summary> private bool LimitChannelChanges(int xStart, int yStart) { bool changesLimited = false; double minDelta = m_scene.RegionInfo.RegionSettings.TerrainLowerLimit; double maxDelta = m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit; // loop through the height map for this patch and compare it against // the revert map for (int x = xStart; x < xStart + Constants.TerrainPatchSize; x++) { for (int y = yStart; y < yStart + Constants.TerrainPatchSize; y++) { double requestedHeight = m_channel[x, y]; double bakedHeight = m_revert[x, y]; double requestedDelta = requestedHeight - bakedHeight; if (requestedDelta > maxDelta) { m_channel[x, y] = bakedHeight + maxDelta; changesLimited = true; } else if (requestedDelta < minDelta) { m_channel[x, y] = bakedHeight + minDelta; //as lower is a -ve delta changesLimited = true; } } } return changesLimited; } /// <summary> /// Sends a copy of the current terrain to the scenes clients /// </summary> /// <param name="serialised">A copy of the terrain as a 1D float array of size w*h</param> /// <param name="x">The patch corner to send</param> /// <param name="y">The patch corner to send</param> private void SendToClients(float[] serialised, int x, int y) { m_scene.ForEachClient( delegate(IClientAPI controller) { controller.SendLayerData( x / Constants.TerrainPatchSize, y / Constants.TerrainPatchSize, serialised); } ); } private void client_OnModifyTerrain(UUID user, float height, float seconds, byte size, byte action, float north, float west, float south, float east, UUID agentId) { bool god = m_scene.Permissions.IsGod(user); bool allowed = false; if (north == south && east == west) { if (m_painteffects.ContainsKey((StandardTerrainEffects) action)) { bool[,] allowMask = new bool[m_channel.Width,m_channel.Height]; allowMask.Initialize(); int n = size + 1; if (n > 2) n = 4; int zx = (int) (west + 0.5); int zy = (int) (north + 0.5); int dx; for (dx=-n; dx<=n; dx++) { int dy; for (dy=-n; dy<=n; dy++) { int x = zx + dx; int y = zy + dy; if (x>=0 && y>=0 && x<m_channel.Width && y<m_channel.Height) { if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x,y,0))) { allowMask[x, y] = true; allowed = true; } } } } if (allowed) { m_painteffects[(StandardTerrainEffects) action].PaintEffect( m_channel, allowMask, west, south, height, size, seconds); CheckForTerrainUpdates(!god); //revert changes outside estate limits } } else { m_log.Debug("Unknown terrain brush type " + action); } } else { if (m_floodeffects.ContainsKey((StandardTerrainEffects) action)) { bool[,] fillArea = new bool[m_channel.Width,m_channel.Height]; fillArea.Initialize(); int x; for (x = 0; x < m_channel.Width; x++) { int y; for (y = 0; y < m_channel.Height; y++) { if (x < east && x > west) { if (y < north && y > south) { if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x,y,0))) { fillArea[x, y] = true; allowed = true; } } } } } if (allowed) { m_floodeffects[(StandardTerrainEffects) action].FloodEffect( m_channel, fillArea, size); CheckForTerrainUpdates(!god); //revert changes outside estate limits } } else { m_log.Debug("Unknown terrain flood type " + action); } } } private void client_OnBakeTerrain(IClientAPI remoteClient) { // Not a good permissions check (see client_OnModifyTerrain above), need to check the entire area. // for now check a point in the centre of the region if (m_scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, true)) { InterfaceBakeTerrain(null); //bake terrain does not use the passed in parameter } } #region Console Commands private void InterfaceLoadFile(Object[] args) { LoadFromFile((string) args[0]); CheckForTerrainUpdates(); } private void InterfaceLoadTileFile(Object[] args) { LoadFromFile((string) args[0], (int) args[1], (int) args[2], (int) args[3], (int) args[4]); CheckForTerrainUpdates(); } private void InterfaceSaveFile(Object[] args) { SaveToFile((string) args[0]); } private void InterfaceBakeTerrain(Object[] args) { UpdateRevertMap(); } private void InterfaceRevertTerrain(Object[] args) { int x, y; for (x = 0; x < m_channel.Width; x++) for (y = 0; y < m_channel.Height; y++) m_channel[x, y] = m_revert[x, y]; CheckForTerrainUpdates(); } private void InterfaceFlipTerrain(Object[] args) { String direction = (String)args[0]; if (direction.ToLower().StartsWith("y")) { for (int x = 0; x < Constants.RegionSize; x++) { for (int y = 0; y < Constants.RegionSize / 2; y++) { double height = m_channel[x, y]; double flippedHeight = m_channel[x, (int)Constants.RegionSize - 1 - y]; m_channel[x, y] = flippedHeight; m_channel[x, (int)Constants.RegionSize - 1 - y] = height; } } } else if (direction.ToLower().StartsWith("x")) { for (int y = 0; y < Constants.RegionSize; y++) { for (int x = 0; x < Constants.RegionSize / 2; x++) { double height = m_channel[x, y]; double flippedHeight = m_channel[(int)Constants.RegionSize - 1 - x, y]; m_channel[x, y] = flippedHeight; m_channel[(int)Constants.RegionSize - 1 - x, y] = height; } } } else { m_log.Error("Unrecognised direction - need x or y"); } CheckForTerrainUpdates(); } private void InterfaceRescaleTerrain(Object[] args) { double desiredMin = (double)args[0]; double desiredMax = (double)args[1]; // determine desired scaling factor double desiredRange = desiredMax - desiredMin; //m_log.InfoFormat("Desired {0}, {1} = {2}", new Object[] { desiredMin, desiredMax, desiredRange }); if (desiredRange == 0d) { // delta is zero so flatten at requested height InterfaceFillTerrain(new Object[] { args[1] }); } else { //work out current heightmap range double currMin = double.MaxValue; double currMax = double.MinValue; int width = m_channel.Width; int height = m_channel.Height; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { double currHeight = m_channel[x, y]; if (currHeight < currMin) { currMin = currHeight; } else if (currHeight > currMax) { currMax = currHeight; } } } double currRange = currMax - currMin; double scale = desiredRange / currRange; //m_log.InfoFormat("Current {0}, {1} = {2}", new Object[] { currMin, currMax, currRange }); //m_log.InfoFormat("Scale = {0}", scale); // scale the heightmap accordingly for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { double currHeight = m_channel[x, y] - currMin; m_channel[x, y] = desiredMin + (currHeight * scale); } } CheckForTerrainUpdates(); } } private void InterfaceElevateTerrain(Object[] args) { int x, y; for (x = 0; x < m_channel.Width; x++) for (y = 0; y < m_channel.Height; y++) m_channel[x, y] += (double) args[0]; CheckForTerrainUpdates(); } private void InterfaceMultiplyTerrain(Object[] args) { int x, y; for (x = 0; x < m_channel.Width; x++) for (y = 0; y < m_channel.Height; y++) m_channel[x, y] *= (double) args[0]; CheckForTerrainUpdates(); } private void InterfaceLowerTerrain(Object[] args) { int x, y; for (x = 0; x < m_channel.Width; x++) for (y = 0; y < m_channel.Height; y++) m_channel[x, y] -= (double) args[0]; CheckForTerrainUpdates(); } private void InterfaceFillTerrain(Object[] args) { int x, y; for (x = 0; x < m_channel.Width; x++) for (y = 0; y < m_channel.Height; y++) m_channel[x, y] = (double) args[0]; CheckForTerrainUpdates(); } private void InterfaceShowDebugStats(Object[] args) { double max = Double.MinValue; double min = double.MaxValue; double sum = 0; int x; for (x = 0; x < m_channel.Width; x++) { int y; for (y = 0; y < m_channel.Height; y++) { sum += m_channel[x, y]; if (max < m_channel[x, y]) max = m_channel[x, y]; if (min > m_channel[x, y]) min = m_channel[x, y]; } } double avg = sum / (m_channel.Height * m_channel.Width); m_log.Info("Channel " + m_channel.Width + "x" + m_channel.Height); m_log.Info("max/min/avg/sum: " + max + "/" + min + "/" + avg + "/" + sum); } private void InterfaceEnableExperimentalBrushes(Object[] args) { if ((bool) args[0]) { m_painteffects[StandardTerrainEffects.Revert] = new WeatherSphere(); m_painteffects[StandardTerrainEffects.Flatten] = new OlsenSphere(); m_painteffects[StandardTerrainEffects.Smooth] = new ErodeSphere(); } else { InstallDefaultEffects(); } } private void InterfaceRunPluginEffect(Object[] args) { if ((string) args[0] == "list") { m_log.Info("List of loaded plugins"); foreach (KeyValuePair<string, ITerrainEffect> kvp in m_plugineffects) { m_log.Info(kvp.Key); } return; } if ((string) args[0] == "reload") { LoadPlugins(); return; } if (m_plugineffects.ContainsKey((string) args[0])) { m_plugineffects[(string) args[0]].RunEffect(m_channel); CheckForTerrainUpdates(); } else { m_log.Warn("No such plugin effect loaded."); } } private void InstallInterfaces() { // Load / Save string supportedFileExtensions = ""; foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders) supportedFileExtensions += " " + loader.Key + " (" + loader.Value + ")"; Command loadFromFileCommand = new Command("load", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadFile, "Loads a terrain from a specified file."); loadFromFileCommand.AddArgument("filename", "The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " + supportedFileExtensions, "String"); Command saveToFileCommand = new Command("save", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveFile, "Saves the current heightmap to a specified file."); saveToFileCommand.AddArgument("filename", "The destination filename for your heightmap, the file extension determines the format to save in. Supported extensions include: " + supportedFileExtensions, "String"); Command loadFromTileCommand = new Command("load-tile", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadTileFile, "Loads a terrain from a section of a larger file."); loadFromTileCommand.AddArgument("filename", "The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " + supportedFileExtensions, "String"); loadFromTileCommand.AddArgument("file width", "The width of the file in tiles", "Integer"); loadFromTileCommand.AddArgument("file height", "The height of the file in tiles", "Integer"); loadFromTileCommand.AddArgument("minimum X tile", "The X region coordinate of the first section on the file", "Integer"); loadFromTileCommand.AddArgument("minimum Y tile", "The Y region coordinate of the first section on the file", "Integer"); // Terrain adjustments Command fillRegionCommand = new Command("fill", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFillTerrain, "Fills the current heightmap with a specified value."); fillRegionCommand.AddArgument("value", "The numeric value of the height you wish to set your region to.", "Double"); Command elevateCommand = new Command("elevate", CommandIntentions.COMMAND_HAZARDOUS, InterfaceElevateTerrain, "Raises the current heightmap by the specified amount."); elevateCommand.AddArgument("amount", "The amount of height to add to the terrain in meters.", "Double"); Command lowerCommand = new Command("lower", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLowerTerrain, "Lowers the current heightmap by the specified amount."); lowerCommand.AddArgument("amount", "The amount of height to remove from the terrain in meters.", "Double"); Command multiplyCommand = new Command("multiply", CommandIntentions.COMMAND_HAZARDOUS, InterfaceMultiplyTerrain, "Multiplies the heightmap by the value specified."); multiplyCommand.AddArgument("value", "The value to multiply the heightmap by.", "Double"); Command bakeRegionCommand = new Command("bake", CommandIntentions.COMMAND_HAZARDOUS, InterfaceBakeTerrain, "Saves the current terrain into the regions revert map."); Command revertRegionCommand = new Command("revert", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRevertTerrain, "Loads the revert map terrain into the regions heightmap."); Command flipCommand = new Command("flip", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFlipTerrain, "Flips the current terrain about the X or Y axis"); flipCommand.AddArgument("direction", "[x|y] the direction to flip the terrain in", "String"); Command rescaleCommand = new Command("rescale", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRescaleTerrain, "Rescales the current terrain to fit between the given min and max heights"); rescaleCommand.AddArgument("min", "min terrain height after rescaling", "Double"); rescaleCommand.AddArgument("max", "max terrain height after rescaling", "Double"); // Debug Command showDebugStatsCommand = new Command("stats", CommandIntentions.COMMAND_STATISTICAL, InterfaceShowDebugStats, "Shows some information about the regions heightmap for debugging purposes."); Command experimentalBrushesCommand = new Command("newbrushes", CommandIntentions.COMMAND_HAZARDOUS, InterfaceEnableExperimentalBrushes, "Enables experimental brushes which replace the standard terrain brushes. WARNING: This is a debug setting and may be removed at any time."); experimentalBrushesCommand.AddArgument("Enabled?", "true / false - Enable new brushes", "Boolean"); //Plugins Command pluginRunCommand = new Command("effect", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRunPluginEffect, "Runs a specified plugin effect"); pluginRunCommand.AddArgument("name", "The plugin effect you wish to run, or 'list' to see all plugins", "String"); m_commander.RegisterCommand("load", loadFromFileCommand); m_commander.RegisterCommand("load-tile", loadFromTileCommand); m_commander.RegisterCommand("save", saveToFileCommand); m_commander.RegisterCommand("fill", fillRegionCommand); m_commander.RegisterCommand("elevate", elevateCommand); m_commander.RegisterCommand("lower", lowerCommand); m_commander.RegisterCommand("multiply", multiplyCommand); m_commander.RegisterCommand("bake", bakeRegionCommand); m_commander.RegisterCommand("revert", revertRegionCommand); m_commander.RegisterCommand("newbrushes", experimentalBrushesCommand); m_commander.RegisterCommand("stats", showDebugStatsCommand); m_commander.RegisterCommand("effect", pluginRunCommand); m_commander.RegisterCommand("flip", flipCommand); m_commander.RegisterCommand("rescale", rescaleCommand); // Add this to our scene so scripts can call these functions m_scene.RegisterModuleCommander(m_commander); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Text; using Xunit; namespace System.Text.EncodingTests { // Encoding.GetChars(byte[],Int32,Int32,char[],Int32) public class EncodingGetChars3 { #region PositiveTest [Fact] public void PosTest1() { byte[] bytes = new byte[0]; Encoding myEncode = Encoding.GetEncoding("utf-16"); int byteIndex = 0; int bytecount = 0; char[] chars = new char[] { TestLibrary.Generator.GetChar(-55) }; int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0); Assert.Equal(0, intVal); Assert.Equal(1, chars.Length); } [Fact] public void PosTest2() { string myStr = "za\u0306\u01fd\u03b2"; Encoding myEncode = Encoding.GetEncoding("utf-16"); byte[] bytes = myEncode.GetBytes(myStr); int byteIndex = 0; int bytecount = 0; char[] chars = new char[] { TestLibrary.Generator.GetChar(-55) }; int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0); Assert.Equal(0, intVal); Assert.Equal(1, chars.Length); } [Fact] public void PosTest3() { string myStr = "za\u0306\u01fd\u03b2"; Encoding myEncode = Encoding.GetEncoding("utf-16"); byte[] bytes = myEncode.GetBytes(myStr); int byteIndex = 0; int bytecount = bytes.Length; char[] chars = new char[myStr.Length]; int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0); Assert.Equal(myStr.Length, intVal); Assert.Equal(myStr.Length, chars.Length); } [Fact] public void PosTest4() { string myStr = "za\u0306\u01fd\u03b2"; Encoding myEncode = Encoding.GetEncoding("utf-16"); byte[] bytes = myEncode.GetBytes(myStr); int byteIndex = 0; int bytecount = bytes.Length; char[] chars = new char[myStr.Length + myStr.Length]; int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, myStr.Length - 1); string subchars = null; for (int i = 0; i < myStr.Length - 1; i++) { subchars += chars[i].ToString(); } Assert.Equal(myStr.Length, intVal); Assert.Equal("\0\0\0\0", subchars); } [Fact] public void PosTest5() { string myStr = "za\u0306\u01fd\u03b2"; Encoding myEncode = Encoding.GetEncoding("utf-16"); byte[] bytes = myEncode.GetBytes(myStr); int byteIndex = 0; int bytecount = bytes.Length - 2; char[] chars = new char[myStr.Length - 1]; int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0); string strVal = new string(chars); Assert.Equal((myStr.Length - 1), intVal); Assert.Equal("za\u0306\u01fd", strVal); } #endregion #region NegativeTest // NegTest1:the byte array is null [Fact] public void NegTest1() { byte[] bytes = null; Encoding myEncode = Encoding.GetEncoding("utf-16"); int byteIndex = 0; int bytecount = 0; char[] chars = new char[0]; Assert.Throws<ArgumentNullException>(() => { int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0); }); } // NegTest2:the char array is null [Fact] public void NegTest2() { byte[] bytes = new byte[0]; Encoding myEncode = Encoding.GetEncoding("utf-16"); int byteIndex = 0; int bytecount = 0; char[] chars = null; Assert.Throws<ArgumentNullException>(() => { int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0); }); } // NegTest3:the char array has no enough capacity to hold the chars [Fact] public void NegTest3() { string myStr = "helloworld"; Encoding myEncode = Encoding.GetEncoding("utf-16"); byte[] bytes = myEncode.GetBytes(myStr); int byteIndex = 0; int bytecount = bytes.Length; char[] chars = new char[0]; Assert.Throws<ArgumentException>(() => { int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0); }); } // NegTest4:the byteIndex is less than zero [Fact] public void NegTest4() { string myStr = "helloworld"; Encoding myEncode = Encoding.GetEncoding("utf-16"); byte[] bytes = myEncode.GetBytes(myStr); int byteIndex = -1; int bytecount = bytes.Length; char[] chars = new char[myStr.Length]; Assert.Throws<ArgumentOutOfRangeException>(() => { int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0); }); } // NegTest5:the bytecount is less than zero [Fact] public void NegTest5() { string myStr = "helloworld"; Encoding myEncode = Encoding.GetEncoding("utf-16"); byte[] bytes = myEncode.GetBytes(myStr); int byteIndex = 0; int bytecount = -1; char[] chars = new char[myStr.Length]; Assert.Throws<ArgumentOutOfRangeException>(() => { int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0); }); } // NegTest6:the charIndex is less than zero [Fact] public void NegTest6() { string myStr = "helloworld"; Encoding myEncode = Encoding.GetEncoding("utf-16"); byte[] bytes = myEncode.GetBytes(myStr); int byteIndex = 0; int bytecount = bytes.Length; char[] chars = new char[myStr.Length]; Assert.Throws<ArgumentOutOfRangeException>(() => { int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, -1); }); } // NegTest7:the charIndex is not valid index in chars array [Fact] public void NegTest7() { string myStr = "helloworld"; Encoding myEncode = Encoding.GetEncoding("utf-16"); byte[] bytes = myEncode.GetBytes(myStr); int byteIndex = 0; int bytecount = bytes.Length; char[] chars = new char[myStr.Length]; Assert.Throws<ArgumentOutOfRangeException>(() => { int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, myStr.Length + 1); }); } // NegTest8:the byteIndex and bytecount do not denote valid range of the bytes array [Fact] public void NegTest8() { string myStr = "helloworld"; Encoding myEncode = Encoding.GetEncoding("utf-16"); byte[] bytes = myEncode.GetBytes(myStr); int byteIndex = 0; int bytecount = bytes.Length + 1; char[] chars = new char[myStr.Length]; Assert.Throws<ArgumentOutOfRangeException>(() => { int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, myStr.Length + 1); }); } #endregion } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using ASC.Common.Data; using ASC.Common.Data.Sql; using ASC.Common.Data.Sql.Expressions; using ASC.Mail.Core.Dao.Interfaces; using ASC.Mail.Core.DbSchema; using ASC.Mail.Core.DbSchema.Interfaces; using ASC.Mail.Core.DbSchema.Tables; using ASC.Mail.Core.Entities; namespace ASC.Mail.Core.Dao { public class UserFolderXMailDao : BaseDao, IUserFolderXMailDao { protected static ITable table = new MailTableFactory().Create<UserFoldertXMailTable>(); protected string CurrentUserId { get; private set; } public UserFolderXMailDao(IDbManager dbManager, int tenant, string user) : base(table, dbManager, tenant) { CurrentUserId = user; } public UserFolderXMail Get(int mailId) { var query = Query() .Where(UserFoldertXMailTable.Columns.Tenant, Tenant) .Where(UserFoldertXMailTable.Columns.User, CurrentUserId) .Where(UserFoldertXMailTable.Columns.MailId, mailId); var result = Db.ExecuteList(query) .ConvertAll(ToUserFolderXMail) .SingleOrDefault(); return result; } public List<UserFolderXMail> GetList(uint? folderId = null, List<int> mailIds = null) { var query = Query() .Where(UserFoldertXMailTable.Columns.Tenant, Tenant) .Where(UserFoldertXMailTable.Columns.User, CurrentUserId); if (folderId.HasValue) { query.Where(UserFoldertXMailTable.Columns.FolderId, folderId.Value); } if (mailIds != null && mailIds.Any()) { query.Where(Exp.In(UserFoldertXMailTable.Columns.MailId, mailIds)); } var list = Db.ExecuteList(query) .ConvertAll(ToUserFolderXMail); return list; } public List<int> GetMailIds(uint folderId) { var query = new SqlQuery(UserFoldertXMailTable.TABLE_NAME) .Select(UserFoldertXMailTable.Columns.MailId) .Where(UserFoldertXMailTable.Columns.Tenant, Tenant) .Where(UserFoldertXMailTable.Columns.User, CurrentUserId) .Where(UserFoldertXMailTable.Columns.FolderId, folderId); var list = Db.ExecuteList(query) .ConvertAll(r => Convert.ToInt32(r[0])); return list; } private delegate SqlInsert CreateInsertDelegate(); public void SetMessagesFolder(IEnumerable<int> messageIds, uint folderId) { var idMessages = messageIds as IList<int> ?? messageIds.ToList(); if (!idMessages.Any()) return; CreateInsertDelegate createInsertQuery = () => new SqlInsert(UserFoldertXMailTable.TABLE_NAME) .IgnoreExists(true) .InColumns(UserFoldertXMailTable.Columns.Tenant, UserFoldertXMailTable.Columns.User, UserFoldertXMailTable.Columns.MailId, UserFoldertXMailTable.Columns.FolderId); var insertQuery = createInsertQuery(); int i, messagessLen; for (i = 0, messagessLen = idMessages.Count; i < messagessLen; i++) { var messageId = idMessages[i]; insertQuery .Values(Tenant, CurrentUserId, messageId, folderId); if ((i % 100 != 0 || i == 0) && i + 1 != messagessLen) continue; Db.ExecuteNonQuery(insertQuery); insertQuery = createInsertQuery(); } } public int Save(UserFolderXMail item) { var query = new SqlInsert(UserFoldertXMailTable.TABLE_NAME, true) .InColumnValue(UserFoldertXMailTable.Columns.Tenant, item.Tenant) .InColumnValue(UserFoldertXMailTable.Columns.User, item.User) .InColumnValue(UserFoldertXMailTable.Columns.MailId, item.MailId) .InColumnValue(UserFoldertXMailTable.Columns.FolderId, item.FolderId); var result = Db.ExecuteNonQuery(query); return result; } public int Remove(int? mailId = null, uint? folderId = null) { var query = new SqlDelete(UserFoldertXMailTable.TABLE_NAME) .Where(UserFoldertXMailTable.Columns.Tenant, Tenant) .Where(UserFoldertXMailTable.Columns.User, CurrentUserId); if (mailId.HasValue) { query.Where(UserFoldertXMailTable.Columns.MailId, mailId.Value); } if (folderId.HasValue) { query.Where(UserFoldertXMailTable.Columns.FolderId, folderId.Value); } var result = Db.ExecuteNonQuery(query); return result; } public int Remove(List<int> mailIds) { var query = new SqlDelete(UserFoldertXMailTable.TABLE_NAME) .Where(UserFoldertXMailTable.Columns.Tenant, Tenant) .Where(UserFoldertXMailTable.Columns.User, CurrentUserId) .Where(Exp.In(UserFoldertXMailTable.Columns.MailId, mailIds)); var result = Db.ExecuteNonQuery(query); return result; } private static readonly string QueryDeleteFormat = string.Format( "delete t from {0} t inner join {1} m " + "on t.{2} = m.{3} and t.{4} = m.{5} and t.{6} = m.{7} " + "where m.{8} = @mailbox_id and m.{5} = @tenant and m.{7} = @user", UserFoldertXMailTable.TABLE_NAME, MailTable.TABLE_NAME, UserFoldertXMailTable.Columns.MailId, MailTable.Columns.Id, UserFoldertXMailTable.Columns.Tenant, MailTable.Columns.Tenant, UserFoldertXMailTable.Columns.User, MailTable.Columns.User, MailTable.Columns.MailboxId); public int RemoveByMailbox(int mailboxId) { return Db.ExecuteNonQuery(QueryDeleteFormat, new { mailbox_id = mailboxId, tenant = Tenant, user = CurrentUserId }); } protected UserFolderXMail ToUserFolderXMail(object[] r) { var folderXMail = new UserFolderXMail { Tenant = Convert.ToInt32(r[0]), User = Convert.ToString(r[1]), MailId = Convert.ToInt32(r[2]), FolderId = Convert.ToUInt32(r[3]), TimeModified = Convert.ToDateTime(r[4]) }; return folderXMail; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Text.Tests { public class EncodingGetChars1 { #region Positive Testcases [Fact] public void PosTest1() { PositiveTestString(Encoding.UTF8, "TestString", new byte[] { 84, 101, 115, 116, 83, 116, 114, 105, 110, 103 }, "00A"); } [Fact] public void PosTest2() { PositiveTestString(Encoding.UTF8, "", new byte[] { }, "00B"); } [Fact] public void PosTest3() { PositiveTestString(Encoding.UTF8, "FooBA\u0400R", new byte[] { 70, 111, 111, 66, 65, 208, 128, 82 }, "00C"); } [Fact] public void PosTest4() { PositiveTestString(Encoding.UTF8, "\u00C0nima\u0300l", new byte[] { 195, 128, 110, 105, 109, 97, 204, 128, 108 }, "00D"); } [Fact] public void PosTest5() { PositiveTestString(Encoding.UTF8, "Test\uD803\uDD75Test", new byte[] { 84, 101, 115, 116, 240, 144, 181, 181, 84, 101, 115, 116 }, "00E"); } [Fact] public void PosTest6() { PositiveTestString(Encoding.UTF8, "\0Te\nst\0\t\0T\u000Fest\0", new byte[] { 0, 84, 101, 10, 115, 116, 0, 9, 0, 84, 15, 101, 115, 116, 0 }, "00F"); } [Fact] public void PosTest7() { PositiveTestString(Encoding.UTF8, "\uFFFDTest\uFFFD\uFFFD\u0130\uFFFDTest\uFFFD", new byte[] { 196, 84, 101, 115, 116, 196, 196, 196, 176, 176, 84, 101, 115, 116, 176 }, "00G"); } [Fact] public void PosTest8() { PositiveTestString(Encoding.GetEncoding("utf-8"), "TestTest", new byte[] { 84, 101, 115, 116, 84, 101, 115, 116 }, "00H"); } [Fact] public void PosTest9() { PositiveTestString(Encoding.GetEncoding("utf-8"), "\uFFFD", new byte[] { 176 }, "00I"); } [Fact] public void PosTest10() { PositiveTestString(Encoding.GetEncoding("utf-8"), "\uFFFD", new byte[] { 196 }, "00J"); } [Fact] public void PosTest11() { PositiveTestString(Encoding.GetEncoding("utf-8"), "\uD803\uDD75\uD803\uDD75\uD803\uDD75", new byte[] { 240, 144, 181, 181, 240, 144, 181, 181, 240, 144, 181, 181 }, "00K"); } [Fact] public void PosTest12() { PositiveTestString(Encoding.GetEncoding("utf-8"), "\u0130", new byte[] { 196, 176 }, "00L"); } [Fact] public void PosTest13() { PositiveTestString(Encoding.GetEncoding("utf-8"), "\uFFFD\uD803\uDD75\uD803\uDD75\uFFFD\uFFFD", new byte[] { 240, 240, 144, 181, 181, 240, 144, 181, 181, 240, 144, 240 }, "0A2"); } [Fact] public void PosTest14() { PositiveTestString(Encoding.Unicode, "TestString\uFFFD", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 83, 0, 116, 0, 114, 0, 105, 0, 110, 0, 103, 0, 45 }, "00A3"); } [Fact] public void PosTest15() { PositiveTestString(Encoding.Unicode, "", new byte[] { }, "00B3"); } [Fact] public void PosTest16() { PositiveTestString(Encoding.Unicode, "FooBA\u0400R", new byte[] { 70, 0, 111, 0, 111, 0, 66, 0, 65, 0, 0, 4, 82, 0 }, "00C3"); } [Fact] public void PosTest17() { PositiveTestString(Encoding.Unicode, "\u00C0nima\u0300l", new byte[] { 192, 0, 110, 0, 105, 0, 109, 0, 97, 0, 0, 3, 108, 0 }, "00D3"); } [Fact] public void PosTest18() { PositiveTestString(Encoding.Unicode, "Test\uD803\uDD75Test", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 3, 216, 117, 221, 84, 0, 101, 0, 115, 0, 116, 0 }, "00E3"); } [Fact] public void PosTest19() { PositiveTestString(Encoding.Unicode, "\0Te\nst\0\t\0T\u000Fest\0", new byte[] { 0, 0, 84, 0, 101, 0, 10, 0, 115, 0, 116, 0, 0, 0, 9, 0, 0, 0, 84, 0, 15, 0, 101, 0, 115, 0, 116, 0, 0, 0 }, "00F3"); } [Fact] public void PosTest20() { PositiveTestString(Encoding.GetEncoding("utf-16"), "TestTest", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 0 }, "00G3"); } [Fact] public void PosTest21() { PositiveTestString(Encoding.GetEncoding("utf-16"), "TestTest\uFFFD", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 0, 117, 221 }, "00H3"); } [Fact] public void PosTest22() { PositiveTestString(Encoding.GetEncoding("utf-16"), "TestTest\uFFFD", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 0, 3, 216 }, "00I3"); } [Fact] public void PosTest23() { PositiveTestString(Encoding.GetEncoding("utf-16"), "\uFFFD\uFFFD", new byte[] { 3, 216, 84 }, "00J3"); } [Fact] public void PosTest24() { PositiveTestString(Encoding.GetEncoding("utf-16"), "\uD803\uDD75\uD803\uDD75\uD803\uDD75", new byte[] { 3, 216, 117, 221, 3, 216, 117, 221, 3, 216, 117, 221 }, "00K3"); } [Fact] public void PosTest25() { PositiveTestString(Encoding.GetEncoding("utf-16"), "\u0130", new byte[] { 48, 1 }, "00L3"); } [Fact] public void PosTest26() { PositiveTestString(Encoding.GetEncoding("utf-16"), "\uD803\uDD75\uD803\uDD75", new byte[] { 3, 216, 117, 221, 3, 216, 117, 221 }, "0A23"); } [Fact] public void PosTest27() { PositiveTestString(Encoding.BigEndianUnicode, "TestString\uFFFD", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 83, 0, 116, 0, 114, 0, 105, 0, 110, 0, 103, 0 }, "00A4"); } [Fact] public void PosTest28() { PositiveTestString(Encoding.BigEndianUnicode, "", new byte[] { }, "00B4"); } [Fact] public void PosTest29() { PositiveTestString(Encoding.BigEndianUnicode, "FooBA\u0400R\uFFFD", new byte[] { 0, 70, 0, 111, 0, 111, 0, 66, 0, 65, 4, 0, 0, 82, 70 }, "00C4"); } [Fact] public void PosTest30() { PositiveTestString(Encoding.BigEndianUnicode, "\u00C0nima\u0300l", new byte[] { 0, 192, 0, 110, 0, 105, 0, 109, 0, 97, 3, 0, 0, 108 }, "00D4"); } [Fact] public void PosTest31() { PositiveTestString(Encoding.BigEndianUnicode, "Test\uD803\uDD75Test", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 216, 3, 221, 117, 0, 84, 0, 101, 0, 115, 0, 116 }, "00E4"); } [Fact] public void PosTest32() { PositiveTestString(Encoding.BigEndianUnicode, "\0Te\nst\0\t\0T\u000Fest\0\uFFFD", new byte[] { 0, 0, 0, 84, 0, 101, 0, 10, 0, 115, 0, 116, 0, 0, 0, 9, 0, 0, 0, 84, 0, 15, 0, 101, 0, 115, 0, 116, 0, 0, 0 }, "00F4"); } [Fact] public void PosTest33() { PositiveTestString(Encoding.BigEndianUnicode, "TestTest", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116 }, "00G4"); } [Fact] public void PosTest34() { PositiveTestString(Encoding.BigEndianUnicode, "TestTest\uFFFD", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 221, 117 }, "00H4"); } [Fact] public void PosTest35() { PositiveTestString(Encoding.GetEncoding("UTF-16BE"), "TestTest\uFFFD", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 216, 3 }, "00I4"); } [Fact] public void PosTest36() { PositiveTestString(Encoding.GetEncoding("UTF-16BE"), "\uFFFD\uFFFD", new byte[] { 216, 3, 48 }, "00J4"); } [Fact] public void PosTest37() { PositiveTestString(Encoding.GetEncoding("UTF-16BE"), "\uD803\uDD75\uD803\uDD75\uD803\uDD75", new byte[] { 216, 3, 221, 117, 216, 3, 221, 117, 216, 3, 221, 117 }, "00K4"); } [Fact] public void PosTest38() { PositiveTestString(Encoding.GetEncoding("UTF-16BE"), "\u0130", new byte[] { 1, 48 }, "00L4"); } [Fact] public void PosTest39() { PositiveTestString(Encoding.GetEncoding("UTF-16BE"), "\uD803\uDD75\uD803\uDD75", new byte[] { 216, 3, 221, 117, 216, 3, 221, 117 }, "0A24"); } #endregion #region Negative Testcases [Fact] public void NegTest1() { NegativeTestChars<ArgumentNullException>(new UTF8Encoding(), null, "00O"); } [Fact] public void NegTest2() { NegativeTestChars<ArgumentNullException>(new UnicodeEncoding(), null, "00O3"); } [Fact] public void NegTest3() { NegativeTestChars<ArgumentNullException>(new UnicodeEncoding(true, false), null, "00O4"); } [Fact] public void NegTest4() { NegativeTestChars2<ArgumentNullException>(new UTF8Encoding(), null, 0, 0, "00P"); } [Fact] public void NegTest5() { NegativeTestChars2<ArgumentOutOfRangeException>(new UTF8Encoding(), new byte[] { 0, 0 }, -1, 1, "00P"); } [Fact] public void NegTest6() { NegativeTestChars2<ArgumentOutOfRangeException>(new UTF8Encoding(), new byte[] { 0, 0 }, 1, -1, "00Q"); } [Fact] public void NegTest7() { NegativeTestChars2<ArgumentOutOfRangeException>(new UTF8Encoding(), new byte[] { 0, 0 }, 0, 10, "00R"); } [Fact] public void NegTest8() { NegativeTestChars2<ArgumentOutOfRangeException>(new UTF8Encoding(), new byte[] { 0, 0 }, 3, 0, "00S"); } [Fact] public void NegTest9() { NegativeTestChars2<ArgumentNullException>(new UnicodeEncoding(), null, 0, 0, "00P3"); } [Fact] public void NegTest10() { NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(), new byte[] { 0, 0 }, -1, 1, "00P3"); } [Fact] public void NegTest11() { NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(), new byte[] { 0, 0 }, 1, -1, "00Q3"); } [Fact] public void NegTest12() { NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(), new byte[] { 0, 0 }, 0, 10, "00R3"); } [Fact] public void NegTest13() { NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(), new byte[] { 0, 0 }, 3, 0, "00S3"); } [Fact] public void NegTest14() { NegativeTestChars2<ArgumentNullException>(new UnicodeEncoding(true, false), null, 0, 0, "00P4"); } [Fact] public void NegTest15() { NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(true, false), new byte[] { 0, 0 }, -1, 1, "00P4"); } [Fact] public void NegTest16() { NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(true, false), new byte[] { 0, 0 }, 1, -1, "00Q4"); } [Fact] public void NegTest17() { NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(true, false), new byte[] { 0, 0 }, 0, 10, "00R4"); } [Fact] public void NegTest18() { NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(true, false), new byte[] { 0, 0 }, 3, 0, "00S4"); } private static char[] s_output = new char[20]; [Fact] public void NegTest19() { NegativeTestChars3<ArgumentNullException>(Encoding.UTF8, null, 0, 0, s_output, 0, "00T"); } [Fact] public void NegTest20() { NegativeTestChars3<ArgumentNullException>(Encoding.UTF8, new byte[] { 0, 0 }, 0, 0, null, 0, "00U"); } [Fact] public void NegTest21() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.UTF8, new byte[] { 0, 0 }, -1, 0, s_output, 0, "00V"); } [Fact] public void NegTest22() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.UTF8, new byte[] { 0, 0 }, 0, 0, s_output, -1, "00W"); } [Fact] public void NegTest23() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.UTF8, new byte[] { 0, 0 }, 3, 0, s_output, 0, "00X"); } [Fact] public void NegTest24() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.UTF8, new byte[] { 0, 0 }, 0, 0, s_output, 21, "00Y"); } [Fact] public void NegTest25() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.UTF8, new byte[] { 0, 0 }, 0, 10, s_output, 0, "00Z"); } [Fact] public void NegTest26() { NegativeTestChars3<ArgumentException>(Encoding.UTF8, new byte[] { 0, 0 }, 0, 2, s_output, 20, "0A0"); } [Fact] public void NegTest27() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.UTF8, new byte[] { 0, 0 }, 0, -1, s_output, 0, "0A1"); } [Fact] public void NegTest28() { NegativeTestChars3<ArgumentNullException>(Encoding.Unicode, null, 0, 0, s_output, 0, "00T3"); } [Fact] public void NegTest29() { NegativeTestChars3<ArgumentNullException>(Encoding.Unicode, new byte[] { 0, 0 }, 0, 0, null, 0, "00U3"); } [Fact] public void NegTest30() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.Unicode, new byte[] { 0, 0 }, -1, 0, s_output, 0, "00V3"); } [Fact] public void NegTest31() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.Unicode, new byte[] { 0, 0 }, 0, 0, s_output, -1, "00W3"); } [Fact] public void NegTest32() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.Unicode, new byte[] { 0, 0 }, 3, 0, s_output, 0, "00X3"); } [Fact] public void NegTest33() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.Unicode, new byte[] { 0, 0 }, 0, 0, s_output, 21, "00Y3"); } [Fact] public void NegTest34() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.Unicode, new byte[] { 0, 0 }, 0, 10, s_output, 0, "00Z3"); } [Fact] public void NegTest35() { NegativeTestChars3<ArgumentException>(Encoding.Unicode, new byte[] { 0, 0 }, 0, 2, s_output, 20, "0A03"); } [Fact] public void NegTest36() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.Unicode, new byte[] { 0, 0 }, 0, -1, s_output, 0, "0A13"); } [Fact] public void NegTest37() { NegativeTestChars3<ArgumentNullException>(Encoding.BigEndianUnicode, null, 0, 0, s_output, 0, "00T4"); } [Fact] public void NegTest38() { NegativeTestChars3<ArgumentNullException>(Encoding.BigEndianUnicode, new byte[] { 0, 0 }, 0, 0, null, 0, "00U4"); } [Fact] public void NegTest39() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.BigEndianUnicode, new byte[] { 0, 0 }, -1, 0, s_output, 0, "00V4"); } [Fact] public void NegTest40() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.BigEndianUnicode, new byte[] { 0, 0 }, 0, 0, s_output, -1, "00W4"); } [Fact] public void NegTest41() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.BigEndianUnicode, new byte[] { 0, 0 }, 3, 0, s_output, 0, "00X4"); } [Fact] public void NegTest42() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.BigEndianUnicode, new byte[] { 0, 0 }, 0, 0, s_output, 21, "00Y4"); } [Fact] public void NegTest43() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.BigEndianUnicode, new byte[] { 0, 0 }, 0, 10, s_output, 0, "00Z4"); } [Fact] public void NegTest44() { NegativeTestChars3<ArgumentException>(Encoding.BigEndianUnicode, new byte[] { 0, 0 }, 0, 2, s_output, 20, "0A04"); } [Fact] public void NegTest45() { NegativeTestChars3<ArgumentOutOfRangeException>(Encoding.BigEndianUnicode, new byte[] { 0, 0 }, 0, -1, s_output, 0, "0A14"); } #endregion public void PositiveTestString(Encoding enc, string expected, byte[] bytes, string id) { char[] chars = enc.GetChars(bytes); string str = new string(chars); Assert.Equal(expected, str); } public void NegativeTestChars<T>(Encoding enc, byte[] bytes, string id) where T : Exception { Assert.Throws<T>(() => { char[] chars = enc.GetChars(bytes); string str = new string(chars); }); } public void NegativeTestChars2<T>(Encoding enc, byte[] bytes, int index, int count, string id) where T : Exception { Assert.Throws<T>(() => { char[] chars = enc.GetChars(bytes, index, count); string str = new string(chars); }); } public void NegativeTestChars3<T>(Encoding enc, byte[] bytes, int index, int count, char[] chars, int bIndex, string id) where T : Exception { Assert.Throws<T>(() => { int output = enc.GetChars(bytes, index, count, chars, bIndex); string str = new string(chars); }); } } }
using System; using System.IO; using System.Xml; using System.Collections; using Weborb; using Weborb.Writer; using Weborb.Util; using Weborb.Message; namespace Weborb.Writer.Amf { public class AmfFormatter : IProtocolFormatter { private FlashorbBinaryWriter writer; private ObjectSerializer objectSerializer; private ReferenceCache referenceCache; protected MemoryStream stream; // this is used for extraction of the body for caching purpuses protected long beginSelectBytesIndex; public AmfFormatter() { stream = new MemoryStream(); writer = new FlashorbBinaryWriter( stream ); objectSerializer = new ObjectSerializer(); referenceCache = new ReferenceCache(); } #region IProtocolFormatter Members internal override void BeginSelectCacheObject() { beginSelectBytesIndex = stream.Length; } internal override object EndSelectCacheObject() { if( stream.Length < beginSelectBytesIndex ) return new byte[ 0 ]; byte[] res = new byte[ stream.Length - beginSelectBytesIndex ]; stream.Position = (int) beginSelectBytesIndex; stream.Read( res, 0, res.Length ); return res; } internal override void WriteCachedObject( object cached ) { writer.Write( (byte[]) cached ); } public override ITypeWriter getWriter( Type type ) { return null; } public override ReferenceCache GetReferenceCache() { return referenceCache; } public override void ResetReferenceCache() { referenceCache.Reset(); } public override void DirectWriteBytes( byte[] b ) { writer.Write( b ); } public override void DirectWriteString( string str ) { UTF8Util.writeUTF( writer, str ); } public override void DirectWriteInt( int i ) { writer.Write( i ); } public override void DirectWriteBoolean( bool b ) { writer.Write( b ); } public override void DirectWriteShort( int s ) { writer.WriteShort( s ); } public override void WriteMessageVersion( float version ) { writer.WriteShort( (int) version ); } public override void BeginWriteArray( int length ) { writer.Write( (byte) Datatypes.ARRAY_DATATYPE_V1 ); writer.WriteInt( length ); } public override void EndWriteArray() { } public override void WriteBoolean( bool b ) { writer.Write( (byte) Datatypes.BOOLEAN_DATATYPE_V1 ); writer.Write( b ); } public override void WriteDate( DateTime datetime ) { writer.Write( (byte) Datatypes.DATE_DATATYPE_V1 ); DateTime olddate = new DateTime( 1970, 1, 1 ); #if( FULL_BUILD || PURE_CLIENT_LIB) // get the offset of the time zone the server is in double localTimezoneOffset = TimeZoneInfo.Local.GetUtcOffset( olddate ).TotalMilliseconds; // convert 1/1/1970 12AM to UTC olddate = olddate.ToUniversalTime(); #else // get the offset of the time zone the server is in double localTimezoneOffset = TimeZoneInfo.Local.GetUtcOffset( olddate ).TotalMilliseconds; // convert 1/1/1970 12AM to UTC olddate = TimeZoneInfo.ConvertTime( olddate, TimeZoneInfo.Utc ); #endif // bring it back to 12AM olddate = olddate.AddMilliseconds( localTimezoneOffset ); datetime = datetime.ToUniversalTime(); TimeSpan span = datetime.Subtract( olddate ); long totalMs = ( (long) span.TotalMilliseconds ); writer.WriteDouble( totalMs ); writer.WriteShort( (short) 0 ); } public override void BeginWriteObjectMap( int size ) { writer.Write( (byte) Datatypes.OBJECTARRAY_DATATYPE_V1 ); writer.WriteInt( size ); } public override void EndWriteObjectMap() { writer.Write( (byte) 0 ); writer.Write( (byte) 0 ); writer.Write( (byte) Datatypes.ENDOFOBJECT_DATATYPE_V1 ); } public override void WriteFieldName( string s ) { UTF8Util.writeUTF( writer, s ); } public override void WriteNull() { writer.Write( (byte) Datatypes.NULL_DATATYPE_V1 ); } public override void WriteInteger( int number ) { writer.Write( (byte) Datatypes.NUMBER_DATATYPE_V1 ); writer.WriteDouble( number ); } public override void WriteDouble( double number ) { writer.Write( (byte) Datatypes.NUMBER_DATATYPE_V1 ); writer.WriteDouble( number ); } public override void BeginWriteNamedObject( string objectName, int fieldCound ) { writer.Write( (byte) Datatypes.NAMEDOBJECT_DATATYPE_V1 ); UTF8Util.writeUTF( writer, objectName ); } public override void EndWriteNamedObject() { writer.Write( (byte) 0 ); writer.Write( (byte) 0 ); writer.Write( (byte) Datatypes.ENDOFOBJECT_DATATYPE_V1 ); } public override void BeginWriteObject( int fieldCound ) { writer.Write( (byte) Datatypes.OBJECT_DATATYPE_V1 ); } public override void EndWriteObject() { writer.Write( (byte) 0 ); writer.Write( (byte) 0 ); writer.Write( (byte) Datatypes.ENDOFOBJECT_DATATYPE_V1 ); } public override void WriteDateReference( int refID ) { writer.Write( (byte) Datatypes.POINTER_DATATYPE_V1 ); writer.WriteShort( (ushort) refID ); } public override void WriteArrayReference( int refID ) { writer.Write( (byte) Datatypes.POINTER_DATATYPE_V1 ); writer.WriteShort( (ushort) refID ); } public override void WriteByteArray( byte[] array ) { writer.Write( (byte) Datatypes.V3_DATATYPE ); writer.Write( (byte) Datatypes.BYTEARRAY_DATATYPE_V3 ); writer.WriteVarInt( array.Length << 1 | 0x1 ); writer.Write( array ); } public override void WriteObjectReference( int refID ) { writer.Write( (byte) Datatypes.POINTER_DATATYPE_V1 ); writer.WriteShort( (ushort) refID ); } public override void WriteStringReference( int refID ) { writer.Write( (byte) Datatypes.POINTER_DATATYPE_V1 ); writer.WriteShort( (ushort) refID ); } public override void WriteString( string s ) { writer.Write( getStringBytes( s ) ); } #if (FULL_BUILD) public override void WriteXML( XmlNode document ) { writer.Write( (byte)Datatypes.PARSEDXML_DATATYPE_V1 ); writer.Write( getEncoded( document.OuterXml ) ); } #endif public override ProtocolBytes GetBytes() { ProtocolBytes protocolBytes = new ProtocolBytes(); protocolBytes.length = (int) stream.Length; protocolBytes.bytes = stream.GetBuffer(); stream.Close(); writer.Close(); return protocolBytes; } public override void Cleanup() { writer.Close(); } public override string GetContentType() { return "application/x-amf"; } public override IObjectSerializer GetObjectSerializer() { return objectSerializer; } #endregion private byte[] getEncoded( string str ) { int strlen = str.Length; uint utflen = 0; char[] charr = str.ToCharArray(); int count = 0; for( int i = 0; i < strlen; i++ ) { int c = charr[ i ]; if( c >= 1 && c <= 127 ) utflen++; else if ( c > 2047 ) utflen += 3; else utflen += 2; } byte[] bytearr = new byte[ utflen + 4 ]; bytearr[ count++ ] = (byte) ( utflen >> 24 & 0xff ); bytearr[ count++ ] = (byte) ( utflen >> 16 & 0xff ); bytearr[ count++ ] = (byte) ( utflen >> 8 & 0xff ); bytearr[ count++ ] = (byte) ( utflen >> 0 & 0xff ); for( int i = 0; i < strlen; i++ ) { int c = charr[ i ]; if( c >= 1 && c <= 127 ) bytearr[ count++ ] = (byte) c; else if( c > 2047 ) { bytearr[ count++ ] = (byte) ( 0xe0 | c >> 12 & 0xf ); bytearr[ count++ ] = (byte) ( 0x80 | c >> 6 & 0x3f ); bytearr[ count++ ] = (byte) ( 0x80 | c >> 0 & 0x3f ); } else { bytearr[ count++ ] = (byte) ( 0xc0 | c >> 6 & 0x1f ); bytearr[ count++ ] = (byte) ( 0x80 | c >> 0 & 0x3f ); } } return bytearr; } public byte[] getStringBytes( String str ) { //TODO: this needs to be fixed and cleaned up if ( str.Equals( "System.Int32" ) ) str = "int"; int strlen = str.Length; uint utflen = 0; char[] charr = str.ToCharArray(); int count = 0; for( int i = 0; i < strlen; i++ ) { int c = charr[ i ]; if( c >= 1 && c <= 127 ) utflen++; else if( c > 2047 ) utflen += 3; else utflen += 2; } byte[] bytearr = new byte[ utflen + ( utflen <= 65535 ? 3 : 5 ) ]; bytearr[ count++ ] = utflen <= 65535 ? (byte) 2 : (byte) 12; if( utflen > 65535 ) { bytearr[ count++ ] = (byte) ( utflen >> 24 & 0xff ); bytearr[ count++ ] = (byte) ( utflen >> 16 & 0xff ); } bytearr[ count++ ] = (byte)( utflen >> 8 & 0xff ); bytearr[ count++ ] = (byte) ( utflen >> 0 & 0xff ); for( int i = 0; i < strlen; i++ ) { int c = charr[ i ]; if( c >= 1 && c <= 127 ) bytearr[ count++ ] = (byte)c; else if( c > 2047 ) { bytearr[ count++ ] = (byte) ( 0xe0 | c >> 12 & 0xf ); bytearr[ count++ ] = (byte) ( 0x80 | c >> 6 & 0x3f ); bytearr[ count++ ] = (byte) ( 0x80 | c >> 0 & 0x3f ); } else { bytearr[ count++ ] = (byte) ( 0xc0 | c >> 6 & 0x1f ); bytearr[ count++ ] = (byte) ( 0x80 | c >> 0 & 0x3f ); } } return bytearr; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using Lucene.Net.Support; using NUnit.Framework; namespace Lucene.Net.Util { [TestFixture] public class TestNumericUtils:LuceneTestCase { private class AnonymousClassLongRangeBuilder:NumericUtils.LongRangeBuilder { public AnonymousClassLongRangeBuilder(long lower, long upper, bool useBitSet, Lucene.Net.Util.OpenBitSet bits, System.Collections.IEnumerator neededBounds, System.Collections.IEnumerator neededShifts,TestNumericUtils enclosingInstance) { InitBlock(lower, upper, useBitSet, bits, neededBounds, neededShifts, enclosingInstance); } private void InitBlock(long lower, long upper, bool useBitSet, Lucene.Net.Util.OpenBitSet bits, System.Collections.IEnumerator neededBounds, System.Collections.IEnumerator neededShifts,TestNumericUtils enclosingInstance) { this.lower = lower; this.upper = upper; this.useBitSet = useBitSet; this.bits = bits; this.neededBounds = neededBounds; this.neededShifts = neededShifts; this.enclosingInstance = enclosingInstance; } private long lower; private long upper; private bool useBitSet; private Lucene.Net.Util.OpenBitSet bits; private System.Collections.IEnumerator neededBounds; private System.Collections.IEnumerator neededShifts; private TestNumericUtils enclosingInstance; public TestNumericUtils Enclosing_Instance { get { return enclosingInstance; } } //@Override public override void AddRange(long min, long max, int shift) { Assert.IsTrue(min >= lower && min <= upper && max >= lower && max <= upper, "min, max should be inside bounds"); if (useBitSet) for (long l = min; l <= max; l++) { Assert.IsFalse(bits.GetAndSet(l - lower), "ranges should not overlap"); // extra exit condition to prevent overflow on MAX_VALUE if (l == max) break; } if (neededBounds == null || neededShifts == null) return; // make unsigned longs for easier display and understanding min ^= unchecked((long) 0x8000000000000000L); max ^= unchecked((long) 0x8000000000000000L); //System.out.println("Long.valueOf(0x"+Long.toHexString(min>>>shift)+"L),Long.valueOf(0x"+Long.toHexString(max>>>shift)+"L)/*shift="+shift+"*/,"); neededShifts.MoveNext(); Assert.AreEqual(((Int32)neededShifts.Current), shift, "shift"); neededBounds.MoveNext(); unchecked { Assert.AreEqual((long)neededBounds.Current, Number.URShift(min, shift), "inner min bound"); neededBounds.MoveNext(); Assert.AreEqual((long)neededBounds.Current, Number.URShift(max, shift), "inner max bound"); } } } private class AnonymousClassIntRangeBuilder:NumericUtils.IntRangeBuilder { public AnonymousClassIntRangeBuilder(int lower, int upper, bool useBitSet, Lucene.Net.Util.OpenBitSet bits, IEnumerator<int> neededBounds, IEnumerator<int> neededShifts, TestNumericUtils enclosingInstance) { InitBlock(lower, upper, useBitSet, bits, neededBounds, neededShifts,enclosingInstance); } private void InitBlock(int lower, int upper, bool useBitSet, Lucene.Net.Util.OpenBitSet bits, IEnumerator<int> neededBounds, IEnumerator<int> neededShifts, TestNumericUtils enclosingInstance) { this.lower = lower; this.upper = upper; this.useBitSet = useBitSet; this.bits = bits; this.neededBounds = neededBounds; this.neededShifts = neededShifts; this.enclosingInstance = enclosingInstance; } private int lower; private int upper; private bool useBitSet; private Lucene.Net.Util.OpenBitSet bits; private IEnumerator<int> neededBounds; private IEnumerator<int> neededShifts; private TestNumericUtils enclosingInstance; public TestNumericUtils Enclosing_Instance { get { return enclosingInstance; } } //@Override public override void AddRange(int min, int max, int shift) { Assert.IsTrue(min >= lower && min <= upper && max >= lower && max <= upper, "min, max should be inside bounds"); if (useBitSet) for (int i = min; i <= max; i++) { Assert.IsFalse(bits.GetAndSet(i - lower), "ranges should not overlap"); // extra exit condition to prevent overflow on MAX_VALUE if (i == max) break; } if (neededBounds == null) return; // make unsigned ints for easier display and understanding min ^= unchecked((int) 0x80000000); max ^= unchecked((int) 0x80000000); neededShifts.MoveNext(); Assert.AreEqual(((int)neededShifts.Current), shift,"shift"); //System.out.println("new Integer(0x"+Integer.toHexString(min>>>shift)+"),new Integer(0x"+Integer.toHexString(max>>>shift)+"),"); neededBounds.MoveNext(); Assert.AreEqual(((System.Int32) neededBounds.Current), Number.URShift(min, shift), "inner min bound"); neededBounds.MoveNext(); Assert.AreEqual(((System.Int32) neededBounds.Current), Number.URShift(max, shift), "inner max bound"); } } [Test] public virtual void TestLongConversionAndOrdering() { // generate a series of encoded longs, each numerical one bigger than the one before System.String last = null; for (long l = - 100000L; l < 100000L; l++) { System.String act = NumericUtils.LongToPrefixCoded(l); if (last != null) { // test if smaller Assert.IsTrue(String.CompareOrdinal(last, act) < 0, "actual bigger than last"); } // test is back and forward conversion works Assert.AreEqual(l, NumericUtils.PrefixCodedToLong(act), "forward and back conversion should generate same long"); // next step last = act; } } [Test] public virtual void TestIntConversionAndOrdering() { // generate a series of encoded ints, each numerical one bigger than the one before System.String last = null; for (int i = - 100000; i < 100000; i++) { System.String act = NumericUtils.IntToPrefixCoded(i); if (last != null) { // test if smaller Assert.IsTrue(String.CompareOrdinal(last, act) < 0, "actual bigger than last"); } // test is back and forward conversion works Assert.AreEqual(i, NumericUtils.PrefixCodedToInt(act), "forward and back conversion should generate same int"); // next step last = act; } } [Test] public virtual void TestLongSpecialValues() { long[] vals = new long[]{System.Int64.MinValue, System.Int64.MinValue + 1, System.Int64.MinValue + 2, - 5003400000000L, - 4000L, - 3000L, - 2000L, - 1000L, - 1L, 0L, 1L, 10L, 300L, 50006789999999999L, System.Int64.MaxValue - 2, System.Int64.MaxValue - 1, System.Int64.MaxValue}; System.String[] prefixVals = new System.String[vals.Length]; for (int i = 0; i < vals.Length; i++) { prefixVals[i] = NumericUtils.LongToPrefixCoded(vals[i]); // check forward and back conversion Assert.AreEqual(vals[i], NumericUtils.PrefixCodedToLong(prefixVals[i]), "forward and back conversion should generate same long"); // test if decoding values as int fails correctly Assert.Throws<FormatException>(() => NumericUtils.PrefixCodedToInt(prefixVals[i]), "decoding a prefix coded long value as int should fail"); } // check sort order (prefixVals should be ascending) for (int i = 1; i < prefixVals.Length; i++) { Assert.IsTrue(String.CompareOrdinal(prefixVals[i - 1], prefixVals[i]) < 0, "check sort order"); } // check the prefix encoding, lower precision should have the difference to original value equal to the lower removed bits for (int i = 0; i < vals.Length; i++) { for (int j = 0; j < 64; j++) { long prefixVal = NumericUtils.PrefixCodedToLong(NumericUtils.LongToPrefixCoded(vals[i], j)); long mask = (1L << j) - 1L; Assert.AreEqual(vals[i] & mask, vals[i] - prefixVal, "difference between prefix val and original value for " + vals[i] + " with shift=" + j); } } } [Test] public virtual void TestIntSpecialValues() { int[] vals = new int[]{System.Int32.MinValue, System.Int32.MinValue + 1, System.Int32.MinValue + 2, - 64765767, - 4000, - 3000, - 2000, - 1000, - 1, 0, 1, 10, 300, 765878989, System.Int32.MaxValue - 2, System.Int32.MaxValue - 1, System.Int32.MaxValue}; System.String[] prefixVals = new System.String[vals.Length]; for (int i = 0; i < vals.Length; i++) { prefixVals[i] = NumericUtils.IntToPrefixCoded(vals[i]); // check forward and back conversion Assert.AreEqual(vals[i], NumericUtils.PrefixCodedToInt(prefixVals[i]), "forward and back conversion should generate same int"); // test if decoding values as long fails correctly Assert.Throws<FormatException>(() => NumericUtils.PrefixCodedToLong(prefixVals[i]), "decoding a prefix coded int value as long should fail"); } // check sort order (prefixVals should be ascending) for (int i = 1; i < prefixVals.Length; i++) { Assert.IsTrue(String.CompareOrdinal(prefixVals[i - 1], prefixVals[i]) < 0, "check sort order"); } // check the prefix encoding, lower precision should have the difference to original value equal to the lower removed bits for (int i = 0; i < vals.Length; i++) { for (int j = 0; j < 32; j++) { int prefixVal = NumericUtils.PrefixCodedToInt(NumericUtils.IntToPrefixCoded(vals[i], j)); int mask = (1 << j) - 1; Assert.AreEqual(vals[i] & mask, vals[i] - prefixVal, "difference between prefix val and original value for " + vals[i] + " with shift=" + j); } } } [Test] public virtual void TestDoubles() { double[] vals = new double[]{System.Double.NegativeInfinity, - 2.3e25, - 1.0e15, - 1.0, - 1.0e-1, - 1.0e-2, - 0.0, + 0.0, 1.0e-2, 1.0e-1, 1.0, 1.0e15, 2.3e25, System.Double.PositiveInfinity}; long[] longVals = new long[vals.Length]; // check forward and back conversion for (int i = 0; i < vals.Length; i++) { longVals[i] = NumericUtils.DoubleToSortableLong(vals[i]); Assert.IsTrue(vals[i].CompareTo(NumericUtils.SortableLongToDouble(longVals[i])) == 0, "forward and back conversion should generate same double"); } // check sort order (prefixVals should be ascending) for (int i = 1; i < longVals.Length; i++) { Assert.IsTrue(longVals[i - 1] < longVals[i], "check sort order"); } } [Test] public virtual void TestFloats() { float[] vals = new float[]{System.Single.NegativeInfinity, - 2.3e25f, - 1.0e15f, - 1.0f, - 1.0e-1f, - 1.0e-2f, - 0.0f, + 0.0f, 1.0e-2f, 1.0e-1f, 1.0f, 1.0e15f, 2.3e25f, System.Single.PositiveInfinity}; int[] intVals = new int[vals.Length]; // check forward and back conversion for (int i = 0; i < vals.Length; i++) { intVals[i] = NumericUtils.FloatToSortableInt(vals[i]); Assert.IsTrue(vals[i].CompareTo(NumericUtils.SortableIntToFloat(intVals[i])) == 0, "forward and back conversion should generate same double"); } // check sort order (prefixVals should be ascending) for (int i = 1; i < intVals.Length; i++) { Assert.IsTrue(intVals[i - 1] < intVals[i], "check sort order"); } } // INFO: Tests for trieCodeLong()/trieCodeInt() not needed because implicitely tested by range filter tests /// <summary>Note: The neededBounds iterator must be unsigned (easier understanding what's happening) </summary> internal virtual void AssertLongRangeSplit(long lower, long upper, int precisionStep, bool useBitSet, IEnumerator<long> neededBounds, IEnumerator<int> neededShifts) { OpenBitSet bits = useBitSet ? new OpenBitSet(upper - lower + 1) : null; NumericUtils.SplitLongRange( new AnonymousClassLongRangeBuilder(lower, upper, useBitSet, bits, neededBounds, neededShifts, this), precisionStep, lower, upper); if (useBitSet) { // after flipping all bits in the range, the cardinality should be zero bits.Flip(0, upper - lower + 1); Assert.IsTrue(bits.IsEmpty(), "The sub-range concenated should match the whole range"); } } /* LUCENE-2541: NumericRangeQuery errors with endpoints near long min and max values */ [Test] public void TestLongExtremeValues() { // upper end extremes AssertLongRangeSplit(long.MaxValue, long.MaxValue, 1, true, new ulong[] { 0xffffffffffffffffL, 0xffffffffffffffffL }.Cast<long>().GetEnumerator(), new int[] { 0 }.AsEnumerable().GetEnumerator()); AssertLongRangeSplit(long.MaxValue, long.MaxValue, 2, true, new ulong[] { 0xffffffffffffffffL, 0xffffffffffffffffL }.Cast<long>().GetEnumerator(), new int[] { 0 }.AsEnumerable().GetEnumerator()); AssertLongRangeSplit(long.MaxValue, long.MaxValue, 4, true, new ulong[] { 0xffffffffffffffffL, 0xffffffffffffffffL }.Cast<long>().GetEnumerator(), new int[] { 0 }.AsEnumerable().GetEnumerator()); AssertLongRangeSplit(long.MaxValue, long.MaxValue, 6, true, new ulong[] { 0xffffffffffffffffL, 0xffffffffffffffffL }.Cast<long>().GetEnumerator(), new int[] { 0 }.AsEnumerable().GetEnumerator()); AssertLongRangeSplit(long.MaxValue, long.MaxValue, 8, true, new ulong[] { 0xffffffffffffffffL, 0xffffffffffffffffL }.Cast<long>().GetEnumerator(), new int[] { 0 }.AsEnumerable().GetEnumerator()); AssertLongRangeSplit(long.MaxValue, long.MaxValue, 64, true, new ulong[] { 0xffffffffffffffffL, 0xffffffffffffffffL }.Cast<long>().GetEnumerator(), new int[] { 0 }.AsEnumerable().GetEnumerator()); AssertLongRangeSplit(long.MaxValue - 0xfL, long.MaxValue, 4, true, new ulong[] { 0xfffffffffffffffL, 0xfffffffffffffffL }.Cast<long>().GetEnumerator(), new int[] { 4 }.AsEnumerable().GetEnumerator()); AssertLongRangeSplit(long.MaxValue - 0x10L, long.MaxValue, 4, true, new ulong[] { 0xffffffffffffffefL, 0xffffffffffffffefL, 0xfffffffffffffffL, 0xfffffffffffffffL }.Cast<long>().GetEnumerator(), new int[] { 0, 4 }.AsEnumerable().GetEnumerator()); // lower end extremes AssertLongRangeSplit(long.MinValue, long.MinValue, 1, true, new long[] { 0x0000000000000000L, 0x0000000000000000L }.Cast<long>().GetEnumerator(), new int[] { 0 }.AsEnumerable().GetEnumerator()); AssertLongRangeSplit(long.MinValue, long.MinValue, 2, true, new long[] { 0x0000000000000000L, 0x0000000000000000L }.Cast<long>().GetEnumerator(), new int[] { 0 }.AsEnumerable().GetEnumerator()); AssertLongRangeSplit(long.MinValue, long.MinValue, 4, true, new long[] { 0x0000000000000000L, 0x0000000000000000L }.Cast<long>().GetEnumerator(), new int[] { 0 }.AsEnumerable().GetEnumerator()); AssertLongRangeSplit(long.MinValue, long.MinValue, 6, true, new long[] { 0x0000000000000000L, 0x0000000000000000L }.Cast<long>().GetEnumerator(), new int[] { 0 }.AsEnumerable().GetEnumerator()); AssertLongRangeSplit(long.MinValue, long.MinValue, 8, true, new long[] { 0x0000000000000000L, 0x0000000000000000L }.Cast<long>().GetEnumerator(), new int[] { 0 }.AsEnumerable().GetEnumerator()); AssertLongRangeSplit(long.MinValue, long.MinValue, 64, true, new long[] { 0x0000000000000000L, 0x0000000000000000L }.Cast<long>().GetEnumerator(), new int[] { 0 }.AsEnumerable().GetEnumerator()); AssertLongRangeSplit(long.MinValue, long.MinValue + 0xfL, 4, true, new long[] { 0x000000000000000L, 0x000000000000000L }.Cast<long>().GetEnumerator(), new int[] { 4 }.AsEnumerable().GetEnumerator()); AssertLongRangeSplit(long.MinValue, long.MinValue + 0x10L, 4, true, new long[] { 0x0000000000000010L, 0x0000000000000010L, 0x000000000000000L, 0x000000000000000L }.Cast<long>().GetEnumerator(), new int[] { 0, 4 }.AsEnumerable().GetEnumerator()); } [Test] public void TestRandomSplit() { Random random = new Random(); for (int i = 0; i < 100; i++) { ExecuteOneRandomSplit(random); } } private void ExecuteOneRandomSplit(Random random) { long lower = RandomLong(random); long len = (long)random.Next(16384 * 1024); // not too large bitsets, else OOME! while (lower + len < lower) { // overflow lower >>= 1; } AssertLongRangeSplit(lower, lower + len, random.Next(64) + 1, true, null, null); } private long RandomLong(Random random) { long val; switch (random.Next(4)) { case 0: val = 1L << (random.Next(63)); // patterns like 0x000000100000 (-1 yields patterns like 0x0000fff) break; case 1: val = -1L << (random.Next(63)); // patterns like 0xfffff00000 break; default: val = random.Next(); break; } val += random.Next(5) - 2; if (random.Next(2) == 1) { if (random.Next(2) == 1) val += random.Next(100) - 50; if (random.Next(2) == 1) val = ~val; if (random.Next(2) == 1) val = val << 1; if (random.Next(2) == 1) val = Number.URShift(val, 1); } return val; } [Test] public void TestSplitLongRange() { // a hard-coded "standard" range AssertLongRangeSplit(- 5000L, 9500L, 4, true, new System.Int64[] { 0x7fffffffffffec78L, 0x7fffffffffffec7fL, unchecked((long) (0x8000000000002510L)), unchecked((long) (0x800000000000251cL)), 0x7fffffffffffec8L, 0x7fffffffffffecfL, 0x800000000000250L, 0x800000000000250L, 0x7fffffffffffedL, 0x7fffffffffffefL, 0x80000000000020L, 0x80000000000024L, 0x7ffffffffffffL, 0x8000000000001L }.Cast<long>().GetEnumerator(), new int[] {0, 0, 4, 4, 8, 8, 12}.Cast<int>().GetEnumerator()); // the same with no range splitting AssertLongRangeSplit(-5000L, 9500L, 64, true, new System.Int64[] {0x7fffffffffffec78L, unchecked((long) (0x800000000000251cL))}.Cast <long>().GetEnumerator(), new int[] { 0 }.Cast<int>().GetEnumerator()); // this tests optimized range splitting, if one of the inner bounds // is also the bound of the next lower precision, it should be used completely AssertLongRangeSplit(0L, 1024L + 63L, 4, true, new System.Int64[] {0x800000000000040L, 0x800000000000043L, 0x80000000000000L, 0x80000000000003L}.Cast <long>().GetEnumerator(), new int[] { 4, 8 }.Cast<int>().GetEnumerator()); // the full long range should only consist of a lowest precision range; no bitset testing here, as too much memory needed :-) AssertLongRangeSplit(System.Int64.MinValue, System.Int64.MaxValue, 8, false, new System.Int64[] {0x00L, 0xffL}.Cast<long>().GetEnumerator(), new int[] { 56 }.Cast<int>().GetEnumerator()); // the same with precisionStep=4 AssertLongRangeSplit(System.Int64.MinValue, System.Int64.MaxValue, 4, false, new System.Int64[] {0x0L, 0xfL}.Cast<long>().GetEnumerator(), new int[] { 60 }.Cast<int>().GetEnumerator()); // the same with precisionStep=2 AssertLongRangeSplit(System.Int64.MinValue, System.Int64.MaxValue, 2, false, new System.Int64[] {0x0L, 0x3L}.Cast<long>().GetEnumerator(), new int[] {62}.Cast<int>().GetEnumerator()); // the same with precisionStep=1 AssertLongRangeSplit(System.Int64.MinValue, System.Int64.MaxValue, 1, false, new System.Int64[] {0x0L, 0x1L}.ToList().GetEnumerator(), new int[] {63}.Cast<int>().GetEnumerator()); // a inverse range should produce no sub-ranges AssertLongRangeSplit(9500L, -5000L, 4, false, Enumerable.Empty<long>().GetEnumerator(), new int[] {}.Cast<int>().GetEnumerator()); // a 0-length range should reproduce the range itsself AssertLongRangeSplit(9500L, 9500L, 4, false, new long[] { unchecked((long) (0x800000000000251cL)), unchecked((long) (0x800000000000251cL)) }.Cast<long>().GetEnumerator(), new int[] {0}.Cast<int>().GetEnumerator()); } /// <summary>Note: The neededBounds iterator must be unsigned (easier understanding what's happening) </summary> protected internal virtual void AssertIntRangeSplit(int lower, int upper, int precisionStep, bool useBitSet, IEnumerator<int> neededBounds, IEnumerator<int> neededShifts) { OpenBitSet bits = useBitSet ? new OpenBitSet(upper - lower + 1) : null; NumericUtils.SplitIntRange(new AnonymousClassIntRangeBuilder(lower, upper, useBitSet, bits, neededBounds, neededShifts,this), precisionStep, lower, upper); if (useBitSet) { // after flipping all bits in the range, the cardinality should be zero bits.Flip(0, upper - lower + 1); Assert.IsTrue(bits.IsEmpty(), "The sub-range concenated should match the whole range"); } } [Test] public virtual void TestSplitIntRange() { // a hard-coded "standard" range AssertIntRangeSplit(- 5000, 9500, 4, true, new System.Int32[] { 0x7fffec78, 0x7fffec7f, unchecked((System.Int32) 0x80002510), unchecked((System.Int32) 0x8000251c), 0x7fffec8, 0x7fffecf, 0x8000250, 0x8000250, 0x7fffed, 0x7fffef, 0x800020, 0x800024, 0x7ffff, 0x80001 }.Cast<int>().GetEnumerator (), new int[] { 0, 0, 4, 4, 8, 8, 12 }.Cast<int>().GetEnumerator()); // the same with no range splitting AssertIntRangeSplit(-5000, 9500, 32, true, new System.Int32[] {0x7fffec78, unchecked((System.Int32) 0x8000251c)}.Cast<int>(). GetEnumerator(), new int[] { 0 }.Cast<int>().GetEnumerator()); // this tests optimized range splitting, if one of the inner bounds // is also the bound of the next lower precision, it should be used completely AssertIntRangeSplit(0, 1024 + 63, 4, true, new System.Int32[] {0x8000040, 0x8000043, 0x800000, 0x800003}.Cast<int>().GetEnumerator(), new int[] { 4, 8 }.Cast<int>().GetEnumerator()); // the full int range should only consist of a lowest precision range; no bitset testing here, as too much memory needed :-) AssertIntRangeSplit(System.Int32.MinValue, System.Int32.MaxValue, 8, false, new System.Int32[] {0x00, 0xff}.Cast<int>().GetEnumerator(), new int[] { 24 }.Cast<int>().GetEnumerator()); // the same with precisionStep=4 AssertIntRangeSplit(System.Int32.MinValue, System.Int32.MaxValue, 4, false, new System.Int32[] {0x0, 0xf}.Cast<int>().GetEnumerator(), new int[] {28}.Cast<int>().GetEnumerator()); // the same with precisionStep=2 AssertIntRangeSplit(System.Int32.MinValue, System.Int32.MaxValue, 2, false, new System.Int32[] {0x0, 0x3}.Cast<int>().GetEnumerator(), new int[] {30}.Cast<int>().GetEnumerator()); // the same with precisionStep=1 AssertIntRangeSplit(System.Int32.MinValue, System.Int32.MaxValue, 1, false, new System.Int32[] {0x0, 0x1}.Cast<int>().GetEnumerator(), new int[] {31}.Cast<int>().GetEnumerator()); // a inverse range should produce no sub-ranges AssertIntRangeSplit(9500, -5000, 4, false, Enumerable.Empty<int>().GetEnumerator(), new int[] {}.Cast<int>().GetEnumerator()); // a 0-length range should reproduce the range itsself AssertIntRangeSplit(9500, 9500, 4, false, new System.Int32[] { unchecked((System.Int32) 0x8000251c), unchecked((System.Int32) 0x8000251c) }.Cast<int>().GetEnumerator(), new int[] {0}.Cast<int>().GetEnumerator()); } } }
using System; using System.Net; using System.Runtime.InteropServices; namespace RedHatX.AspNetCore.Server.Kestrel.Transport.Linux { unsafe struct IOVector { public void* Base; public void* Count; } static class SocketInterop { [DllImportAttribute(Interop.Library, EntryPoint = "RHXKL_Socket")] public static extern unsafe PosixResult Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, bool blocking, out Socket socket); [DllImportAttribute(Interop.Library, EntryPoint = "RHXKL_GetAvailableBytes")] public static extern PosixResult GetAvailableBytes(Socket socket); [DllImportAttribute(Interop.Library, EntryPoint = "RHXKL_Bind")] public static extern unsafe PosixResult Bind(Socket socket, byte* addr, int addrlen); [DllImportAttribute(Interop.Library, EntryPoint = "RHXKL_Connect")] public static extern unsafe PosixResult Connect(Socket socket, byte* addr, int addrlen); [DllImportAttribute(Interop.Library, EntryPoint = "RHXKL_Listen")] public static extern PosixResult Listen(Socket socket, int backlog); [DllImportAttribute(Interop.Library, EntryPoint = "RHXKL_Accept")] public static unsafe extern PosixResult Accept(Socket socket, byte* socketAddress, int socketAddressLen, bool blocking, out Socket clientSocket); [DllImportAttribute(Interop.Library, EntryPoint = "RHXKL_Shutdown")] public static extern PosixResult Shutdown(Socket socket, SocketShutdown shutdown); [DllImportAttribute(Interop.Library, EntryPoint = "RHXKL_Send")] public static extern unsafe PosixResult Send(int socket, IOVector* ioVectors, int ioVectorLen); public static unsafe PosixResult Send(SafeHandle socket, IOVector* ioVectors, int ioVectorLen) => Send(socket.DangerousGetHandle().ToInt32(), ioVectors, ioVectorLen); [DllImportAttribute(Interop.Library, EntryPoint = "RHXKL_Receive")] public static unsafe extern PosixResult Receive(int socket, IOVector* ioVectors, int ioVectorLen); public static unsafe PosixResult Receive(SafeHandle socket, IOVector* ioVectors, int ioVectorLen) => Receive(socket.DangerousGetHandle().ToInt32(), ioVectors, ioVectorLen); [DllImportAttribute(Interop.Library, EntryPoint = "RHXKL_SetSockOpt")] public static extern unsafe PosixResult SetSockOpt(SafeHandle socket, SocketOptionLevel optionLevel, SocketOptionName optionName, byte* optionValue, int optionLen); [DllImportAttribute(Interop.Library, EntryPoint = "RHXKL_GetSockOpt")] public static extern unsafe PosixResult GetSockOpt(SafeHandle socket, SocketOptionLevel optionLevel, SocketOptionName optionName, byte* optionValue, int* optionLen); [DllImportAttribute(Interop.Library, EntryPoint = "RHXKL_GetPeerName")] public static extern unsafe PosixResult GetPeerName(Socket socket, byte* addr, int addrlen); [DllImportAttribute(Interop.Library, EntryPoint = "RHXKL_GetSockName")] public static extern unsafe PosixResult GetSockName(Socket socket, byte* addr, int addrlen); [DllImportAttribute(Interop.Library, EntryPoint = "RHXKL_Duplicate")] public static extern PosixResult Duplicate(Socket socket, out Socket dup); } // Warning: Some operations use DangerousGetHandle for increased performance class Socket : CloseSafeHandle { private Socket() {} public static Socket Create(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, bool blocking) { Socket socket; var result = SocketInterop.Socket(addressFamily, socketType, protocolType, blocking, out socket); result.ThrowOnError(); return socket; } public int GetAvailableBytes() { var result = TryGetAvailableBytes(); result.ThrowOnError(); return result.Value; } public PosixResult TryGetAvailableBytes() { return SocketInterop.GetAvailableBytes(this); } public void Bind(IPEndPoint endpoint) { TryBind(endpoint) .ThrowOnError(); } public unsafe PosixResult TryBind(IPEndPoint endpoint) { IPSocketAddress socketAddress = new IPSocketAddress(endpoint); return SocketInterop.Bind(this, (byte*)&socketAddress, sizeof(IPSocketAddress)); } public void Connect(IPEndPoint endpoint) { TryConnect(endpoint) .ThrowOnError(); } public unsafe PosixResult TryConnect(IPEndPoint endpoint) { IPSocketAddress socketAddress = new IPSocketAddress(endpoint); return SocketInterop.Connect(this, (byte*)&socketAddress, sizeof(IPSocketAddress)); } public void Listen(int backlog) { TryListen(backlog) .ThrowOnError(); } public PosixResult TryListen(int backlog) { return SocketInterop.Listen(this, backlog); } public unsafe Socket Accept(bool blocking) { Socket clientSocket; var result = TryAccept(out clientSocket, blocking); result.ThrowOnError(); return clientSocket; } public unsafe PosixResult TryAccept(out Socket clientSocket, bool blocking) { return SocketInterop.Accept(this, null, 0, blocking, out clientSocket); } public int Receive(ArraySegment<byte> buffer) { var result = TryReceive(buffer); result.ThrowOnError(); return result.Value; } public unsafe PosixResult TryReceive(ArraySegment<byte> buffer) { ValidateSegment(buffer); fixed (byte* buf = buffer.Array) { IOVector ioVector = new IOVector() { Base = buf + buffer.Offset, Count = (void*)buffer.Count }; return SocketInterop.Receive(this, &ioVector, 1); } } public unsafe int Receive(IOVector* ioVectors, int ioVectorLen) { var result = TryReceive(ioVectors, ioVectorLen); result.ThrowOnError(); return result.Value; } public unsafe PosixResult TryReceive(IOVector* ioVectors, int ioVectorLen) { return SocketInterop.Receive(this, ioVectors, ioVectorLen); } public void Shutdown(SocketShutdown shutdown) { TryShutdown(shutdown) .ThrowOnError(); } public PosixResult TryShutdown(SocketShutdown shutdown) { return SocketInterop.Shutdown(this, shutdown); } public int Send(ArraySegment<byte> buffer) { var result = TrySend(buffer); result.ThrowOnError(); return result.Value; } public unsafe PosixResult TrySend(ArraySegment<byte> buffer) { ValidateSegment(buffer); fixed (byte* buf = buffer.Array) { IOVector ioVector = new IOVector() { Base = buf + buffer.Offset, Count = (void*)buffer.Count }; return SocketInterop.Send(this, &ioVector, 1); } } public unsafe int Send(IOVector* ioVectors, int ioVectorLen) { var result = TrySend(ioVectors, ioVectorLen); result.ThrowOnError(); return result.Value; } public unsafe PosixResult TrySend(IOVector* ioVectors, int ioVectorLen) { return SocketInterop.Send(this, ioVectors, ioVectorLen); } public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int value) { TrySetSocketOption(optionLevel, optionName, value) .ThrowOnError(); } public unsafe PosixResult TrySetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int value) { return SocketInterop.SetSockOpt(this, optionLevel, optionName, (byte*)&value, 4); } // TODO: rename to GetSocketOptionInt public int GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName) { int value = 0; var result = TryGetSocketOption(optionLevel, optionName, ref value); result.ThrowOnError(); return value; } public unsafe PosixResult TryGetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, ref int value) { int v = 0; int length = 4; var rv = SocketInterop.GetSockOpt(this, optionLevel, optionName, (byte*)&v, &length); if (rv.IsSuccess) { value = v; } return rv; } public IPEndPoint GetLocalIPAddress() { IPEndPoint ep; TryGetLocalIPAddress(out ep) .ThrowOnError(); return ep; } public unsafe PosixResult TryGetLocalIPAddress(out IPEndPoint ep) { IPSocketAddress socketAddress; var rv = SocketInterop.GetSockName(this, (byte*)&socketAddress, sizeof(IPSocketAddress)); if (rv.IsSuccess) { ep = socketAddress.ToIPEndPoint(); } else { ep = null; } return rv; } public IPEndPoint GetPeerIPAddress() { IPEndPoint ep; TryGetPeerIPAddress(out ep) .ThrowOnError(); return ep; } public unsafe PosixResult TryGetPeerIPAddress(out IPEndPoint ep) { IPSocketAddress socketAddress; var rv = SocketInterop.GetPeerName(this, (byte*)&socketAddress, sizeof(IPSocketAddress)); if (rv.IsSuccess) { ep = socketAddress.ToIPEndPoint(); } else { ep = null; } return rv; } public Socket Duplicate() { Socket dup; var rv = TryDuplicate(out dup); rv.ThrowOnError(); return dup; } public PosixResult TryDuplicate(out Socket dup) { return SocketInterop.Duplicate(this, out dup); } private static void ValidateSegment(ArraySegment<byte> segment) { // ArraySegment<byte> is not nullable. if (segment.Array == null) { throw new ArgumentNullException(nameof(segment)); } // Length zero is explicitly allowed if (segment.Offset < 0 || segment.Count < 0 || segment.Count > (segment.Array.Length - segment.Offset)) { throw new ArgumentOutOfRangeException(nameof(segment)); } } } }