content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
class TheBiggestOf3
{
static void Main()
{
Console.WriteLine("enter three real numbers");
double a = double.Parse(Console.ReadLine());
double b = double.Parse(Console.ReadLine());
double c = double.Parse(Console.ReadLine());
double biggest = 0;
if (a > b && a > c) biggest = a;
if (b > a && b > c) biggest = b;
if (c > a && c > b) biggest = c;
Console.WriteLine("the biggest number is {0}", biggest);
}
}
| 25.35 | 64 | 0.546351 | [
"MIT"
] | ivannk0900/Telerik-Academy | C# 1/ConditionalStatements/TheBiggestOf3/TheBiggestOf3.cs | 509 | C# |
/*****************************************************************************
*
* ReoGrid - .NET Spreadsheet Control
*
* http://reogrid.net/
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
* PURPOSE.
*
* Author: Jing <lujing at unvell.com>
*
* Copyright (c) 2012-2016 Jing <lujing at unvell.com>
* Copyright (c) 2012-2016 unvell.com, all rights reserved.
*
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Text.RegularExpressions;
#if WINFORM || ANDROID
using RGFloat = System.Single;
#elif WPF
using RGFloat = System.Double;
#endif // WPF
using RGWorkbook = unvell.ReoGrid.IWorkbook;
using RGWorksheet = unvell.ReoGrid.Worksheet;
using unvell.Common;
using unvell.ReoGrid.Rendering;
using unvell.ReoGrid.DataFormat;
using unvell.ReoGrid.Utility;
using unvell.ReoGrid.IO.OpenXML.Schema;
using unvell.ReoGrid.Graphics;
using unvell.ReoGrid.Drawing;
using System.Globalization;
namespace unvell.ReoGrid.IO.OpenXML
{
#region Reader
internal sealed class ExcelReader
{
private static readonly string[] AcceptableDateFormats = { "M/d/yyyy", "yyyy/M/d", "M-d-yyyy", "yyyy-M-d", "M-d-y", "M/d/y" };
#region Read Stream
public static void ReadStream(RGWorkbook rgWorkbook, Stream stream)
{
#if DEBUG
Stopwatch sw = Stopwatch.StartNew();
#endif
var document = Document.ReadFromStream(stream);
if (document.Workbook.sheets.Count == 0) throw new ReoGridLoadException("Specified Excel file does not contain any valid sheets.");
rgWorkbook.Worksheets.Clear();
// create all worksheets
foreach (var sheet in document.Workbook.sheets)
{
var rgSheet = rgWorkbook.CreateWorksheet(sheet.name);
rgWorkbook.AddWorksheet(rgSheet);
}
// load all defined names
foreach (var definedName in document.Workbook.definedNames)
{
if (string.IsNullOrEmpty(definedName.name))
{
continue;
}
ReadNamedRange(rgWorkbook, document.Workbook, definedName);
}
// load all worksheets
foreach (var sheet in document.Workbook.sheets)
{
LoadWorksheet(rgWorkbook, document, sheet);
}
#if DEBUG
sw.Stop();
long ms = sw.ElapsedMilliseconds;
if (ms > 20)
{
Logger.Log("file format", "reading excel format takes " + ms + " ms.");
}
#endif
}
#endregion // Read Stream
#region Named range
private static void ReadNamedRangeAddr(RGWorkbook rgBook, string name, string addr, bool worksheetRange)
{
int sheetSplit = addr.IndexOf('!');
string sheetName = null;
if (sheetSplit >= 0)
{
sheetName = addr.Substring(0, sheetSplit);
addr = addr.Substring(sheetSplit + 1);
}
if (!string.IsNullOrEmpty(sheetName))
{
if ((sheetName[0] == '\'' && sheetName[0] == '"')
|| (sheetName[sheetName.Length - 1] == '\'' && sheetName[sheetName.Length - 1] == '"'))
{
sheetName = sheetName.Substring(1, sheetName.Length - 2);
}
}
var rgSheet = rgBook.GetWorksheetByName(sheetName);
if (rgSheet != null)
{
if (!RangePosition.IsValidAddress(addr))
{
rgBook.NotifyExceptionHappen(rgSheet, new InvalidAddressException(addr));
}
else
{
// TODO: real workbook scope name
rgSheet.DefineNamedRange(name, addr,
worksheetRange ? NamedRangeScope.Worksheet : NamedRangeScope.Workbook);
}
}
}
private static void ReadNamedRange(RGWorkbook rgBook, Schema.Workbook workbook, Schema.DefinedName defName)
{
var name = defName.name;
int index = name.IndexOf('.');
if (index == 0)
{
return;
}
else if (index > 0)
{
string space = name.Substring(0, index);
name = name.Substring(index + 1);
switch (space)
{
case "_xlnm":
break;
}
}
else if (!string.IsNullOrEmpty(defName.address))
{
// TODO: real workbook scope name
ReadNamedRangeAddr(rgBook, name, defName.address, !string.IsNullOrEmpty(defName.localSheetId));
}
}
#endregion // Named range
#region Worksheet
private static void LoadWorksheet(RGWorkbook rgWorkbook, Document doc, WorkbookSheet sheetIndex)
{
RGWorksheet rgSheet = rgWorkbook.GetWorksheetByName(sheetIndex.name);
var sheet = doc.LoadRelationResourceById<Schema.Worksheet>(doc.Workbook, sheetIndex.resId);
float fixedCharWidth = 7.0f; //ResourcePoolManager.Instance.GetFont("Arial", 10f, System.Drawing.FontStyle.Regular).SizeInPoints;
#region SheetView
var sheetView = sheet.sheetViews.FirstOrDefault() as SheetView;
if (sheetView != null)
{
if (sheetView.showGridLines != null)
{
rgSheet.SetSettings(WorksheetSettings.View_ShowGridLine, OpenXMLUtility.IsTrue(sheetView.showGridLines));
}
if (sheetView.showRowColHeaders != null)
{
rgSheet.SetSettings(WorksheetSettings.View_ShowHeaders, OpenXMLUtility.IsTrue(sheetView.showRowColHeaders));
}
if (sheetView.zoomScale != null)
{
double zoom = 100;
if (double.TryParse(sheetView.zoomScale, out zoom))
{
rgSheet.ScaleFactor = (float)(zoom / 100f);
}
}
}
#endregion // SheetView
double dpi = PlatformUtility.GetDPI();
ushort defaultRowHeight = rgSheet.defaultRowHeight;
#region SheetFormatProperty
if (sheet.sheetFormatProperty != null)
{
if (sheet.sheetFormatProperty.defaultRowHeight != null)
{
double defRowHeight = 4f;
if (double.TryParse(sheet.sheetFormatProperty.defaultRowHeight, System.Globalization.NumberStyles.Number,
ExcelWriter.EnglishCulture, out defRowHeight))
{
defaultRowHeight = (ushort)Math.Round(defRowHeight * dpi / 72.0);
rgSheet.defaultRowHeight = defaultRowHeight;
}
}
if (sheet.sheetFormatProperty.defaultColumnWidth != null)
{
double defColumnWidth = 0;
if (double.TryParse(sheet.sheetFormatProperty.defaultColumnWidth, System.Globalization.NumberStyles.Number,
ExcelWriter.EnglishCulture, out defColumnWidth))
{
ushort pixelWidth = (ushort)Math.Truncate(((256 * defColumnWidth + Math.Truncate(128 / fixedCharWidth)) / 256) * fixedCharWidth);
rgSheet.defaultColumnWidth = pixelWidth;
rgSheet.SetColumnsWidth(0, rgSheet.ColumnCount, c => rgSheet.defaultColumnWidth, false, false);
}
}
}
#endregion // SheetFormatProperty
#region Dimension
// resize to dimension
if (sheet.dimension != null && !string.IsNullOrEmpty(sheet.dimension.address))
{
RangePosition contentRange = new RangePosition(sheet.dimension.address);
if (rgSheet.RowCount <= contentRange.EndRow)
{
rgSheet.Rows = contentRange.EndRow + 1;
}
if (rgSheet.ColumnCount <= contentRange.EndCol)
{
rgSheet.Columns = contentRange.EndCol + 1;
}
}
#endregion // Dimension
#region Columns
// columns
if (sheet.cols != null)
{
foreach (Column col in sheet.cols)
{
//width = Truncate([{Number of Characters} * {Maximum Digit Width} + {5 pixel padding}] / {Maximum Digit Width} * 256) / 256
//ushort pixelWidth = (ushort)Math.Truncate(((256 * col.width + Math.Truncate(128 / fixedCharWidth)) / 256) * fixedCharWidth);
//ushort excelWidth = (ushort)( ( col.width - 12) / 7d + 1);
//OpenXmlWidth = (Pixels - 12 + 5) / 7d + 1;//From pixels to inches.
ushort pixelWidth = (ushort)Math.Truncate(((256 * col.width + Math.Truncate(128 / fixedCharWidth)) / 256) * fixedCharWidth);
int startCol = col.min - 1;
int count = col.max - col.min + 1;
if (startCol + count > rgSheet.ColumnCount) count = rgSheet.ColumnCount - startCol;
rgSheet.SetColumnsWidth(startCol, count, pixelWidth);
for (int i = startCol; i < startCol + count; i++)
{
var header = rgSheet.GetColumnHeader(i);
header.IsAutoWidth = !OpenXMLUtility.IsTrue(col.customWidth);
}
}
}
#endregion // Columns
// stylesheet
var styles = doc.LoadEntryFile<Stylesheet>(doc.Workbook._path, "styles.xml");
doc.Stylesheet = styles;
// fonts
var fonts = styles.fonts;
// borders
var borders = styles.borders;
// fills
var fills = styles.fills;
// cell formats
var cellFormats = styles.cellFormats;
// data
SharedStrings sharedStringTable = doc.ReadSharedStringTable();
var defaultFont = fonts.list.ElementAtOrDefault(0) as Schema.Font;
if (defaultFont != null)
{
SetStyleFont(doc, rgSheet.RootStyle, defaultFont);
}
#if DEBUG
Stopwatch sw = Stopwatch.StartNew();
Logger.Log("excel format", "begin iterating cells...");
Stopwatch swBorder = new Stopwatch();
Stopwatch swStyle = new Stopwatch();
Stopwatch swValue = new Stopwatch();
Stopwatch swFormula = new Stopwatch();
Stopwatch swRowStyle = new Stopwatch();
Stopwatch swRowHeight = new Stopwatch();
Stopwatch swDrawing = new Stopwatch();
int cellCount = 0;
#endif
Dictionary<int, SharedFormulaInfo> sharedFormulas = new Dictionary<int, SharedFormulaInfo>();
int rowTop = rgSheet.GetRowHeader(0).Top;
int lastRowIndex = -1;
int maxHBorderRow = -1, maxHBorderCol = -1;
int maxVBorderRow = -1, maxVBorderCol = -1;
#region Rows
foreach (Row row in sheet.rows)
{
int rowIndex = row.index - 1;
#region Row Height
#if DEBUG
swRowHeight.Start();
#endif // DEBUG
if (rowIndex - lastRowIndex > 1)
{
//rgSheet.SetRowsHeight(lastRowIndex + 1, rowIndex - lastRowIndex - 1, defaultRowHeight);
for (int i = lastRowIndex + 1; i < rowIndex; i++)
{
var passedRowHeader = rgSheet.GetRowHeader(i);
passedRowHeader.Top = rowTop;
passedRowHeader.InnerHeight = defaultRowHeight;
rowTop += defaultRowHeight;
}
//rowTop += (rowIndex - lastRowIndex - 1) * rgSheet.defaultRowHeight;
lastRowIndex = rowIndex - 1;
}
// row height
double rowHeight = 0;
bool isHidden = OpenXMLUtility.IsTrue(row.hidden);
RowHeader rowHeader;
if (//row.customHeight == "1"
//&&
!string.IsNullOrEmpty(row.height) && double.TryParse(row.height, out rowHeight))
{
rowHeader = rgSheet.GetRowHeader(rowIndex);
ushort height = (ushort)Math.Round(rowHeight * dpi / 72f);
rowHeader.Top = rowTop;
if (isHidden)
{
rowHeader.LastHeight = height;
rowHeader.InnerHeight = 0;
}
else
{
rowHeader.InnerHeight = height;
rowTop += height;
}
}
else
{
rowHeader = rgSheet.GetRowHeader(rowIndex);
rowHeader.Top = rowTop;
if (isHidden)
{
rowHeader.LastHeight = defaultRowHeight;
rowHeader.InnerHeight = 0;
}
else
{
rowHeader.InnerHeight = defaultRowHeight;
rowTop += defaultRowHeight;
}
}
rowHeader.IsAutoHeight = !OpenXMLUtility.IsTrue(row.customHeight);
lastRowIndex = rowIndex;
#if DEBUG
swRowHeight.Stop();
#endif // DEBUG
#endregion // Row Height
#region Row Style
#if DEBUG
swRowStyle.Start();
#endif // DEBUG
WorksheetRangeStyle rowStyle = null;
int styleIndex = -1;
// row style
if (!string.IsNullOrEmpty(row.styleIndex) && int.TryParse(row.styleIndex, out styleIndex))
{
var style = cellFormats.list.ElementAtOrDefault(styleIndex) as CellFormat;
if (style != null)
{
if (!style._preprocessed)
{
PreprocessCellStyle(doc, rgSheet, style, fonts, fills);
}
if (style._cachedStyleSet != null)
{
rowStyle = style._cachedStyleSet;
rgSheet.RetrieveRowHeader(row.index - 1).InnerStyle = new WorksheetRangeStyle(rowStyle);
}
if (//style.applyBorder == "1" &&
!string.IsNullOrEmpty(style.borderId))
{
int id = 0;
if (int.TryParse(style.borderId, out id)
&& id >= 0 && id < borders.Count)
{
var border = borders[id];
if (border != null)
{
if (!border._preprocessed)
{
PreprocessCellBorders(doc, border);
}
if (border._hasTop)
{
for (int c = 0; c < rgSheet.Columns; c++)
{
var hb = rgSheet.GetHBorder(rowIndex, c);
hb.Pos |= Core.HBorderOwnerPosition.Top;
hb.Style = border._top;
hb.Span = 1;
}
if (maxHBorderRow < rowIndex) maxHBorderRow = rowIndex;
maxHBorderCol = rgSheet.Columns;
}
if (border._hasBottom)
{
for (int c = 0; c < rgSheet.Columns; c++)
{
var hb = rgSheet.GetHBorder(rowIndex + 1, c);
hb.Pos |= Core.HBorderOwnerPosition.Bottom;
hb.Style = border._bottom;
hb.Span = 1;
}
if (maxHBorderRow < rowIndex + 1) maxHBorderRow = rowIndex + 1;
maxHBorderCol = rgSheet.Columns;
}
if (border._hasLeft)
{
for (int c = 0; c < rgSheet.Columns; c++)
{
var vb = rgSheet.GetVBorder(rowIndex, c);
vb.Pos |= Core.VBorderOwnerPosition.Left;
vb.Style = border._left;
vb.Span = 1;
}
if (maxVBorderRow < rowIndex) maxVBorderRow = rowIndex;
maxVBorderCol = rgSheet.Columns;
}
if (border._hasRight)
{
for (int c = 0; c < rgSheet.Columns; c++)
{
var vb = rgSheet.GetVBorder(rowIndex, c + 1);
vb.Pos |= Core.VBorderOwnerPosition.Right;
vb.Style = border._right;
vb.Span = 1;
}
if (maxVBorderRow < rowIndex) maxVBorderRow = rowIndex;
maxVBorderCol = rgSheet.Columns + 1;
}
}
}
}
}
}
#if DEBUG
swRowStyle.Stop();
#endif // DEBUG
#endregion // Row Style
foreach (Schema.Cell cell in row.cells)
{
CellPosition pos = new CellPosition(cell.address);
Cell rgCell = rgSheet.cells[pos.Row, pos.Col];
if (rgCell == null)
{
rgCell = rgSheet.CreateCell(pos.Row, pos.Col);
rgSheet.cells[pos.Row, pos.Col] = rgCell;
}
else
{
//var rowHeader = rgSheet.rows[pos.Row];
rgCell.Top = rowHeader.Top;
rgCell.Height = rowHeader.InnerHeight + 1;
}
#if DEBUG
Debug.Assert(rgCell.Height == rgSheet.GetRowHeader(pos.Row).InnerHeight + 1);
#endif // DEBUG
CellFormat style = null;
#region Cell Style, Border
if (!string.IsNullOrEmpty(cell.styleIndex) && int.TryParse(cell.styleIndex, out styleIndex))
{
#if DEBUG
swStyle.Start();
#endif // DEBUG
style = cellFormats.list.ElementAtOrDefault(styleIndex) as CellFormat;
#if DEBUG
swStyle.Stop();
#endif // DEBUG
if (style != null)
{
#if DEBUG
swStyle.Start();
#endif // DEBUG
//cell._style = style;
if (!style._preprocessed)
{
PreprocessCellStyle(doc, rgSheet, style, fonts, fills);
}
#if DEBUG
swStyle.Stop();
#endif // DEBUG
if (style._cachedStyleSet != null)
{
#if DEBUG
swStyle.Start();
#endif // DEBUG
if (rowStyle != null && rowStyle != style._cachedStyleSet)
{
rgCell.InnerStyle = StyleUtility.CreateMergedStyle(style._cachedStyleSet, rowStyle);
rgCell.StyleParentKind = Core.StyleParentKind.Own;
StyleUtility.UpdateCellRenderAlign(rgSheet, rgCell);
}
else
{
rgCell.InnerStyle = style._cachedStyleSet;
rgCell.StyleParentKind = Core.StyleParentKind.Range;
StyleUtility.UpdateCellRenderAlign(rgSheet, rgCell);
}
#if DEBUG
swStyle.Stop();
#endif // DEBUG
}
#region Border
#if DEBUG
swBorder.Start();
#endif // DEBUG
int borderId = 0;
if (style != null
&& int.TryParse(style.borderId, out borderId)
&& borderId < borders.Count
&& (//style.applyBorder == "1" ||
borderId > 0))
{
var border = borders[borderId];
if (border != null)
{
if (!border._preprocessed)
{
PreprocessCellBorders(doc, border);
}
if (border._hasTop)
{
var hb = rgSheet.GetHBorder(pos.Row, pos.Col);
hb.Pos |= Core.HBorderOwnerPosition.Top;
hb.Style = border._top;
hb.Span = 1;
if (maxHBorderRow < pos.Row) maxHBorderRow = pos.Row;
if (maxHBorderCol < pos.Col) maxHBorderCol = pos.Col;
}
if (border._hasBottom)
{
var hb = rgSheet.GetHBorder(pos.Row + 1, pos.Col);
hb.Pos |= Core.HBorderOwnerPosition.Bottom;
hb.Style = border._bottom;
hb.Span = 1;
if (maxHBorderRow < pos.Row + 1) maxHBorderRow = pos.Row + 1;
if (maxHBorderCol < pos.Col) maxHBorderCol = pos.Col;
}
if (border._hasLeft)
{
var vb = rgSheet.GetVBorder(pos.Row, pos.Col);
vb.Pos |= Core.VBorderOwnerPosition.Left;
vb.Style = border._left;
vb.Span = 1;
if (maxVBorderRow < pos.Row) maxVBorderRow = pos.Row;
if (maxVBorderCol < pos.Col) maxVBorderCol = pos.Col;
}
if (border._hasRight)
{
var vb = rgSheet.GetVBorder(pos.Row, pos.Col + 1);
vb.Pos |= Core.VBorderOwnerPosition.Right;
vb.Style = border._right;
vb.Span = 1;
if (maxVBorderRow < pos.Row) maxVBorderRow = pos.Row;
if (maxVBorderCol < pos.Col + 1) maxVBorderCol = pos.Col + 1;
}
}
}
#if DEBUG
swBorder.Stop();
#endif // DEBUG
#endregion // Border
}
}
#endregion // Cell Style, Border
#region Cell Value
#if DEBUG
swValue.Start();
#endif // DEBUG
if (cell.value != null && !string.IsNullOrEmpty(cell.value.val))
{
if (cell.dataType == "s")
{
if (sharedStringTable != null)
{
int sharedTextIndex = 0;
if (int.TryParse(cell.value.val, out sharedTextIndex))
{
var ssitem = sharedStringTable.items[sharedTextIndex];
if (ssitem.text != null)
{
rgCell.InnerData = ssitem.text.val;
if (rgCell.InnerData != null && DateTime.TryParseExact(rgCell.InnerData.ToString(), AcceptableDateFormats,
CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dateCheck))
{
rgCell.InnerData = dateCheck;
rgCell.DataFormat = CellDataFormatFlag.DateTime;
}
else
{
rgCell.DataFormat = CellDataFormatFlag.Text;
}
}
else if (ssitem.runs != null)
{
#if DRAWING
rgCell.InnerData = CreateRichTextFromRuns(doc, new Paragraph[] { new Paragraph { runs = ssitem.runs } });
#endif // DRAWING
}
}
}
}
else if (cell.dataType == "b")
{
rgCell.InnerData = OpenXMLUtility.IsTrue(cell.value.val);
}
else
{
rgCell.InnerData = cell.value.val;
}
}
#if DEBUG
swValue.Stop();
#endif // DEBUG
#endregion // Cell Value
#region Data Format
if (style != null)
{
int numFormatId = 0;
if (rgCell.DataFormat == CellDataFormatFlag.General
//&& style.applyNumberFormat == "1"
&& !string.IsNullOrEmpty(style.numberFormatId)
&& int.TryParse(style.numberFormatId, out numFormatId))
{
rgCell.DataFormat = SetRGSheetDataFormat(rgSheet, rgCell, numFormatId, styles);
if (rgCell.DataFormat == CellDataFormatFlag.DateTime && rgCell.InnerData != null)
{
double days = Convert.ToDouble(rgCell.InnerData) - 1;
if (days >= 60) days--;
rgCell.InnerData = DateTimeDataFormatter.BaseStartDate.AddDays(days);
}
}
}
DataFormatterManager.Instance.FormatCell(rgCell);
#endregion // Data Format
#region Cell Formula
#if FORMULA
#if DEBUG
swFormula.Start();
#endif // DEBUG
var formula = cell.formula;
if (formula != null)
{
string cellFormula = null;
if (formula.type == "shared")
{
int sharedIndex = 0;
if (int.TryParse(formula.sharedIndex, out sharedIndex))
{
if (!string.IsNullOrEmpty(formula.val))
{
// parent
cellFormula = formula.val;
sharedFormulas[sharedIndex] = new SharedFormulaInfo { pos = pos, formula = cellFormula };
}
else
{
var sharedFormulaInfo = sharedFormulas[sharedIndex];
// children
unvell.ReoGrid.Formula.FormulaRefactor.Reuse(rgSheet, sharedFormulaInfo.pos, new RangePosition(pos));
}
}
}
else
{
cellFormula = formula.val;
}
if (cellFormula != null)
{
try
{
rgSheet.SetCellFormula(rgCell, cellFormula);
}
catch { }
}
}
#if DEBUG
swFormula.Stop();
#endif // DEBUG
#endif // FORMULA
#endregion // Cell Formula
}
#if DEBUG
cellCount++;
#endif // DEBUG
}
#endregion // Rows
#if DEBUG
swRowHeight.Start();
#endif // DEBUG
#region Normalize Row Heights
//int offset = 0;
for (int i = lastRowIndex + 1; i < rgSheet.Rows; i++)
{
var rowHeader = rgSheet.GetRowHeader(i);
rowHeader.Top = rowTop;
rowHeader.InnerHeight = defaultRowHeight;
rowTop += defaultRowHeight;
}
#endregion // Normalize Row Heights
#if DEBUG
swRowHeight.Stop();
#endif
#region Merge
// merge
if (sheet.mergeCells != null)
{
foreach (MergeCell mcell in sheet.mergeCells)
{
rgSheet.MergeRange(new RangePosition(mcell.address), updateUIAndEvent: false);
}
}
#endregion // Merge
#region Border
#if DEBUG
swBorder.Start();
#endif // DEBUG
// horizontal normalize
RangeBorderStyle lastBorder = RangeBorderStyle.Empty;
Core.HBorderOwnerPosition lastHPos = Core.HBorderOwnerPosition.None;
int borderSpans = 0;
for (int r = maxHBorderRow; r >= 0; r--)
{
lastBorder = RangeBorderStyle.Empty;
lastHPos = Core.HBorderOwnerPosition.None;
borderSpans = 1;
for (int c = maxHBorderCol; c >= 0; c--)
{
var hb = rgSheet.RetrieveHBorder(r, c);
if (hb != null)
{
if (hb.Span > 0 && hb.Style.Equals(lastBorder))
{
hb.Span += borderSpans;
hb.Pos |= lastHPos;
borderSpans++;
}
else
{
lastBorder = hb.Style;
lastHPos = hb.Pos;
borderSpans = 1;
}
}
else
{
lastBorder = RangeBorderStyle.Empty;
lastHPos = Core.HBorderOwnerPosition.None;
borderSpans = 1;
}
}
}
lastBorder = RangeBorderStyle.Empty;
Core.VBorderOwnerPosition lastVPos = Core.VBorderOwnerPosition.None;
borderSpans = 1;
// vertical normalize
for (int c = maxVBorderCol; c >= 0; c--)
{
lastBorder = RangeBorderStyle.Empty;
lastVPos = Core.VBorderOwnerPosition.None;
borderSpans = 1;
for (int r = maxVBorderRow; r >= 0; r--)
{
var vb = rgSheet.RetrieveVBorder(r, c);
if (vb != null)
{
if (vb.Span > 0 && vb.Style.Equals(lastBorder))
{
vb.Span += borderSpans;
vb.Pos |= lastVPos;
borderSpans++;
}
else
{
lastBorder = vb.Style;
lastVPos = Core.VBorderOwnerPosition.None;
borderSpans = 1;
}
}
else
{
lastBorder = RangeBorderStyle.Empty;
lastVPos = Core.VBorderOwnerPosition.None;
borderSpans = 1;
}
}
}
#if DEBUG
swBorder.Stop();
#endif // DEBUG
#endregion // Border
#region Drawing
#if DRAWING
if (sheet.drawing != null)
{
#if DEBUG
swDrawing.Start();
#endif // DEBUG
var drawingFile = doc.LoadRelationResourceById<Schema.Drawing>(sheet, sheet.drawing.id);
if (drawingFile != null)
{
LoadDrawingObjects(doc, sheet, rgSheet, drawingFile);
}
#if DEBUG
swDrawing.Stop();
#endif // DEBUG
}
#endif // DRAWING
#endregion // Drawing
#region Print Settings
#if PRINT
if (sheet.pageMargins != null)
{
rgSheet.PrintSettings.Margins = new Print.PageMargins(sheet.pageMargins.top,
sheet.pageMargins.bottom, sheet.pageMargins.left, sheet.pageMargins.bottom);
}
if (sheet.pageSetup != null)
{
rgSheet.PrintSettings.Landscape = sheet.pageSetup.orientation == "portrait";
}
if (sheet.rowBreaks != null && sheet.rowBreaks.breaks != null)
{
foreach (var rb in sheet.rowBreaks.breaks)
{
rgSheet.InsertRowPageBreak(rb.id, false);
}
}
if (sheet.colBreaks != null && sheet.colBreaks.breaks != null)
{
foreach (var cb in sheet.colBreaks.breaks)
{
rgSheet.InsertColumnPageBreak(cb.id, false);
}
}
#endif // PRINT
#endregion // Print Settings
#region Freeze
//#if FREEZE
if (sheetView != null && sheetView.pane != null)
{
int freezeRow = 0, freezeCol = 0;
if (sheetView.pane.ySplit != null)
{
int.TryParse(sheetView.pane.ySplit, out freezeRow);
}
if (sheetView.pane.xSplit != null)
{
int.TryParse(sheetView.pane.xSplit, out freezeCol);
}
if (freezeRow > 0 || freezeCol > 0)
{
rgSheet.FreezeToCell(new CellPosition(freezeRow, freezeCol));
}
}
//#endif // FREEZE
#endregion // Freeze
rgSheet.UpdateViewportController();
#if DEBUG
sw.Stop();
Logger.Log("excel format", "end iterating. cells: {0}, {1} ms.", cellCount, sw.ElapsedMilliseconds);
Debug.WriteLine(string.Format("Row Height : {0} ms.", swRowHeight.ElapsedMilliseconds));
Debug.WriteLine(string.Format("Row Style : {0} ms.", swRowStyle.ElapsedMilliseconds));
Debug.WriteLine(string.Format("Cell Style : {0} ms.", swStyle.ElapsedMilliseconds));
Debug.WriteLine(string.Format("Cell Border : {0} ms.", swBorder.ElapsedMilliseconds));
Debug.WriteLine(string.Format("Cell Value : {0} ms.", swValue.ElapsedMilliseconds));
Debug.WriteLine(string.Format("Cell Formula : {0} ms.", swFormula.ElapsedMilliseconds));
Debug.WriteLine(string.Format("Drawing : {0} ms.", swDrawing.ElapsedMilliseconds));
#if WINFORM
rgSheet._Debug_Validate_All();
#endif // WINFORM
#endif // DEBUG
}
#endregion // Worksheet
#region Style
private static void SetStyleFont(Document doc, WorksheetRangeStyle styleset, Schema.Font font)
{
SolidColor tempColor = new SolidColor();
if (font.name != null && !string.IsNullOrEmpty(font.name.value))
{
styleset.Flag |= PlainStyleFlag.FontName;
styleset.FontName = font.name.value;
}
float v;
if (font.size != null && float.TryParse(font.size, System.Globalization.NumberStyles.Float,
ExcelWriter.EnglishCulture, out v))
{
styleset.Flag |= PlainStyleFlag.FontSize;
styleset.FontSize = v;
}
if (font.bold != null)
{
styleset.Flag |= PlainStyleFlag.FontStyleBold;
styleset.Bold = true;
}
if (font.italic != null)
{
styleset.Flag |= PlainStyleFlag.FontStyleItalic;
styleset.Italic = true;
}
if (font.strikethrough != null)
{
styleset.Flag |= PlainStyleFlag.FontStyleStrikethrough;
styleset.Strikethrough = true;
}
if (font.strikethrough != null)
{
styleset.Flag |= PlainStyleFlag.FontStyleStrikethrough;
styleset.Strikethrough = true;
}
if (font.underline != null)
{
styleset.Flag |= PlainStyleFlag.FontStyleUnderline;
styleset.Underline = true;
}
if (ConvertFromIndexedColor(doc, font.color, ref tempColor))
{
styleset.Flag |= PlainStyleFlag.TextColor;
styleset.TextColor = tempColor;
}
}
private static void PreprocessCellStyle(Document doc, RGWorksheet rgSheet, CellFormat style,
FontCollection fonts, FillCollection fills)
{
WorksheetRangeStyle styleset = new WorksheetRangeStyle(rgSheet.RootStyle);
SolidColor tempColor = new SolidColor();
#region Font
if (//style.applyFont == "1" &&
!string.IsNullOrEmpty(style.fontId))
{
var font = fonts.list.ElementAtOrDefault(int.Parse(style.fontId)) as Schema.Font;
if (font != null)
{
SetStyleFont(doc, styleset, font);
}
}
#endregion // Font
#region Fill
if (//OpenXMLUtility.IsTrue(style.applyFill) &&
!string.IsNullOrEmpty(style.fillId))
{
var fill = fills.list.ElementAtOrDefault(int.Parse(style.fillId)) as Fill;
if (fill != null && fill.patternFill != null && fill.patternFill.patternType != null)
{
switch (fill.patternFill.patternType)
{
case "solid":
// solid pattern only use foregroundColor
if (ConvertFromIndexedColor(doc, fill.patternFill.foregroundColor, ref tempColor))
{
styleset.Flag |= PlainStyleFlag.BackColor;
styleset.BackColor = tempColor;
}
break;
case "darkHorizontal":
case "darkVertical":
case "darkDown":
case "darkUp":
case "darkGrid":
case "lightHorizontal":
case "lightVertical":
case "lightDown":
case "lightUp":
case "lightGrid":
case "lightTrellis":
case "darkTrellis":
SolidColor foreColor = SolidColor.Transparent;
tempColor = SolidColor.White;
if (ConvertFromIndexedColor(doc, fill.patternFill.foregroundColor, ref foreColor)
|| ConvertFromIndexedColor(doc, fill.patternFill.backgroundColor, ref tempColor))
{
styleset.Flag |= PlainStyleFlag.FillPattern | PlainStyleFlag.BackColor;
styleset.FillPatternStyle = HatchStyles.DottedDiamond;
styleset.FillPatternColor = foreColor;
styleset.BackColor = tempColor;
}
break;
}
}
}
#endregion // Fill
#region Alignment
if (//style.applyAlignment == "1" &&
style.alignment != null)
{
// vertical alignment
if (!string.IsNullOrEmpty(style.alignment.horizontal))
{
ReoGridHorAlign halign = ReoGridHorAlign.Left;
switch (style.alignment.horizontal)
{
default:
case "left":
halign = ReoGridHorAlign.Left;
break;
case "center":
halign = ReoGridHorAlign.Center;
break;
case "right":
halign = ReoGridHorAlign.Right;
break;
}
styleset.Flag |= PlainStyleFlag.HorizontalAlign;
styleset.HAlign = halign;
}
// horizontal alignment
//
// Excel does not have default vertical alignment,
// should always enter this switch
//if (!string.IsNullOrEmpty(style.alignment.vertical))
//{
ReoGridVerAlign valign = ReoGridVerAlign.General;
switch (style.alignment.vertical)
{
// Excel doesn't have general style
// Default is bottom
//
//case "general":
// valign = ReoGridVerAlign.General;
// break;
case "top":
valign = ReoGridVerAlign.Top;
break;
case "center":
valign = ReoGridVerAlign.Middle;
break;
default:
case "bottom":
valign = ReoGridVerAlign.Bottom;
break;
}
styleset.Flag |= PlainStyleFlag.VerticalAlign;
styleset.VAlign = valign;
// text wrap
if (TextFormatHelper.IsSwitchOn(style.alignment.wrapText))
{
styleset.Flag |= PlainStyleFlag.TextWrap;
styleset.TextWrapMode = TextWrapMode.WordBreak;
}
// text rotation
if (!string.IsNullOrEmpty(style.alignment.textRotation))
{
int angle;
if (int.TryParse(style.alignment.textRotation, out angle))
{
styleset.Flag |= PlainStyleFlag.RotationAngle;
if (angle > 90) angle = 90 - angle;
styleset.RotationAngle = angle;
}
}
// indent
if (!string.IsNullOrEmpty(style.alignment.indent))
{
ushort indent;
if (ushort.TryParse(style.alignment.indent, out indent))
{
styleset.Indent = indent;
}
}
}
#endregion // Alignment
if (styleset.Flag != PlainStyleFlag.None)
{
style._cachedStyleSet = styleset;
}
style._preprocessed = true;
}
#endregion // Style
#region Color
private static bool ConvertFromIndexedColor(Document doc, ColorValue color, ref SolidColor rgColor)
{
if (color == null) return false;
int rgbValue;
if (!string.IsNullOrEmpty(color.rgb)
&& int.TryParse(color.rgb, System.Globalization.NumberStyles.AllowHexSpecifier, null, out rgbValue))
{
rgColor = SolidColor.FromRGB(rgbValue);
return true;
}
int themeIndex;
double tint;
if (!string.IsNullOrEmpty(color.theme)
&& int.TryParse(color.theme, out themeIndex)
&& themeIndex >= 0)
{
var theme = doc.Themesheet;
if (theme != null)
{
if (theme.elements != null
&& theme.elements.clrScheme != null)
{
switch (themeIndex)
{
case 0: rgColor = SolidColor.White; break;// doc.ConvertFromCompColor(theme.elements.clrScheme.dk1); break;
case 1: rgColor = SolidColor.Black; break;// doc.ConvertFromCompColor(theme.elements.clrScheme.lt1); break;
case 2: rgColor = doc.ConvertFromCompColor(theme.elements.clrScheme.dk2); break;
case 3: rgColor = doc.ConvertFromCompColor(theme.elements.clrScheme.lt2); break;
case 4: rgColor = doc.ConvertFromCompColor(theme.elements.clrScheme.accent1); break;
case 5: rgColor = doc.ConvertFromCompColor(theme.elements.clrScheme.accent2); break;
case 6: rgColor = doc.ConvertFromCompColor(theme.elements.clrScheme.accent3); break;
case 7: rgColor = doc.ConvertFromCompColor(theme.elements.clrScheme.accent4); break;
case 8: rgColor = doc.ConvertFromCompColor(theme.elements.clrScheme.accent5); break;
case 9: rgColor = doc.ConvertFromCompColor(theme.elements.clrScheme.accent6); break;
case 10: rgColor = doc.ConvertFromCompColor(theme.elements.clrScheme.hlink); break;
case 11: rgColor = doc.ConvertFromCompColor(theme.elements.clrScheme.folHlink); break;
default: rgColor = SolidColor.Black; break;
}
if (double.TryParse(color.tint, out tint))
{
HSLColor hlsColor = ColorUtility.RGBToHSL(rgColor);
hlsColor.L = ColorUtility.CalculateFinalLumValue((float)tint, (float)hlsColor.L * 255f) / 255f;
rgColor = ColorUtility.HSLToRgb(hlsColor);
}
return true;
}
}
}
int colorIndex;
if (!string.IsNullOrEmpty(color.indexed)
&& int.TryParse(color.indexed, out colorIndex)
&& colorIndex >= 0)
{
switch (colorIndex)
{
case 64: // System Foreground
rgColor = StaticResources.SystemColor_WindowText;
return true;
case 65: // System Background
rgColor = StaticResources.SystemColor_Window;
return true;
default:
{
if (doc.Stylesheet.colors != null
&& doc.Stylesheet.colors.indexedColors != null
&& colorIndex < doc.Stylesheet.colors.indexedColors.Count
&& int.TryParse(doc.Stylesheet.colors.indexedColors[colorIndex].rgb,
System.Globalization.NumberStyles.AllowHexSpecifier, null, out rgbValue))
{
rgColor = SolidColor.FromArgb(rgbValue);
return true;
}
else if (colorIndex < IndexedColorTable.colors.Length)
{
rgColor = SolidColor.FromRGB(IndexedColorTable.colors[colorIndex]);
return true;
}
}
break;
}
}
return false;
}
#endregion // Color
#region Border
private static void PreprocessCellBorders(Document doc, Border border)
{
border._hasTop = ConvertFromExcelBorder(doc, border.top, ref border._top);
border._hasBottom = ConvertFromExcelBorder(doc, border.bottom, ref border._bottom);
border._hasLeft = ConvertFromExcelBorder(doc, border.left, ref border._left);
border._hasRight = ConvertFromExcelBorder(doc, border.right, ref border._right);
border._preprocessed = true;
}
private static void SetRGRangeBorders(Document doc, RGWorksheet rgSheet, RangePosition range, Border border)
{
RangeBorderStyle posStyle = new RangeBorderStyle();
if (ConvertFromExcelBorder(doc, border.top, ref posStyle))
{
rgSheet.SetRangeBorders(range, BorderPositions.Top, posStyle, false);
}
if (ConvertFromExcelBorder(doc, border.bottom, ref posStyle))
{
rgSheet.SetRangeBorders(range, BorderPositions.Bottom, posStyle, false);
}
if (ConvertFromExcelBorder(doc, border.left, ref posStyle))
{
rgSheet.SetRangeBorders(range, BorderPositions.Left, posStyle, false);
}
if (ConvertFromExcelBorder(doc, border.right, ref posStyle))
{
rgSheet.SetRangeBorders(range, BorderPositions.Right, posStyle, false);
}
}
private static bool ConvertFromExcelBorder(Document doc, SideBorder sideBorder, ref RangeBorderStyle rgStyle)
{
if (sideBorder != null && !string.IsNullOrEmpty(sideBorder.style))
{
SolidColor color = new SolidColor();
rgStyle.Style = ConvertFromExcelBorderStyle(sideBorder.style);
if (sideBorder.color == null)
{
rgStyle.Color = SolidColor.Black;
return true;
}
else if (ConvertFromIndexedColor(doc, sideBorder.color, ref color))
{
rgStyle.Color = color;
return true;
}
else if (OpenXMLUtility.IsTrue(sideBorder.color.auto))
{
rgStyle.Color = SolidColor.Black;
return true;
}
}
return false;
}
private static BorderLineStyle ConvertFromExcelBorderStyle(string ebStyle)
{
switch (ebStyle)
{
default:
case "thin":
return BorderLineStyle.Solid;
case "medium":
return BorderLineStyle.BoldSolid;
case "thick":
return BorderLineStyle.BoldSolidStrong;
case "hair":
return BorderLineStyle.Dotted;
case "dashed":
return BorderLineStyle.Dashed;
case "dotted":
return BorderLineStyle.Dashed2;
case "double":
return BorderLineStyle.DoubleLine;
case "mediumDashed":
return BorderLineStyle.BoldDashed;
case "mediumDashDot":
return BorderLineStyle.BoldDashDot;
case "mediumDashDotDot":
return BorderLineStyle.BoldDashDotDot;
case "dashDot":
return BorderLineStyle.DashDot;
case "dashDotDot":
return BorderLineStyle.DashDotDot;
case "slantDashDot": // not supported in ReoGrid yet
return BorderLineStyle.BoldDashDotDot;
}
}
#endregion
#region Data Format
//private static Regex numberFormatRegex = new Regex("0*\\.{[0]+}");
private static Regex currencyFormatRegex = new Regex(@"([^\\\s]*)\\?(\s*)\[\$([^(\-|\])]+)-?[^\]]*\]\\?(\s*)([^\\\s]*)", RegexOptions.Compiled);
private static NumberDataFormatter.INumberFormatArgs ReadNumberFormatArgs(string pattern, NumberDataFormatter.INumberFormatArgs arg)
{
if (pattern.StartsWith("[Red]", StringComparison.CurrentCultureIgnoreCase))
{
// add red style
arg.NegativeStyle |= NumberDataFormatter.NumberNegativeStyle.Red;
// remove minus symbol
arg.NegativeStyle &= ~NumberDataFormatter.NumberNegativeStyle.Minus;
pattern = pattern.Substring(5);
}
if (pattern.StartsWith("\""))
{
int index = pattern.IndexOf('"', 1);
string prefix = pattern.Substring(1, index - 1);
if (prefix == "▲ ")
{
// add sankaku symbol
arg.NegativeStyle |= NumberDataFormatter.NumberNegativeStyle.Prefix_Sankaku;
// remove minus symbol
arg.NegativeStyle &= ~NumberDataFormatter.NumberNegativeStyle.Minus;
}
else
{
arg.CustomNegativePrefix = prefix;
}
pattern = pattern.Substring(index + 1);
}
if (pattern.StartsWith("\\(") && pattern.EndsWith("\\)"))
{
// add bracket style
arg.NegativeStyle |= NumberDataFormatter.NumberNegativeStyle.Brackets;
// remove minus symbol
arg.NegativeStyle &= ~NumberDataFormatter.NumberNegativeStyle.Minus;
pattern = pattern.Substring(2, pattern.Length - 4);
}
var culture = System.Threading.Thread.CurrentThread.CurrentCulture;
int len = pattern.Length;
int decimalSeparatorIndex = pattern.LastIndexOf(culture.NumberFormat.NumberDecimalSeparator, len - 1);
if (decimalSeparatorIndex >= 0 && decimalSeparatorIndex < len - 1)
{
arg.DecimalPlaces = (short)(len - 1 - decimalSeparatorIndex);
}
else
{
arg.DecimalPlaces = 0;
}
arg.UseSeparator = (pattern.IndexOf(culture.NumberFormat.NumberGroupSeparator) > 0);
return arg;
}
enum NumberFormatParseStatus
{
Segment,
InString,
}
enum NumberFormatSegmentDefines
{
Positive = 0,
Negative = 1,
Zero = 2,
Text = 3,
}
private static CellDataFormatFlag SetRGSheetDataFormat(RGWorksheet rgSheet, Cell cell, int formatId, Stylesheet styles)
{
CellDataFormatFlag flag = CellDataFormatFlag.General;
if (BuiltinNumberFormats.SetFromExcelBuiltinFormat(rgSheet, cell, formatId, out flag))
{
return flag;
}
if (styles.numberFormats != null)
{
var numFormat = styles.numberFormats.list.FirstOrDefault(nf => nf.formatId == formatId) as NumberFormat;
if (numFormat != null)
{
string[] patterns = numFormat.formatCode.Split(';');
if (patterns != null && patterns.Length > 0)
{
object arg = null;
Match currencyMatch = null;
var pattern = patterns[0];
if (pattern.StartsWith("\"$\""))
{
flag = CellDataFormatFlag.Currency;
string param = pattern.Substring(3);
if (patterns.Length >= 2) { param = patterns[1]; }
var carg = (CurrencyDataFormatter.CurrencyFormatArgs)ReadNumberFormatArgs(
param, new CurrencyDataFormatter.CurrencyFormatArgs());
carg.PrefixSymbol = "$";
arg = carg;
}
// #,##0.00 [$-419E] #,##0.00
else if ((currencyMatch = currencyFormatRegex.Match(pattern)).Success)
{
#region Currency
flag = CellDataFormatFlag.Currency;
var carg = new CurrencyDataFormatter.CurrencyFormatArgs();
if (currencyMatch.Groups[1].Length > 0)
{
if (currencyMatch.Groups[3].Success)
{
carg.PostfixSymbol = currencyMatch.Groups[3].Value;
}
if (currencyMatch.Groups[2].Length > 0)
{
carg.PostfixSymbol = currencyMatch.Groups[2].Value + carg.PostfixSymbol;
}
carg = (CurrencyDataFormatter.CurrencyFormatArgs)ReadNumberFormatArgs(currencyMatch.Groups[1].Value, carg);
}
else if (currencyMatch.Groups[5].Length > 0)
{
if (currencyMatch.Groups[3].Success)
{
carg.PrefixSymbol = currencyMatch.Groups[3].Value;
}
if (currencyMatch.Groups[4].Length > 0)
{
carg.PrefixSymbol += currencyMatch.Groups[4].Value;
}
carg = (CurrencyDataFormatter.CurrencyFormatArgs)ReadNumberFormatArgs(currencyMatch.Groups[5].Value, carg);
}
arg = carg;
#endregion // Currency
}
else if (pattern.EndsWith("%"))
{
#region Percent
flag = CellDataFormatFlag.Percent;
pattern = pattern.Substring(0, pattern.Length - 1);
arg = ReadNumberFormatArgs(pattern, new NumberDataFormatter.NumberFormatArgs());
#endregion // Percent
}
else if (pattern.Any(c => c == 'm' || c == 'h' || c == 's' || c == 'y' || c == 'd'))
{
pattern = pattern.Replace("yyyy/mm", "yyyy/MM").Replace("mm/yy", "MM/yy")
.Replace("mm/d", "MM/d").Replace("m/d", "M/d")
.Replace("d/mm", "d/MM").Replace("d/m", "d/M")
.Replace("aaa", "ddd");
flag = CellDataFormatFlag.DateTime;
arg = new DateTimeDataFormatter.DateTimeFormatArgs
{
Format = pattern,
};
}
else
{
flag = CellDataFormatFlag.Number;
arg = ReadNumberFormatArgs(patterns.Length > 1 ? patterns[1] : patterns[0], new NumberDataFormatter.NumberFormatArgs());
}
if (flag != CellDataFormatFlag.General)
{
//rgSheet.SetCellDataFormat(cell, flag, ref arg, );
cell.DataFormat = flag;
cell.DataFormatArgs = arg;
}
}
}
}
return flag;
}
#endregion
#region Drawing
#if DRAWING
private static void LoadDrawingObjects(Document doc, Schema.Worksheet sheet, RGWorksheet rgSheet, Schema.Drawing drawingFile)
{
foreach (var archor in drawingFile.twoCellAnchors)
{
DrawingObject obj = null;
if (archor.pic != null)
{
obj = LoadImage(doc, rgSheet, archor.pic, drawingFile);
}
else
if (archor.shape != null)
{
obj = LoadShape(doc, rgSheet, archor.shape);
}
else if (archor.cxnShape != null)
{
obj = LoadShape(doc, rgSheet, archor.cxnShape);
}
else if (archor.graphcFrame != null)
{
obj = LoadGraphic(doc, rgSheet, drawingFile, archor.graphcFrame);
}
if (obj != null)
{
obj.Bounds = GetDrawingBounds(rgSheet, archor);
rgSheet.FloatingObjects.Add(obj);
}
}
}
private static void SetDrawingObjectStyle(Document doc, DrawingObject obj, Schema.Shape shape)
{
var theme = doc.Themesheet;
if (theme == null || theme.elements == null
|| theme.elements.fmtScheme == null)
{
return;
}
var style = shape.style;
var prop = shape.prop;
// line color
bool overrideFill = false;
bool overrideLineWeight = false;
bool overrideLineStyle = false;
bool overrideLineColor = false;
if (prop != null)
{
#region Line
if (prop.line != null)
{
if (prop.line.solidFill != null)
{
obj.LineColor = doc.ConvertFromCompColor(prop.line.solidFill);
overrideLineColor = true;
}
else if (prop.line.noFill != null)
{
obj.LineColor = SolidColor.Transparent;
overrideLineColor = true;
}
if (prop.line.weight != null)
{
int weight;
if (int.TryParse(prop.line.weight, out weight))
{
obj.LineWidth = MeasureToolkit.EMUToPixel(weight, PlatformUtility.GetDPI());
overrideLineWeight = true;
}
}
if (prop.line.prstDash != null)
{
Graphics.LineStyles lineStyle;
if (ConvertFromDashStyle(prop.line.prstDash.value, out lineStyle))
{
obj.LineStyle = lineStyle;
overrideLineStyle = true;
}
}
}
#endregion // Line
if (prop.solidFill != null)
{
obj.FillColor = doc.ConvertFromCompColor(prop.solidFill, prop.solidFill);
overrideFill = true;
}
else if (prop.noFill != null)
{
obj.FillColor = SolidColor.Transparent;
overrideFill = true;
}
}
#region Style
if (style != null)
{
var lnRef = style.lnRef;
if (lnRef != null && !string.IsNullOrEmpty(lnRef.idx))
{
int index = -1;
int.TryParse(lnRef.idx, out index);
if (theme.elements.fmtScheme != null
&& theme.elements.fmtScheme.lineStyles != null
&& index > 0 && index <= theme.elements.fmtScheme.lineStyles.Count)
{
var refLineStyle = theme.elements.fmtScheme.lineStyles[index - 1];
if (!overrideLineColor && refLineStyle.solidFill != null && refLineStyle.solidFill.schemeColor != null)
{
obj.LineColor = doc.ConvertFromCompColor(refLineStyle.solidFill, style.lnRef);
}
if (!overrideLineWeight)
{
obj.LineWidth = MeasureToolkit.EMUToPixel(refLineStyle.weight, PlatformUtility.GetDPI());
}
if (!overrideLineStyle && refLineStyle.prstDash != null)
{
Graphics.LineStyles lineStyle;
ConvertFromDashStyle(refLineStyle.prstDash.value, out lineStyle);
obj.LineStyle = lineStyle;
}
}
}
if (!overrideFill && style.fillRef != null && !string.IsNullOrEmpty(style.fillRef.idx))
{
int index = -1;
int.TryParse(style.fillRef.idx, out index);
if (theme.elements.fmtScheme != null
&& theme.elements.fmtScheme.fillStyles != null
&& index > 0 && index <= theme.elements.fmtScheme.fillStyles.Count)
{
var fillStyle = theme.elements.fmtScheme.fillStyles[index - 1];
if (fillStyle is CompColor)
{
obj.FillColor = doc.ConvertFromCompColor((CompColor)fillStyle, style.fillRef);
}
else if (fillStyle is GradientFill)
{
var gf = (GradientFill)fillStyle;
if (gf.gsLst.Count > 0)
{
var gs = gf.gsLst[gf.gsLst.Count / 2];
obj.FillColor = doc.ConvertFromCompColor(gs, style.fillRef);
}
}
}
}
if (style.fontRef != null)
{
}
}
#endregion Style
if (prop != null && prop.transform != null)
{
if (OpenXMLUtility.IsTrue(prop.transform.flipV))
{
if (obj is Drawing.Shapes.ShapeObject)
{
obj.ScaleY = -1;
}
}
}
}
private static bool ConvertFromDashStyle(string val, out Graphics.LineStyles lineStyle)
{
switch (val)
{
case "dash":
lineStyle = Graphics.LineStyles.Dash;
return true;
default:
lineStyle = Graphics.LineStyles.Solid;
return false;
}
}
#region Image
private static ImageObject LoadImage(Document doc, RGWorksheet rgSheet, Pic pic, Schema.Drawing drawingFile)
{
var blipFill = pic.blipFill;
if (blipFill != null)
{
var blip = pic.blipFill.blip;
if (blip != null && !string.IsNullOrEmpty(blip.embedId) && drawingFile._relationFile != null)
{
var relation = drawingFile._relationFile.relations.FirstOrDefault(r => r.id == blip.embedId);
var finalPath = RelativePathUtility.GetRelativePath(drawingFile._path, relation.target);
var stream = doc.GetResourceStream(finalPath);
if (stream != null)
{
#if WINFORM
System.Drawing.Image image = null;
try
{
image = System.Drawing.Image.FromStream(stream, false);
// note: cannot print when use 'using'
//using (var fs = new MemoryStream(40960))
var fs = new MemoryStream(40960);
{
image.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
image.Dispose();
fs.Position = 0;
image = System.Drawing.Image.FromStream(fs);
}
}
catch { }
stream.Dispose();
if (image != null)
{
return new ImageObject(image);
}
#elif WPF
try
{
System.Windows.Media.Imaging.BitmapImage biImg = new System.Windows.Media.Imaging.BitmapImage();
biImg.BeginInit();
biImg.StreamSource = stream;
biImg.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
biImg.EndInit();
//stream.Dispose();
System.Windows.Media.ImageSource image = biImg as System.Windows.Media.ImageSource;
return image == null ? null : new ImageObject(image);
}
catch { }
#endif // WINFORM
}
}
}
return null;
}
#endregion // Image
#region LoadShape
private static Drawing.DrawingObject LoadShape(Document doc, RGWorksheet rgSheet, Schema.Shape shape)
{
DrawingObject obj = null;
var prop = shape.prop;
// create shape
if (prop != null && prop.prstGeom != null)
{
switch (prop.prstGeom.presetType)
{
case "rect": obj = new Drawing.Shapes.RectangleShape(); break;
case "roundRect":
Drawing.Shapes.RoundedRectangleShape roundRect = new Drawing.Shapes.RoundedRectangleShape();
if (shape.prop.prstGeom.avList != null)
{
var adj = shape.prop.prstGeom.avList.FirstOrDefault(gd => gd.name == "adj");
if (adj != null)
{
if (adj.formula.StartsWith("val "))
{
int rate = -1;
int.TryParse(adj.formula.Substring(4), out rate);
if (rate >= 0)
{
roundRect.RoundRate = (float)rate / 50000f;
}
}
}
}
obj = roundRect;
break;
case "diamond": obj = new Drawing.Shapes.DiamondShape(); break;
case "ellipse": obj = new Drawing.Shapes.EllipseShape(); break;
case "line":
case "straightConnector1":
obj = LoadLine(prop);
break;
}
}
// set style
if (obj != null)
{
SetDrawingObjectStyle(doc, obj, shape);
}
if (obj is Drawing.Shapes.ShapeObject)
{
// text
if (shape.textBody != null)
{
if (shape.textBody.paragraphs != null)
{
var rgShape = (Drawing.Shapes.ShapeObject)obj;
rgShape.RichText = CreateRichTextFromRuns(doc, shape.textBody.paragraphs);
var sb = new StringBuilder();
RGFloat fontSize = 11.0f;
foreach (var p in shape.textBody.paragraphs)
{
if (p.runs != null)
{
foreach (var r in p.runs)
{
if (r.text != null
&& !string.IsNullOrEmpty(r.text.innerText))
{
var runPr = r.property;
if (runPr != null)
{
int size = 0;
if (int.TryParse(runPr.sizeAttr, out size))
{
fontSize = (float)size / 133f;
}
}
sb.Append(r.text.innerText);
}
}
sb.Append(Environment.NewLine);
}
}
rgShape.Text = sb.ToString();
rgShape.FontSize = fontSize;
if (shape.textBody.bodyProperty != null)
{
if (shape.textBody.bodyProperty.anchor != null)
{
switch (shape.textBody.bodyProperty.anchor)
{
case "t":
if (rgShape.RichText != null)
{
rgShape.RichText.VerticalAlignment = ReoGridVerAlign.Top;
}
break;
default:
if (rgShape.RichText != null)
{
rgShape.RichText.VerticalAlignment = ReoGridVerAlign.Middle;
}
break;
case "b":
if (rgShape.RichText != null)
{
rgShape.RichText.VerticalAlignment = ReoGridVerAlign.Bottom;
}
break;
}
}
}
}
}
}
return obj;
}
private static Drawing.Shapes.Line LoadLine(ShapeProperty prop)
{
Drawing.Shapes.Line line = new Drawing.Shapes.Line();
var xfrm = prop.transform;
if (xfrm != null)
{
RGFloat dpi = PlatformUtility.GetDPI();
Rectangle bounds = new Rectangle(MeasureToolkit.EMUToPixel(xfrm.offset.x, dpi), MeasureToolkit.EMUToPixel(xfrm.offset.y, dpi),
MeasureToolkit.EMUToPixel(xfrm.extents.cx, dpi), MeasureToolkit.EMUToPixel(xfrm.extents.cy, dpi));
RGFloat startX, startY, endX, endY;
if (OpenXMLUtility.IsTrue(xfrm.flipV))
{
startY = bounds.Bottom;
endY = bounds.Top;
}
else
{
startY = bounds.Top;
endY = bounds.Bottom;
}
if (OpenXMLUtility.IsTrue(xfrm.flipH))
{
startX = bounds.Right;
endX = bounds.Left;
}
else
{
startX = bounds.Left;
endX = bounds.Right;
}
line.StartPoint = new Point(startX, startY);
line.EndPoint = new Point(endX, endY);
}
if (prop.line != null)
{
if (prop.line.headEnd != null
&& !string.IsNullOrEmpty(prop.line.headEnd.type))
{
switch (prop.line.headEnd.type)
{
case "triangle":
line.StartCap = LineCapStyles.Arrow;
break;
}
}
if (prop.line.tailEnd != null
&& !string.IsNullOrEmpty(prop.line.tailEnd.type))
{
switch (prop.line.tailEnd.type)
{
case "triangle":
line.EndCap = LineCapStyles.Arrow;
break;
}
}
}
return line;
}
#endregion // LoadShape
#region GetDrawingBounds
private static Rectangle GetDrawingBounds(RGWorksheet rgSheet, TwoCellAnchor archor)
{
if (archor.to.row >= rgSheet.RowCount)
{
rgSheet.AppendRows(archor.to.row - rgSheet.RowCount + 1);
}
if (archor.to.col >= rgSheet.ColumnCount)
{
rgSheet.AppendCols(archor.to.col - rgSheet.ColumnCount + 1);
}
RGFloat dpi = PlatformUtility.GetDPI();
RGFloat sxoff = MeasureToolkit.EMUToPixel(archor.from.colOff, dpi);
RGFloat syoff = MeasureToolkit.EMUToPixel(archor.from.rowOff, dpi);
Debug.Assert(sxoff >= 0 && syoff >= 0);
Point start = rgSheet.GetCellPhysicsPosition(archor.from.row, archor.from.col);
start.X += sxoff;
start.Y += syoff;
RGFloat exoff = MeasureToolkit.EMUToPixel(archor.to.colOff, dpi);
RGFloat eyoff = MeasureToolkit.EMUToPixel(archor.to.rowOff, dpi);
Debug.Assert(exoff >= 0 && eyoff >= 0);
Point end = rgSheet.GetCellPhysicsPosition(archor.to.row, archor.to.col);
end.X += exoff;
end.Y += eyoff;
return new Rectangle(start, end);
}
#endregion // GetDrawingBounds
#region LoadGraphic
private static Drawing.DrawingObject LoadGraphic(Document doc, RGWorksheet rgSheet, Schema.Drawing drawingFile, Schema.GraphicFrame graphicFrame)
{
var graphic = graphicFrame.graphic;
if (graphic != null && graphic.data != null)
{
switch (graphic.data.uri)
{
case OpenXMLNamespaces.Chart________:
if (graphic.data.chart != null
&& !string.IsNullOrEmpty(graphic.data.chart.id))
{
var xmlChart = doc.LoadRelationResourceById<Schema.ChartSpace>(drawingFile, graphic.data.chart.id);
if (xmlChart != null)
{
return LoadChart(rgSheet, xmlChart);
}
}
break;
}
}
return null;
}
#endregion // LoadGraphic
#region Chart
private static Chart.Chart LoadChart(RGWorksheet rgSheet, Schema.ChartSpace chartSpace)
{
if (chartSpace.chart == null) return null;
var chart = chartSpace.chart;
var plot = chart.plotArea;
if (plot == null) return null;
Chart.Chart rgChart = null;
Chart.WorksheetChartDataSource dataSource = new Chart.WorksheetChartDataSource(rgSheet);
if (plot.lineChart != null)
{
#region Line Chart Plot Area
if (plot.lineChart.serials != null)
{
foreach (var ser in plot.lineChart.serials)
{
ReadDataSerial(dataSource, rgSheet, ser);
}
}
rgChart = new Chart.LineChart()
{
DataSource = dataSource,
};
#endregion // Line Chart Plot Area
}
else if (plot.barChart != null)
{
#region Column/Bar Chart Plot Area
if (plot.barChart.serials != null)
{
foreach (var ser in plot.barChart.serials)
{
ReadDataSerial(dataSource, rgSheet, ser);
}
}
if (plot.barChart.barDir != null
&& plot.barChart.barDir.value == "col")
{
rgChart = new Chart.ColumnChart();
}
else
{
rgChart = new Chart.BarChart();
}
rgChart.DataSource = dataSource;
#endregion // Column Chart Plot Area
}
else if (plot.pieChart != null)
{
#region Pie Chart Plot Area
if (plot.pieChart.serials != null)
{
foreach (var ser in plot.pieChart.serials)
{
ReadDataSerial(dataSource, rgSheet, ser);
}
}
rgChart = new Chart.PieChart()
{
DataSource = dataSource,
};
#endregion // Pie Chart Plot Area
}
else if (plot.doughnutChart != null)
{
#region Doughnut Chart Plot Area
if (plot.doughnutChart.serials != null)
{
foreach (var ser in plot.doughnutChart.serials)
{
ReadDataSerial(dataSource, rgSheet, ser);
}
}
rgChart = new Chart.DoughnutChart()
{
DataSource = dataSource,
};
#endregion // Pie Chart Plot Area
}
else if (plot.areaChart != null)
{
#region Area Chart Plot Area
if (plot.areaChart.serials != null)
{
foreach (var ser in plot.areaChart.serials)
{
ReadDataSerial(dataSource, rgSheet, ser);
}
}
rgChart = new Chart.AreaChart()
{
DataSource = dataSource,
};
#endregion // Area Chart Plot Area
}
bool showLegend = false;
if (chart.legend != null)
{
if (chart.legend.legendPos != null)
{
showLegend = true;
}
}
rgChart.ShowLegend = showLegend;
return rgChart;
}
private static Chart.WorksheetChartDataSerial ReadDataSerial(Chart.WorksheetChartDataSource dataSource,
RGWorksheet rgSheet, IChartSerial serial)
{
if (serial == null) return null;
#if FORMULA
CellPosition labelAddress = CellPosition.Empty;
var label = serial.ChartLabel;
if (label != null
&& label.strRef != null)
{
if (label.strRef.formula != null
&& !string.IsNullOrEmpty(label.strRef.formula))
{
var serialNameVal = Formula.Evaluator.Evaluate(rgSheet.workbook, label.strRef.formula);
if (serialNameVal.type == Formula.FormulaValueType.Cell)
{
labelAddress = (CellPosition)serialNameVal.value;
}
}
//if (label.strRef.strCache != null
// && label.strRef.strCache.ptList != null
// && label.strRef.strCache.ptList.Count > 0)
//{
// var pt = label.strRef.strCache.ptList[0];
// if (pt.value != null)
// {
// serialName = pt.value.val;
// }
//}
}
var values = serial.Values;
if (values.numRef != null
&& values.numRef.formula != null
&& !string.IsNullOrEmpty(values.numRef.formula))
{
var dataRangeVal = Formula.Evaluator.Evaluate(rgSheet.workbook, values.numRef.formula);
if (dataRangeVal.type == Formula.FormulaValueType.Range)
{
var range = (RangePosition)dataRangeVal.value;
if (serial is PieChartSerial)
{
// transfer to multiple serials
for (int r = range.Row; r <= range.EndRow; r++)
{
dataSource.AddSerial(rgSheet, labelAddress, new RangePosition(r, range.Col, 1, 1));
}
}
else
{
dataSource.AddSerial(rgSheet, labelAddress, range);
}
}
}
#endif // FORMULA
return null;
}
#endregion // Chart
#endif // DRAWING
#endregion // Drawing
#region RichText
#if DRAWING
private static RichText CreateRichTextFromRuns(Document doc, IEnumerable<Paragraph> paragraphs)
{
var rt = new RichText();
foreach (var p in paragraphs)
{
foreach (var run in p.runs)
{
AddRunIntoRichText(doc, rt, run);
}
if (p.property != null)
{
if (p.property.align != null)
{
switch (p.property.align)
{
case "ctr":
rt.SetStyles(halign: ReoGridHorAlign.Center);
break;
}
}
}
rt.NewLine();
}
return rt;
}
private static void AddRunIntoRichText(Document doc, RichText rt, Run r)
{
if (string.IsNullOrEmpty(r.text.innerText))
{
// FIXME: need support to read single white space XML text
// https://github.com/unvell/ReoGrid/issues/29
return;
}
string fontName = null;
RGFloat fontSize = 8.5f;
SolidColor foreColor = SolidColor.Black;
SolidColor backColor = SolidColor.Transparent;
Drawing.Text.FontStyles fontStyles = Drawing.Text.FontStyles.Regular;
#region Run Property
var rpr = r.property;
if (rpr != null)
{
fontName = rpr.font;
if (rpr.size != null)
{
RGFloat.TryParse(rpr.size, out fontSize);
}
else if (rpr.sizeAttr != null)
{
int intFontSize = 11;
int.TryParse(rpr.sizeAttr, out intFontSize);
fontSize = intFontSize / 100f;
}
#if DEBUG
else
{
Debug.Assert(false); // not found font size
}
#endif // DEBUG
if (rpr.color != null)
{
ConvertFromIndexedColor(doc, rpr.color, ref foreColor);
}
else if (rpr.solidFill != null)
{
foreColor = doc.ConvertFromCompColor(rpr.solidFill);
}
if (rpr.b != null)
{
fontStyles |= Drawing.Text.FontStyles.Bold;
}
if (rpr.i != null)
{
fontStyles |= Drawing.Text.FontStyles.Italic;
}
if (rpr.u != null)
{
fontStyles |= Drawing.Text.FontStyles.Underline;
}
if (rpr.vertAlign != null)
{
if (rpr.vertAlign.value == "superscript")
{
fontStyles |= Drawing.Text.FontStyles.Superscrit;
}
else if (rpr.vertAlign.value == "subscript")
{
fontStyles |= Drawing.Text.FontStyles.Subscript;
}
}
}
#endregion // Run Property
int nlIndex = r.text.innerText.IndexOf('\n');
if (nlIndex > -1)
{
rt.AddText(r.text.innerText.Substring(0, nlIndex), fontName, fontSize, fontStyles, foreColor, backColor);
rt.NewLine();
rt.AddText(r.text.innerText.Substring(nlIndex + 1), fontName, fontSize, fontStyles, foreColor, backColor);
}
else
{
rt.AddText(r.text.innerText, fontName, fontSize, fontStyles, foreColor, backColor);
}
}
#endif // DRAWING
#endregion // RichText
}
class SharedFormulaInfo
{
internal CellPosition pos;
internal string formula;
}
#endregion // Reader
#region IndexedColors
sealed class IndexedColorTable
{
#region Colors
public static readonly int[] colors = new int[] {
0x000000, // 0
0xFFFFFF, // 1
0xFF0000, // 2
0x00FF00, // 3
0x0000FF, // 4
0xFFFF00, // 5
0xFF00FF, // 6
0x00FFFF, // 7
0x000000, // 8
0xFFFFFF,
0xFF0000, // 10
0x00FF00,
0x0000FF, // 12
0xFFFF00,
0xFF00FF, // 14
0x00FFFF,
0x800000, // 16
0x008000,
0x000080, // 18
0x808000,
0x800080, // 20
0x008080,
0xC0C0C0, // 22
0x808080,
0x9999FF, // 24
0x993366,
0xFFFFCC, // 26
0xCCFFFF,
0x660066, // 28
0xFF8080,
0x0066CC, // 30
0xCCCCFF,
0x000080, // 32
0xFF00FF,
0xFFFF00,
0x00FFFF,
0x800080, // 36
0x800000,
0x008080,
0x0000FF,
0x00CCFF, // 40
0xCCFFFF,
0xCCFFCC,
0xFFFF99,
0x99CCFF, // 44
0xFF99CC,
0xCC99FF,
0xFFCC99, // 47
0x3366FF,
0x33CCCC, // 49
0x99CC00, // 50
0xFFCC00,
0xFF9900,
0xFF6600,
0x666699, // 54
0x969696,
0x003366,
0x339966, // 57
0x003300,
0x333300,
0x993300, // 60
0x993366,
0x333399,
0x333333,
//0x0, // 64: System Foreground
//0x0, // 65: System Background
};
#endregion // Colors
}
#endregion // IndexedColors
#region Builtin Number Formats
sealed class BuiltinNumberFormats
{
public static bool SetFromExcelBuiltinFormat(RGWorksheet rgSheet, Cell cell, int formatId, out CellDataFormatFlag dataFormatFlag)
{
CellDataFormatFlag? format = null;
object arg = null;
switch (formatId)
{
case 0: // General
format = CellDataFormatFlag.General;
break;
case 1: // 0
format = CellDataFormatFlag.Number;
arg = new NumberDataFormatter.NumberFormatArgs { DecimalPlaces = 0, UseSeparator = false };
break;
case 2: // 0.00
case 11: // 0.00E+00
format = CellDataFormatFlag.Number;
arg = new NumberDataFormatter.NumberFormatArgs { DecimalPlaces = 2, UseSeparator = false };
break;
case 3: // #,##0
format = CellDataFormatFlag.Number;
arg = new NumberDataFormatter.NumberFormatArgs { DecimalPlaces = 0, UseSeparator = true };
break;
case 4: // #,##0.00
format = CellDataFormatFlag.Number;
arg = new NumberDataFormatter.NumberFormatArgs { DecimalPlaces = 2, UseSeparator = true };
break;
case 9: // 0%
format = CellDataFormatFlag.Percent;
arg = new NumberDataFormatter.NumberFormatArgs { DecimalPlaces = 0, UseSeparator = false };
break;
case 10: // 0.00%
format = CellDataFormatFlag.Percent;
arg = new NumberDataFormatter.NumberFormatArgs { DecimalPlaces = 2, UseSeparator = false };
break;
case 14:
// openxml spec: mm-dd-yy
// Excel implementation: m/d/yyyy
format = CellDataFormatFlag.DateTime;
arg = new DateTimeDataFormatter.DateTimeFormatArgs
{
CultureName = "en-US",
Format = "M/d/yyyy",
};
break;
case 15: // d-mmm-yy
format = CellDataFormatFlag.DateTime;
arg = new DateTimeDataFormatter.DateTimeFormatArgs
{
CultureName = "en-US",
Format = "d-MMM-yy",
};
break;
case 16: // d-mmm
format = CellDataFormatFlag.DateTime;
arg = new DateTimeDataFormatter.DateTimeFormatArgs
{
CultureName = "en-US",
Format = "d-MMM",
};
break;
case 17: // mmm-yy
format = CellDataFormatFlag.DateTime;
arg = new DateTimeDataFormatter.DateTimeFormatArgs
{
CultureName = "en-US",
Format = "MMM-yy",
};
break;
case 18: // h:mm AM/PM
format = CellDataFormatFlag.DateTime;
arg = new DateTimeDataFormatter.DateTimeFormatArgs
{
CultureName = "en-US",
Format = "h:mm tt",
};
break;
case 19: // h:mm:ss AM/PM
format = CellDataFormatFlag.DateTime;
arg = new DateTimeDataFormatter.DateTimeFormatArgs
{
CultureName = "en-US",
Format = "h:mm:ss tt",
};
break;
case 20: // h:mm
format = CellDataFormatFlag.DateTime;
arg = new DateTimeDataFormatter.DateTimeFormatArgs
{
CultureName = "en-US",
Format = "h:mm",
};
break;
case 21: // h:mm:ss
format = CellDataFormatFlag.DateTime;
arg = new DateTimeDataFormatter.DateTimeFormatArgs
{
CultureName = "en-US",
Format = "H:mm:ss",
};
break;
case 22: // m/d/yy h:mm
format = CellDataFormatFlag.DateTime;
arg = new DateTimeDataFormatter.DateTimeFormatArgs
{
CultureName = "en-US",
Format = "M/d/yy h:mm",
};
break;
case 37: // #,##0 ;(#,##0)
format = CellDataFormatFlag.Number;
arg = new NumberDataFormatter.NumberFormatArgs
{
DecimalPlaces = 0,
UseSeparator = true,
NegativeStyle = NumberDataFormatter.NumberNegativeStyle.Brackets,
};
break;
case 38: // #,##0 ;[Red](#,##0)
format = CellDataFormatFlag.Number;
arg = new NumberDataFormatter.NumberFormatArgs
{
DecimalPlaces = 0,
UseSeparator = true,
NegativeStyle = NumberDataFormatter.NumberNegativeStyle.Red | NumberDataFormatter.NumberNegativeStyle.Brackets,
};
break;
case 39: // #,##0.00;(#,##0.00)
format = CellDataFormatFlag.Number;
arg = new NumberDataFormatter.NumberFormatArgs
{
DecimalPlaces = 2,
UseSeparator = true,
NegativeStyle = NumberDataFormatter.NumberNegativeStyle.Brackets,
};
break;
case 40: // #,##0.00;[Red](#,##0.00)
format = CellDataFormatFlag.Number;
arg = new NumberDataFormatter.NumberFormatArgs
{
DecimalPlaces = 2,
UseSeparator = true,
NegativeStyle = NumberDataFormatter.NumberNegativeStyle.Red | NumberDataFormatter.NumberNegativeStyle.Brackets,
};
break;
case 45: // mm:ss
format = CellDataFormatFlag.DateTime;
arg = new DateTimeDataFormatter.DateTimeFormatArgs
{
CultureName = "en-US",
Format = "mm:ss",
};
break;
case 46: // [h]:mm:ss
format = CellDataFormatFlag.DateTime;
arg = new DateTimeDataFormatter.DateTimeFormatArgs
{
CultureName = "en-US",
Format = "h:mm:ss",
};
break;
case 47: // mmss.0
format = CellDataFormatFlag.DateTime;
arg = new DateTimeDataFormatter.DateTimeFormatArgs
{
CultureName = "en-US",
Format = "mmss.f",
};
break;
case 49: // @
format = CellDataFormatFlag.Text;
break;
case 12: // # ?/?
case 13: // # ??/??
case 48: // ##0.0E+0
//throw new NotSupportedException();
break;
}
if (format == null)
{
dataFormatFlag = CellDataFormatFlag.General;
return false;
}
else
{
cell.DataFormat = format.Value;
cell.DataFormatArgs = arg;
dataFormatFlag = format.Value;
//rgSheet.SetCellDataFormat(cell, format.Value, ref arg);
return true;
}
}
}
#endregion // Builtin Number Formats
#region Excel Document
internal partial class Document
{
private IZipArchive zipArchive;
public Schema.Workbook Workbook { get; private set; }
public bool IsReadonly { get; private set; }
private Document()
{
IsReadonly = false;
}
public static Document ReadFromStream(Stream stream)
{
IZipArchive zip = MZipArchiveFactory.OpenOnStream(stream);
if (zip == null) return null;
var doc = new Document { zipArchive = zip, _path = string.Empty };
doc.LoadRelationShipsFile(doc, string.Empty);
doc.Workbook = doc.LoadEntryFile<Schema.Workbook>("xl/", "workbook.xml");
return doc;
}
#region Load Resources
internal T LoadEntryFile<T>(string path, string name) where T : class
{
T obj = this.LoadObjectFromPath<T>(path, name);
if (obj == null) throw new ExcelFormatException("Failed to load specified entry resource: " + name);
return obj;
}
private void LoadRelationShipsFile(OpenXMLFile entryFile, string name)
{
string finalPath = entryFile._path + "_rels/" + name + ".rels";
if (this.zipArchive.IsFileExist(finalPath))
{
entryFile._relationFile = this.LoadObjectFromPath<Relationships>(finalPath, null);
}
}
internal T LoadRelationResourceById<T>(OpenXMLFile entryFile, string id) where T : class
{
var relation = entryFile._relationFile.relations.FirstOrDefault(_r => _r.id == id);
if (relation == null)
{
throw new ExcelFormatException("Relation resource cannot be found: " + entryFile._path);
}
return this.LoadObjectFromPath<T>(entryFile._path, relation.target);
}
internal T LoadRelationResourceByType<T>(OpenXMLFile entryFile, string typeNamespace) where T : class
{
var relation = this.Workbook._relationFile.relations.FirstOrDefault(r => r.type == typeNamespace);
return relation == null ? null : this.LoadObjectFromPath<T>(entryFile._path, relation.target);
}
internal T LoadObjectFromPath<T>(string path, string name) where T : class
{
var finalPath = RelativePathUtility.GetRelativePath(path, name);
var entry = this.zipArchive.GetFile(finalPath);
if (entry == null)
{
throw new ExcelFormatException("Resource entry cannot be found: " + path);
}
using (var stream = entry.GetStream())
{
if (stream == null)
{
throw new ExcelFormatException("Resource stream cannot be found: " + path);
}
T obj = XMLHelper.LoadXML<T>(stream) as T;
if (obj is OpenXMLFile)
{
var objectPath = RelativePathUtility.GetPathWithoutFilename(finalPath);
var objectName = RelativePathUtility.GetFileNameFromPath(finalPath);
var entryFile = obj as OpenXMLFile;
entryFile._path = objectPath;
this.LoadRelationShipsFile(entryFile, objectName);
}
return obj;
}
}
internal Stream GetResourceStream(string path)
{
var entry = this.zipArchive.GetFile(path);
return entry == null ? null : entry.GetStream();
}
#endregion // Load Resources
#region SharedStrings
public SharedStrings SharedStrings { get; set; }
private const string sharedStrings_xml_filename = "sharedStrings.xml";
public SharedStrings ReadSharedStringTable()
{
if (this.zipArchive.IsFileExist(this.Workbook._path + sharedStrings_xml_filename))
{
return this.LoadEntryFile<SharedStrings>(this.Workbook._path, sharedStrings_xml_filename);
}
else
{
return null;
}
}
#endregion // SharedStrings
public Stylesheet Stylesheet { get; set; }
#region Themesheet
private Theme themesheet;
public Theme Themesheet
{
get
{
if (this.themesheet == null && this.zipArchive != null)
{
this.themesheet = this.LoadRelationResourceByType<Theme>(this.Workbook, OpenXMLRelationTypes.theme____________);
}
return this.themesheet;
}
set
{
this.themesheet = value;
}
}
#region Convert CompColor
internal SolidColor ConvertFromCompColor(CompColor compColor, CompColor overrideColor = null)
{
if (compColor._solidColor.A > 0)
{
return compColor._solidColor;
}
if (compColor.srgbColor != null
&& !string.IsNullOrEmpty(compColor.srgbColor.val))
{
int hex = 0;
int.TryParse(compColor.srgbColor.val, System.Globalization.NumberStyles.AllowHexSpecifier, null, out hex);
compColor._solidColor = SolidColor.FromRGB(hex);
return compColor._solidColor;
}
if (compColor.sysColor != null
&& !string.IsNullOrEmpty(compColor.sysColor.val))
{
switch (compColor.sysColor.val)
{
case "windowText":
compColor._solidColor = StaticResources.SystemColor_WindowText;
return compColor._solidColor;
case "window":
compColor._solidColor = StaticResources.SystemColor_Window;
return compColor._solidColor;
}
}
if (compColor.schemeColor != null)
{
SolidColor color = SolidColor.Black;
var theme = this.Themesheet;
switch (compColor.schemeColor.val)
{
case "dk1": color = ConvertFromCompColor(theme.elements.clrScheme.dk1); break;
case "lt1": color = ConvertFromCompColor(theme.elements.clrScheme.lt1); break;
case "dk2": color = ConvertFromCompColor(theme.elements.clrScheme.dk2); break;
case "lt2": color = ConvertFromCompColor(theme.elements.clrScheme.lt2); break;
case "accent1": color = ConvertFromCompColor(theme.elements.clrScheme.accent1); break;
case "accent2": color = ConvertFromCompColor(theme.elements.clrScheme.accent2); break;
case "accent3": color = ConvertFromCompColor(theme.elements.clrScheme.accent3); break;
case "accent4": color = ConvertFromCompColor(theme.elements.clrScheme.accent4); break;
case "accent5": color = ConvertFromCompColor(theme.elements.clrScheme.accent5); break;
case "accent6": color = ConvertFromCompColor(theme.elements.clrScheme.accent6); break;
case "hlink": color = ConvertFromCompColor(theme.elements.clrScheme.hlink); break;
case "folHlink": color = ConvertFromCompColor(theme.elements.clrScheme.folHlink); break;
case "phClr": color = ConvertFromCompColor(overrideColor); break;
}
if (overrideColor != null)
{
HSLColor hlsColor = ColorUtility.RGBToHSL(color);
var compColorVal = overrideColor.schemeColor;
if (compColorVal.shade != null)
{
hlsColor.L = ColorUtility.CalculateFinalLumValue(-(float)compColorVal.shade.value / 100000f, (float)hlsColor.L * 255f) / 255f;
}
if (compColorVal.tint != null)
{
hlsColor.L = ColorUtility.CalculateFinalLumValue((float)compColorVal.tint.value / 100000f, (float)hlsColor.L * 255f) / 255f;
}
if (compColorVal.lumMod != null)
{
hlsColor.L *= (float)compColorVal.lumMod.value / 100000f;
}
if (compColorVal.lumOff != null)
{
hlsColor.L += (float)compColorVal.lumOff.value / 100000f;
}
if (compColorVal.satMod != null)
{
hlsColor.S *= (float)compColorVal.satMod.value / 100000f;
}
color = ColorUtility.HSLToRgb(hlsColor);
}
else
{
compColor._solidColor = color;
}
return color;
}
return SolidColor.Transparent;
}
#endregion // Convert CompColor
#endregion // Themesheet
}
#endregion // Excel Document
#region Exceptions
class ExcelFormatException : ReoGridException
{
public ExcelFormatException(string msg) : base(msg) { }
public ExcelFormatException(string msg, Exception inner) : base(msg, inner) { }
}
#endregion // Exceptions
}
| 25.582319 | 147 | 0.622364 | [
"MIT"
] | SlightPlus/ReoGrid | ReoGrid/IO/ExcelReader.cs | 79,872 | C# |
namespace Starfield.Core.Networking.Packet.Server.Play {
[Packet(0x29, ProtocolState.Play, PacketSide.Server)]
public class SP29EntityRotation : MinecraftPacket {
public int EntityId { get; }
public float Yaw { get; }
public float Pitch { get; }
public bool OnGround { get; }
public SP29EntityRotation(MinecraftClient client, int entityId, float yaw, float pitch, bool onGround) : base(client) {
EntityId = Data.WriteVarInt(entityId);
Yaw = Data.WriteAngle(yaw);
Pitch = Data.WriteAngle(pitch);
OnGround = Data.WriteBoolean(onGround);
}
}
} | 37.166667 | 128 | 0.620329 | [
"MIT"
] | StarfieldMC/Starfield | Starfield.Core/Networking/Packet/Server/Play/SP29EntityRotation.cs | 671 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Custom Spreadsheet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("customProject")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 42.482143 | 98 | 0.709962 | [
"MIT"
] | uzairrj/Custom-SpreadSheet | Custom Spreadsheet/Properties/AssemblyInfo.cs | 2,382 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.TrafficManager.Models;
using Microsoft.Azure.Commands.TrafficManager.Utilities;
using System.Management.Automation;
using ProjectResources = Microsoft.Azure.Commands.TrafficManager.Properties.Resources;
namespace Microsoft.Azure.Commands.TrafficManager
{
[Cmdlet(VerbsCommon.Remove, "AzureRmTrafficManagerEndpoint", SupportsShouldProcess = true),
OutputType(typeof(bool))]
public class RemoveAzureTrafficManagerEndpoint : TrafficManagerBaseCmdlet
{
[Parameter(Mandatory = true, HelpMessage = "The name of the endpoint.", ParameterSetName = "Fields")]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
[Parameter(Mandatory = true, HelpMessage = "The type of the endpoint.", ParameterSetName = "Fields")]
[ValidateSet(Constants.AzureEndpoint, Constants.ExternalEndpoint, Constants.NestedEndpoint, IgnoreCase = true)]
[ValidateNotNullOrEmpty]
public string Type { get; set; }
[Parameter(Mandatory = true, HelpMessage = "The name of the profile.", ParameterSetName = "Fields")]
[ValidateNotNullOrEmpty]
public string ProfileName { get; set; }
[Parameter(Mandatory = true, HelpMessage = "The resource group to which the profile belongs.", ParameterSetName = "Fields")]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }
[Parameter(Mandatory = true, ValueFromPipeline = true, HelpMessage = "The endpoint.", ParameterSetName = "Object")]
[ValidateNotNullOrEmpty]
public TrafficManagerEndpoint TrafficManagerEndpoint { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Do not ask for confirmation.")]
public SwitchParameter Force { get; set; }
public override void ExecuteCmdlet()
{
var deleted = false;
TrafficManagerEndpoint trafficManagerEndpointToDelete = null;
if (this.ParameterSetName == "Fields")
{
trafficManagerEndpointToDelete = new TrafficManagerEndpoint
{
Name = this.Name,
ProfileName = this.ProfileName,
ResourceGroupName = this.ResourceGroupName,
Type = this.Type
};
}
else if (this.ParameterSetName == "Object")
{
trafficManagerEndpointToDelete = this.TrafficManagerEndpoint;
}
this.ConfirmAction(
this.Force.IsPresent,
string.Format(ProjectResources.Confirm_RemoveEndpoint, trafficManagerEndpointToDelete.Name, trafficManagerEndpointToDelete.ProfileName, trafficManagerEndpointToDelete.ResourceGroupName),
ProjectResources.Progress_RemovingEndpoint,
this.Name,
() =>
{
deleted = this.TrafficManagerClient.DeleteTrafficManagerEndpoint(trafficManagerEndpointToDelete);
if (deleted)
{
this.WriteVerbose(ProjectResources.Success);
this.WriteVerbose(string.Format(ProjectResources.Success_RemoveEndpoint, trafficManagerEndpointToDelete.Name, trafficManagerEndpointToDelete.ProfileName, trafficManagerEndpointToDelete.ResourceGroupName));
}
this.WriteObject(deleted);
});
}
}
}
| 48.393258 | 230 | 0.623868 | [
"MIT"
] | SpillChek2/azure-powershell | src/ResourceManager/TrafficManager/Commands.TrafficManager2/Endpoint/RemoveAzureTrafficManagerEndpoint.cs | 4,221 | C# |
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using FontAwesome.WPF;
namespace EdgeManager.Gui.Converters
{
public sealed class BoolToEdgeDeviceIconConverter : IValueConverter
{
public BoolToEdgeDeviceIconConverter()
{
this.TrueValue = FontAwesomeIcon.Cloud;
this.FalseValue = FontAwesomeIcon.Microchip;
}
public FontAwesomeIcon FalseValue { get; set; }
public FontAwesomeIcon TrueValue { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return !(value is bool flag) ? DependencyProperty.UnsetValue : flag ? TrueValue : FalseValue;
}
public object ConvertBack(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
} | 28 | 105 | 0.643878 | [
"MIT"
] | evopro-ag/EdgeManager | EdgeManager.Gui/Converters/BoolToEdgeDeviceIconConverter.cs | 982 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace CodeContractsRemover.CS
{
public class CSharpStatsCollector : SyntaxWalker
{
public static Dictionary<string, int> Stats = new Dictionary<string, int>();
public static string GetStats()
{
var sb = new StringBuilder();
foreach (var stat in CSharpStatsCollector.Stats.OrderBy(s => s.Key))
{
sb.AppendLine($"{stat.Key,-50}\t{stat.Value,3}");
}
return sb.ToString();
}
/// <summary>
/// Called when the walker visits a node. This method may be overridden if subclasses want
/// to handle the node. Overrides should call back into this base method if they want the
/// children of this node to be visited.
/// </summary>
/// <param name="node">The current node that the walker is visiting.</param>
public override void Visit(SyntaxNode node)
{
switch (node)
{
case InvocationExpressionSyntax invNode:
var invInfo = new InvocationInfo(invNode);
if (invInfo.Class == "Contract")
{
IncrementStats($"{invInfo.Class}.{invInfo.Method}");
}
break;
case AttributeSyntax attrNode:
var attrName = attrNode.Name.ToString().Replace("Attribute", string.Empty);
if (ContractRemover.ContractAttributes.Contains(attrName)
|| attrName.StartsWith(ContractRemover.ContractClassForAttributeName))
{
IncrementStats($"[{attrName}]");
}
break;
}
base.Visit(node);
}
private static void IncrementStats(string key)
{
if (Stats.ContainsKey(key))
{
Stats[key]++;
}
else
{
Stats[key] = 1;
}
}
}
}
| 25.3 | 94 | 0.646527 | [
"MIT"
] | deniszykov/code-contracts-remover | src/CodeContractsRemover/CS/CSharpStatsCollector.cs | 1,771 | C# |
using System.Collections.Generic;
using System.Runtime.Serialization;
using Stranne.VasttrafikNET.ApiModels.JourneyPlanner;
namespace Stranne.VasttrafikNET.ApiModels.TrafficSituations
{
/// <summary>
/// Line.
/// </summary>
public class LineApiModel
{
/// <summary>
/// List of <see cref="DirectionApiModel"/>.
/// </summary>
public List<DirectionApiModel> Directions { get; set; }
/// <summary>
/// Name of the transport authority responsible for operating the line. Example data: "Västtrafik".
/// </summary>
public string TransportAuthorityName { get; set; }
/// <summary>
/// Line text color. Example data: "FFFFFF".
/// </summary>
public string TextColor { get; set; }
/// <summary>
/// A code incicating the transport authority responsible for operating the line. Example data: "vt".
/// </summary>
public string TransportAuthorityCode { get; set; }
/// <summary>
/// Transport mode of the line. Example data: "bus", "tram", "train", "taxi", "ferry".
/// </summary>
public string DefaultTransportModeCode { get; set; }
/// <summary>
/// Internally used number of the line. Example data: 6205.
/// </summary>
public int TechnicalNumber { get; set; }
/// <summary>
/// Line background color. Example data: "F03A43".
/// </summary>
public string BackgroundColor { get; set; }
/// <summary>
/// Name of the line. Example data: "Grön express".
/// </summary>
public string Name { get; set; }
/// <summary>
/// Designation of the line. Example data: "GRÖN", "4".
/// </summary>
public string Designation { get; set; }
/// <summary>
/// Global unique identifier for the line. Example data: 9011014620500000.
/// </summary>
public string Gid { get; set; }
/// <summary>
/// List of municipalities.
/// </summary>
public IEnumerable<MunicipalityApiModel> Municipalities { get; set; }
/// <summary>
/// List of affected stop points global identifiers.
/// </summary>
public IEnumerable<string> AffectedStopPointGids { get; set; }
}
} | 32.652778 | 109 | 0.573373 | [
"MIT"
] | stranne/Vasttrafik.NET | src/Stranne.VasttrafikNET/ApiModels/TrafficSituations/LineApiModel.cs | 2,356 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
using NMFExamples.Pcm.Core;
using NMFExamples.Pcm.Core.Entity;
using NMFExamples.Pcm.Parameter;
using NMFExamples.Pcm.Repository;
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using global::System.Collections;
using global::System.Collections.Generic;
using global::System.Collections.ObjectModel;
using global::System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace NMFExamples.Pcm.Core.Composition
{
/// <summary>
/// The default implementation of the RequiredInfrastructureDelegationConnector class
/// </summary>
[XmlNamespaceAttribute("http://sdq.ipd.uka.de/PalladioComponentModel/Core/Composition/5.0")]
[XmlNamespacePrefixAttribute("composition")]
[ModelRepresentationClassAttribute("http://sdq.ipd.uka.de/PalladioComponentModel/5.0#//core/composition/RequiredInfra" +
"structureDelegationConnector")]
[DebuggerDisplayAttribute("RequiredInfrastructureDelegationConnector {Id}")]
public partial class RequiredInfrastructureDelegationConnector : DelegationConnector, IRequiredInfrastructureDelegationConnector, IModelElement
{
private static Lazy<ITypedElement> _innerRequiredRole__RequiredInfrastructureDelegationConnectorReference = new Lazy<ITypedElement>(RetrieveInnerRequiredRole__RequiredInfrastructureDelegationConnectorReference);
/// <summary>
/// The backing field for the InnerRequiredRole__RequiredInfrastructureDelegationConnector property
/// </summary>
private IInfrastructureRequiredRole _innerRequiredRole__RequiredInfrastructureDelegationConnector;
private static Lazy<ITypedElement> _outerRequiredRole__RequiredInfrastructureDelegationConnectorReference = new Lazy<ITypedElement>(RetrieveOuterRequiredRole__RequiredInfrastructureDelegationConnectorReference);
/// <summary>
/// The backing field for the OuterRequiredRole__RequiredInfrastructureDelegationConnector property
/// </summary>
private IInfrastructureRequiredRole _outerRequiredRole__RequiredInfrastructureDelegationConnector;
private static Lazy<ITypedElement> _assemblyContext__RequiredInfrastructureDelegationConnectorReference = new Lazy<ITypedElement>(RetrieveAssemblyContext__RequiredInfrastructureDelegationConnectorReference);
/// <summary>
/// The backing field for the AssemblyContext__RequiredInfrastructureDelegationConnector property
/// </summary>
private IAssemblyContext _assemblyContext__RequiredInfrastructureDelegationConnector;
private static IClass _classInstance;
/// <summary>
/// The innerRequiredRole__RequiredInfrastructureDelegationConnector property
/// </summary>
[XmlElementNameAttribute("innerRequiredRole__RequiredInfrastructureDelegationConnector")]
[XmlAttributeAttribute(true)]
public IInfrastructureRequiredRole InnerRequiredRole__RequiredInfrastructureDelegationConnector
{
get
{
return this._innerRequiredRole__RequiredInfrastructureDelegationConnector;
}
set
{
if ((this._innerRequiredRole__RequiredInfrastructureDelegationConnector != value))
{
IInfrastructureRequiredRole old = this._innerRequiredRole__RequiredInfrastructureDelegationConnector;
ValueChangedEventArgs e = new ValueChangedEventArgs(old, value);
this.OnInnerRequiredRole__RequiredInfrastructureDelegationConnectorChanging(e);
this.OnPropertyChanging("InnerRequiredRole__RequiredInfrastructureDelegationConnector", e, _innerRequiredRole__RequiredInfrastructureDelegationConnectorReference);
this._innerRequiredRole__RequiredInfrastructureDelegationConnector = value;
if ((old != null))
{
old.Deleted -= this.OnResetInnerRequiredRole__RequiredInfrastructureDelegationConnector;
}
if ((value != null))
{
value.Deleted += this.OnResetInnerRequiredRole__RequiredInfrastructureDelegationConnector;
}
this.OnInnerRequiredRole__RequiredInfrastructureDelegationConnectorChanged(e);
this.OnPropertyChanged("InnerRequiredRole__RequiredInfrastructureDelegationConnector", e, _innerRequiredRole__RequiredInfrastructureDelegationConnectorReference);
}
}
}
/// <summary>
/// The outerRequiredRole__RequiredInfrastructureDelegationConnector property
/// </summary>
[XmlElementNameAttribute("outerRequiredRole__RequiredInfrastructureDelegationConnector")]
[XmlAttributeAttribute(true)]
public IInfrastructureRequiredRole OuterRequiredRole__RequiredInfrastructureDelegationConnector
{
get
{
return this._outerRequiredRole__RequiredInfrastructureDelegationConnector;
}
set
{
if ((this._outerRequiredRole__RequiredInfrastructureDelegationConnector != value))
{
IInfrastructureRequiredRole old = this._outerRequiredRole__RequiredInfrastructureDelegationConnector;
ValueChangedEventArgs e = new ValueChangedEventArgs(old, value);
this.OnOuterRequiredRole__RequiredInfrastructureDelegationConnectorChanging(e);
this.OnPropertyChanging("OuterRequiredRole__RequiredInfrastructureDelegationConnector", e, _outerRequiredRole__RequiredInfrastructureDelegationConnectorReference);
this._outerRequiredRole__RequiredInfrastructureDelegationConnector = value;
if ((old != null))
{
old.Deleted -= this.OnResetOuterRequiredRole__RequiredInfrastructureDelegationConnector;
}
if ((value != null))
{
value.Deleted += this.OnResetOuterRequiredRole__RequiredInfrastructureDelegationConnector;
}
this.OnOuterRequiredRole__RequiredInfrastructureDelegationConnectorChanged(e);
this.OnPropertyChanged("OuterRequiredRole__RequiredInfrastructureDelegationConnector", e, _outerRequiredRole__RequiredInfrastructureDelegationConnectorReference);
}
}
}
/// <summary>
/// The assemblyContext__RequiredInfrastructureDelegationConnector property
/// </summary>
[XmlElementNameAttribute("assemblyContext__RequiredInfrastructureDelegationConnector")]
[XmlAttributeAttribute(true)]
public IAssemblyContext AssemblyContext__RequiredInfrastructureDelegationConnector
{
get
{
return this._assemblyContext__RequiredInfrastructureDelegationConnector;
}
set
{
if ((this._assemblyContext__RequiredInfrastructureDelegationConnector != value))
{
IAssemblyContext old = this._assemblyContext__RequiredInfrastructureDelegationConnector;
ValueChangedEventArgs e = new ValueChangedEventArgs(old, value);
this.OnAssemblyContext__RequiredInfrastructureDelegationConnectorChanging(e);
this.OnPropertyChanging("AssemblyContext__RequiredInfrastructureDelegationConnector", e, _assemblyContext__RequiredInfrastructureDelegationConnectorReference);
this._assemblyContext__RequiredInfrastructureDelegationConnector = value;
if ((old != null))
{
old.Deleted -= this.OnResetAssemblyContext__RequiredInfrastructureDelegationConnector;
}
if ((value != null))
{
value.Deleted += this.OnResetAssemblyContext__RequiredInfrastructureDelegationConnector;
}
this.OnAssemblyContext__RequiredInfrastructureDelegationConnectorChanged(e);
this.OnPropertyChanged("AssemblyContext__RequiredInfrastructureDelegationConnector", e, _assemblyContext__RequiredInfrastructureDelegationConnectorReference);
}
}
}
/// <summary>
/// Gets the referenced model elements of this model element
/// </summary>
public override IEnumerableExpression<IModelElement> ReferencedElements
{
get
{
return base.ReferencedElements.Concat(new RequiredInfrastructureDelegationConnectorReferencedElementsCollection(this));
}
}
/// <summary>
/// Gets the Class model for this type
/// </summary>
public new static IClass ClassInstance
{
get
{
if ((_classInstance == null))
{
_classInstance = ((IClass)(MetaRepository.Instance.Resolve("http://sdq.ipd.uka.de/PalladioComponentModel/5.0#//core/composition/RequiredInfra" +
"structureDelegationConnector")));
}
return _classInstance;
}
}
/// <summary>
/// Gets fired before the InnerRequiredRole__RequiredInfrastructureDelegationConnector property changes its value
/// </summary>
public event global::System.EventHandler<ValueChangedEventArgs> InnerRequiredRole__RequiredInfrastructureDelegationConnectorChanging;
/// <summary>
/// Gets fired when the InnerRequiredRole__RequiredInfrastructureDelegationConnector property changed its value
/// </summary>
public event global::System.EventHandler<ValueChangedEventArgs> InnerRequiredRole__RequiredInfrastructureDelegationConnectorChanged;
/// <summary>
/// Gets fired before the OuterRequiredRole__RequiredInfrastructureDelegationConnector property changes its value
/// </summary>
public event global::System.EventHandler<ValueChangedEventArgs> OuterRequiredRole__RequiredInfrastructureDelegationConnectorChanging;
/// <summary>
/// Gets fired when the OuterRequiredRole__RequiredInfrastructureDelegationConnector property changed its value
/// </summary>
public event global::System.EventHandler<ValueChangedEventArgs> OuterRequiredRole__RequiredInfrastructureDelegationConnectorChanged;
/// <summary>
/// Gets fired before the AssemblyContext__RequiredInfrastructureDelegationConnector property changes its value
/// </summary>
public event global::System.EventHandler<ValueChangedEventArgs> AssemblyContext__RequiredInfrastructureDelegationConnectorChanging;
/// <summary>
/// Gets fired when the AssemblyContext__RequiredInfrastructureDelegationConnector property changed its value
/// </summary>
public event global::System.EventHandler<ValueChangedEventArgs> AssemblyContext__RequiredInfrastructureDelegationConnectorChanged;
private static ITypedElement RetrieveInnerRequiredRole__RequiredInfrastructureDelegationConnectorReference()
{
return ((ITypedElement)(((ModelElement)(NMFExamples.Pcm.Core.Composition.RequiredInfrastructureDelegationConnector.ClassInstance)).Resolve("innerRequiredRole__RequiredInfrastructureDelegationConnector")));
}
/// <summary>
/// Raises the InnerRequiredRole__RequiredInfrastructureDelegationConnectorChanging event
/// </summary>
/// <param name="eventArgs">The event data</param>
protected virtual void OnInnerRequiredRole__RequiredInfrastructureDelegationConnectorChanging(ValueChangedEventArgs eventArgs)
{
global::System.EventHandler<ValueChangedEventArgs> handler = this.InnerRequiredRole__RequiredInfrastructureDelegationConnectorChanging;
if ((handler != null))
{
handler.Invoke(this, eventArgs);
}
}
/// <summary>
/// Raises the InnerRequiredRole__RequiredInfrastructureDelegationConnectorChanged event
/// </summary>
/// <param name="eventArgs">The event data</param>
protected virtual void OnInnerRequiredRole__RequiredInfrastructureDelegationConnectorChanged(ValueChangedEventArgs eventArgs)
{
global::System.EventHandler<ValueChangedEventArgs> handler = this.InnerRequiredRole__RequiredInfrastructureDelegationConnectorChanged;
if ((handler != null))
{
handler.Invoke(this, eventArgs);
}
}
/// <summary>
/// Handles the event that the InnerRequiredRole__RequiredInfrastructureDelegationConnector property must reset
/// </summary>
/// <param name="sender">The object that sent this reset request</param>
/// <param name="eventArgs">The event data for the reset event</param>
private void OnResetInnerRequiredRole__RequiredInfrastructureDelegationConnector(object sender, global::System.EventArgs eventArgs)
{
this.InnerRequiredRole__RequiredInfrastructureDelegationConnector = null;
}
private static ITypedElement RetrieveOuterRequiredRole__RequiredInfrastructureDelegationConnectorReference()
{
return ((ITypedElement)(((ModelElement)(NMFExamples.Pcm.Core.Composition.RequiredInfrastructureDelegationConnector.ClassInstance)).Resolve("outerRequiredRole__RequiredInfrastructureDelegationConnector")));
}
/// <summary>
/// Raises the OuterRequiredRole__RequiredInfrastructureDelegationConnectorChanging event
/// </summary>
/// <param name="eventArgs">The event data</param>
protected virtual void OnOuterRequiredRole__RequiredInfrastructureDelegationConnectorChanging(ValueChangedEventArgs eventArgs)
{
global::System.EventHandler<ValueChangedEventArgs> handler = this.OuterRequiredRole__RequiredInfrastructureDelegationConnectorChanging;
if ((handler != null))
{
handler.Invoke(this, eventArgs);
}
}
/// <summary>
/// Raises the OuterRequiredRole__RequiredInfrastructureDelegationConnectorChanged event
/// </summary>
/// <param name="eventArgs">The event data</param>
protected virtual void OnOuterRequiredRole__RequiredInfrastructureDelegationConnectorChanged(ValueChangedEventArgs eventArgs)
{
global::System.EventHandler<ValueChangedEventArgs> handler = this.OuterRequiredRole__RequiredInfrastructureDelegationConnectorChanged;
if ((handler != null))
{
handler.Invoke(this, eventArgs);
}
}
/// <summary>
/// Handles the event that the OuterRequiredRole__RequiredInfrastructureDelegationConnector property must reset
/// </summary>
/// <param name="sender">The object that sent this reset request</param>
/// <param name="eventArgs">The event data for the reset event</param>
private void OnResetOuterRequiredRole__RequiredInfrastructureDelegationConnector(object sender, global::System.EventArgs eventArgs)
{
this.OuterRequiredRole__RequiredInfrastructureDelegationConnector = null;
}
private static ITypedElement RetrieveAssemblyContext__RequiredInfrastructureDelegationConnectorReference()
{
return ((ITypedElement)(((ModelElement)(NMFExamples.Pcm.Core.Composition.RequiredInfrastructureDelegationConnector.ClassInstance)).Resolve("assemblyContext__RequiredInfrastructureDelegationConnector")));
}
/// <summary>
/// Raises the AssemblyContext__RequiredInfrastructureDelegationConnectorChanging event
/// </summary>
/// <param name="eventArgs">The event data</param>
protected virtual void OnAssemblyContext__RequiredInfrastructureDelegationConnectorChanging(ValueChangedEventArgs eventArgs)
{
global::System.EventHandler<ValueChangedEventArgs> handler = this.AssemblyContext__RequiredInfrastructureDelegationConnectorChanging;
if ((handler != null))
{
handler.Invoke(this, eventArgs);
}
}
/// <summary>
/// Raises the AssemblyContext__RequiredInfrastructureDelegationConnectorChanged event
/// </summary>
/// <param name="eventArgs">The event data</param>
protected virtual void OnAssemblyContext__RequiredInfrastructureDelegationConnectorChanged(ValueChangedEventArgs eventArgs)
{
global::System.EventHandler<ValueChangedEventArgs> handler = this.AssemblyContext__RequiredInfrastructureDelegationConnectorChanged;
if ((handler != null))
{
handler.Invoke(this, eventArgs);
}
}
/// <summary>
/// Handles the event that the AssemblyContext__RequiredInfrastructureDelegationConnector property must reset
/// </summary>
/// <param name="sender">The object that sent this reset request</param>
/// <param name="eventArgs">The event data for the reset event</param>
private void OnResetAssemblyContext__RequiredInfrastructureDelegationConnector(object sender, global::System.EventArgs eventArgs)
{
this.AssemblyContext__RequiredInfrastructureDelegationConnector = null;
}
/// <summary>
/// Sets a value to the given feature
/// </summary>
/// <param name="feature">The requested feature</param>
/// <param name="value">The value that should be set to that feature</param>
protected override void SetFeature(string feature, object value)
{
if ((feature == "INNERREQUIREDROLE__REQUIREDINFRASTRUCTUREDELEGATIONCONNECTOR"))
{
this.InnerRequiredRole__RequiredInfrastructureDelegationConnector = ((IInfrastructureRequiredRole)(value));
return;
}
if ((feature == "OUTERREQUIREDROLE__REQUIREDINFRASTRUCTUREDELEGATIONCONNECTOR"))
{
this.OuterRequiredRole__RequiredInfrastructureDelegationConnector = ((IInfrastructureRequiredRole)(value));
return;
}
if ((feature == "ASSEMBLYCONTEXT__REQUIREDINFRASTRUCTUREDELEGATIONCONNECTOR"))
{
this.AssemblyContext__RequiredInfrastructureDelegationConnector = ((IAssemblyContext)(value));
return;
}
base.SetFeature(feature, value);
}
/// <summary>
/// Gets the property expression for the given attribute
/// </summary>
/// <returns>An incremental property expression</returns>
/// <param name="attribute">The requested attribute in upper case</param>
protected override NMF.Expressions.INotifyExpression<object> GetExpressionForAttribute(string attribute)
{
if ((attribute == "InnerRequiredRole__RequiredInfrastructureDelegationConnector"))
{
return new InnerRequiredRole__RequiredInfrastructureDelegationConnectorProxy(this);
}
if ((attribute == "OuterRequiredRole__RequiredInfrastructureDelegationConnector"))
{
return new OuterRequiredRole__RequiredInfrastructureDelegationConnectorProxy(this);
}
if ((attribute == "AssemblyContext__RequiredInfrastructureDelegationConnector"))
{
return new AssemblyContext__RequiredInfrastructureDelegationConnectorProxy(this);
}
return base.GetExpressionForAttribute(attribute);
}
/// <summary>
/// Gets the property expression for the given reference
/// </summary>
/// <returns>An incremental property expression</returns>
/// <param name="reference">The requested reference in upper case</param>
protected override NMF.Expressions.INotifyExpression<NMF.Models.IModelElement> GetExpressionForReference(string reference)
{
if ((reference == "InnerRequiredRole__RequiredInfrastructureDelegationConnector"))
{
return new InnerRequiredRole__RequiredInfrastructureDelegationConnectorProxy(this);
}
if ((reference == "OuterRequiredRole__RequiredInfrastructureDelegationConnector"))
{
return new OuterRequiredRole__RequiredInfrastructureDelegationConnectorProxy(this);
}
if ((reference == "AssemblyContext__RequiredInfrastructureDelegationConnector"))
{
return new AssemblyContext__RequiredInfrastructureDelegationConnectorProxy(this);
}
return base.GetExpressionForReference(reference);
}
/// <summary>
/// Gets the Class for this model element
/// </summary>
public override IClass GetClass()
{
if ((_classInstance == null))
{
_classInstance = ((IClass)(MetaRepository.Instance.Resolve("http://sdq.ipd.uka.de/PalladioComponentModel/5.0#//core/composition/RequiredInfra" +
"structureDelegationConnector")));
}
return _classInstance;
}
/// <summary>
/// The collection class to to represent the children of the RequiredInfrastructureDelegationConnector class
/// </summary>
public class RequiredInfrastructureDelegationConnectorReferencedElementsCollection : ReferenceCollection, ICollectionExpression<IModelElement>, ICollection<IModelElement>
{
private RequiredInfrastructureDelegationConnector _parent;
/// <summary>
/// Creates a new instance
/// </summary>
public RequiredInfrastructureDelegationConnectorReferencedElementsCollection(RequiredInfrastructureDelegationConnector parent)
{
this._parent = parent;
}
/// <summary>
/// Gets the amount of elements contained in this collection
/// </summary>
public override int Count
{
get
{
int count = 0;
if ((this._parent.InnerRequiredRole__RequiredInfrastructureDelegationConnector != null))
{
count = (count + 1);
}
if ((this._parent.OuterRequiredRole__RequiredInfrastructureDelegationConnector != null))
{
count = (count + 1);
}
if ((this._parent.AssemblyContext__RequiredInfrastructureDelegationConnector != null))
{
count = (count + 1);
}
return count;
}
}
protected override void AttachCore()
{
this._parent.InnerRequiredRole__RequiredInfrastructureDelegationConnectorChanged += this.PropagateValueChanges;
this._parent.OuterRequiredRole__RequiredInfrastructureDelegationConnectorChanged += this.PropagateValueChanges;
this._parent.AssemblyContext__RequiredInfrastructureDelegationConnectorChanged += this.PropagateValueChanges;
}
protected override void DetachCore()
{
this._parent.InnerRequiredRole__RequiredInfrastructureDelegationConnectorChanged -= this.PropagateValueChanges;
this._parent.OuterRequiredRole__RequiredInfrastructureDelegationConnectorChanged -= this.PropagateValueChanges;
this._parent.AssemblyContext__RequiredInfrastructureDelegationConnectorChanged -= this.PropagateValueChanges;
}
/// <summary>
/// Adds the given element to the collection
/// </summary>
/// <param name="item">The item to add</param>
public override void Add(IModelElement item)
{
if ((this._parent.InnerRequiredRole__RequiredInfrastructureDelegationConnector == null))
{
IInfrastructureRequiredRole innerRequiredRole__RequiredInfrastructureDelegationConnectorCasted = item.As<IInfrastructureRequiredRole>();
if ((innerRequiredRole__RequiredInfrastructureDelegationConnectorCasted != null))
{
this._parent.InnerRequiredRole__RequiredInfrastructureDelegationConnector = innerRequiredRole__RequiredInfrastructureDelegationConnectorCasted;
return;
}
}
if ((this._parent.OuterRequiredRole__RequiredInfrastructureDelegationConnector == null))
{
IInfrastructureRequiredRole outerRequiredRole__RequiredInfrastructureDelegationConnectorCasted = item.As<IInfrastructureRequiredRole>();
if ((outerRequiredRole__RequiredInfrastructureDelegationConnectorCasted != null))
{
this._parent.OuterRequiredRole__RequiredInfrastructureDelegationConnector = outerRequiredRole__RequiredInfrastructureDelegationConnectorCasted;
return;
}
}
if ((this._parent.AssemblyContext__RequiredInfrastructureDelegationConnector == null))
{
IAssemblyContext assemblyContext__RequiredInfrastructureDelegationConnectorCasted = item.As<IAssemblyContext>();
if ((assemblyContext__RequiredInfrastructureDelegationConnectorCasted != null))
{
this._parent.AssemblyContext__RequiredInfrastructureDelegationConnector = assemblyContext__RequiredInfrastructureDelegationConnectorCasted;
return;
}
}
}
/// <summary>
/// Clears the collection and resets all references that implement it.
/// </summary>
public override void Clear()
{
this._parent.InnerRequiredRole__RequiredInfrastructureDelegationConnector = null;
this._parent.OuterRequiredRole__RequiredInfrastructureDelegationConnector = null;
this._parent.AssemblyContext__RequiredInfrastructureDelegationConnector = null;
}
/// <summary>
/// Gets a value indicating whether the given element is contained in the collection
/// </summary>
/// <returns>True, if it is contained, otherwise False</returns>
/// <param name="item">The item that should be looked out for</param>
public override bool Contains(IModelElement item)
{
if ((item == this._parent.InnerRequiredRole__RequiredInfrastructureDelegationConnector))
{
return true;
}
if ((item == this._parent.OuterRequiredRole__RequiredInfrastructureDelegationConnector))
{
return true;
}
if ((item == this._parent.AssemblyContext__RequiredInfrastructureDelegationConnector))
{
return true;
}
return false;
}
/// <summary>
/// Copies the contents of the collection to the given array starting from the given array index
/// </summary>
/// <param name="array">The array in which the elements should be copied</param>
/// <param name="arrayIndex">The starting index</param>
public override void CopyTo(IModelElement[] array, int arrayIndex)
{
if ((this._parent.InnerRequiredRole__RequiredInfrastructureDelegationConnector != null))
{
array[arrayIndex] = this._parent.InnerRequiredRole__RequiredInfrastructureDelegationConnector;
arrayIndex = (arrayIndex + 1);
}
if ((this._parent.OuterRequiredRole__RequiredInfrastructureDelegationConnector != null))
{
array[arrayIndex] = this._parent.OuterRequiredRole__RequiredInfrastructureDelegationConnector;
arrayIndex = (arrayIndex + 1);
}
if ((this._parent.AssemblyContext__RequiredInfrastructureDelegationConnector != null))
{
array[arrayIndex] = this._parent.AssemblyContext__RequiredInfrastructureDelegationConnector;
arrayIndex = (arrayIndex + 1);
}
}
/// <summary>
/// Removes the given item from the collection
/// </summary>
/// <returns>True, if the item was removed, otherwise False</returns>
/// <param name="item">The item that should be removed</param>
public override bool Remove(IModelElement item)
{
if ((this._parent.InnerRequiredRole__RequiredInfrastructureDelegationConnector == item))
{
this._parent.InnerRequiredRole__RequiredInfrastructureDelegationConnector = null;
return true;
}
if ((this._parent.OuterRequiredRole__RequiredInfrastructureDelegationConnector == item))
{
this._parent.OuterRequiredRole__RequiredInfrastructureDelegationConnector = null;
return true;
}
if ((this._parent.AssemblyContext__RequiredInfrastructureDelegationConnector == item))
{
this._parent.AssemblyContext__RequiredInfrastructureDelegationConnector = null;
return true;
}
return false;
}
/// <summary>
/// Gets an enumerator that enumerates the collection
/// </summary>
/// <returns>A generic enumerator</returns>
public override IEnumerator<IModelElement> GetEnumerator()
{
return Enumerable.Empty<IModelElement>().Concat(this._parent.InnerRequiredRole__RequiredInfrastructureDelegationConnector).Concat(this._parent.OuterRequiredRole__RequiredInfrastructureDelegationConnector).Concat(this._parent.AssemblyContext__RequiredInfrastructureDelegationConnector).GetEnumerator();
}
}
/// <summary>
/// Represents a proxy to represent an incremental access to the innerRequiredRole__RequiredInfrastructureDelegationConnector property
/// </summary>
private sealed class InnerRequiredRole__RequiredInfrastructureDelegationConnectorProxy : ModelPropertyChange<IRequiredInfrastructureDelegationConnector, IInfrastructureRequiredRole>
{
/// <summary>
/// Creates a new observable property access proxy
/// </summary>
/// <param name="modelElement">The model instance element for which to create the property access proxy</param>
public InnerRequiredRole__RequiredInfrastructureDelegationConnectorProxy(IRequiredInfrastructureDelegationConnector modelElement) :
base(modelElement, "innerRequiredRole__RequiredInfrastructureDelegationConnector")
{
}
/// <summary>
/// Gets or sets the value of this expression
/// </summary>
public override IInfrastructureRequiredRole Value
{
get
{
return this.ModelElement.InnerRequiredRole__RequiredInfrastructureDelegationConnector;
}
set
{
this.ModelElement.InnerRequiredRole__RequiredInfrastructureDelegationConnector = value;
}
}
}
/// <summary>
/// Represents a proxy to represent an incremental access to the outerRequiredRole__RequiredInfrastructureDelegationConnector property
/// </summary>
private sealed class OuterRequiredRole__RequiredInfrastructureDelegationConnectorProxy : ModelPropertyChange<IRequiredInfrastructureDelegationConnector, IInfrastructureRequiredRole>
{
/// <summary>
/// Creates a new observable property access proxy
/// </summary>
/// <param name="modelElement">The model instance element for which to create the property access proxy</param>
public OuterRequiredRole__RequiredInfrastructureDelegationConnectorProxy(IRequiredInfrastructureDelegationConnector modelElement) :
base(modelElement, "outerRequiredRole__RequiredInfrastructureDelegationConnector")
{
}
/// <summary>
/// Gets or sets the value of this expression
/// </summary>
public override IInfrastructureRequiredRole Value
{
get
{
return this.ModelElement.OuterRequiredRole__RequiredInfrastructureDelegationConnector;
}
set
{
this.ModelElement.OuterRequiredRole__RequiredInfrastructureDelegationConnector = value;
}
}
}
/// <summary>
/// Represents a proxy to represent an incremental access to the assemblyContext__RequiredInfrastructureDelegationConnector property
/// </summary>
private sealed class AssemblyContext__RequiredInfrastructureDelegationConnectorProxy : ModelPropertyChange<IRequiredInfrastructureDelegationConnector, IAssemblyContext>
{
/// <summary>
/// Creates a new observable property access proxy
/// </summary>
/// <param name="modelElement">The model instance element for which to create the property access proxy</param>
public AssemblyContext__RequiredInfrastructureDelegationConnectorProxy(IRequiredInfrastructureDelegationConnector modelElement) :
base(modelElement, "assemblyContext__RequiredInfrastructureDelegationConnector")
{
}
/// <summary>
/// Gets or sets the value of this expression
/// </summary>
public override IAssemblyContext Value
{
get
{
return this.ModelElement.AssemblyContext__RequiredInfrastructureDelegationConnector;
}
set
{
this.ModelElement.AssemblyContext__RequiredInfrastructureDelegationConnector = value;
}
}
}
}
}
| 51.230337 | 317 | 0.64478 | [
"BSD-3-Clause"
] | NMFCode/NMF | IntegrationTests/ComponentBasedSoftwareArchitectures/Pcm/Core/Composition/RequiredInfrastructureDelegationConnector.cs | 36,478 | C# |
using System.ComponentModel.DataAnnotations;
using System.Configuration;
namespace FRTools.Web.Models
{
public class DressModelViewModel
{
[Display(Name = "Scry image URL")]
[Required]
public string ScryerUrl { get; set; }
[Display(Name = "Dressing image URL")]
[Required]
public string DressingRoomUrl { get; set; }
}
public class DressModelResultViewModel
{
public string PreviewUrl { get; set; }
public string CDNBasePath => ConfigurationManager.AppSettings["CDNBasePath"];
}
} | 27.190476 | 85 | 0.654991 | [
"MIT"
] | Nensec/FRSkinTester | FRTools.Web/Models/ScryerModels.cs | 573 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace DataLayer
{
public abstract class Event
{
public String Id { get; set; }
public DateTime dateTime { get; }
public StateOfSHOP state { get; set; }
public Customer customer { get; set; }
//constructor
public Event(string id, StateOfSHOP state, Customer customer, DateTime dateTime)
{
this.Id = id;
this.state = state;
this.customer = customer;
this.dateTime = dateTime;
}
//generated equals method
public override bool Equals(object obj)
{
var @event = obj as Event;
return @event != null &&
Id == @event.Id;
}
}
}
| 23.411765 | 88 | 0.545226 | [
"MIT"
] | 224088/zustyna | DoNutShopLibrary/DataLayer/Event.cs | 798 | C# |
using NationalInstruments.Shell;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Svn.Plugin.UserPreferences
{
/// <summary>
/// User preferences page factory export
/// </summary>
[ExportUserPreferences()]
public class SvnPropertiesPageProvider : UserPreferencesProvider
{
/// <inheritdoc/>
public override string PreferencesPageName
{
get
{
return "SVN Preferences";
}
}
/// <inheritdoc/>
public override IUserPreferencesPage CreatePage()
{
return Host.CreateInstance<SvnPreferencesPage>();
}
}
}
| 22.96875 | 68 | 0.613605 | [
"MIT"
] | benhysell/nxg-svn | Svn.Plugin/UserPreferences/SvnPropertiesPageProvider.cs | 737 | C# |
using System;
namespace Server
{
public class DocEvents
{
public event Action<DocDto> OnNewDoc;
public event Action<DocDto> OnUpdatedDoc;
public event Action<DocDto> OnDeletedDoc;
public void NewDoc(DocDto dto) => OnNewDoc?.Invoke(dto);
public void UpdateDoc(DocDto dto) => OnUpdatedDoc?.Invoke(dto);
public void DeletedDoc(DocDto dto) => OnDeletedDoc?.Invoke(dto);
}
} | 30.714286 | 72 | 0.669767 | [
"MIT"
] | askleon/BlazorDocs | src/Server/Services/DocEvents.cs | 430 | C# |
using System.Windows.Controls;
namespace Xe.Tools.Components.KernelEditor.Views
{
/// <summary>
/// Interaction logic for TabActorDropItems.xaml
/// </summary>
public partial class TabActorDropItems : UserControl
{
public TabActorDropItems()
{
InitializeComponent();
}
}
}
| 18.125 | 53 | 0.727586 | [
"MIT"
] | XeEngine/XeTools | Xe.Tools.Components.KernelEditor/Views/TabActorDropItems.xaml.cs | 292 | C# |
using System;
namespace Spyder.Console.Modules
{
public class SegmentEncoder : Segment
{
public SegmentEncoder(int portID) : base(portID, SegmentType.Encoder)
{
display.Startup(40, 2);
this.display.DisplayText = "Encoder";
}
}
}
| 17.5 | 71 | 0.714286 | [
"MIT"
] | dsmithson/Vista.Controllers.ScreenMaster3.SpyderTranslator | src/SpyderConsoleLibrary/Modules/SegmentEncoder.cs | 245 | C# |
using System;
using Microsoft.EntityFrameworkCore;
namespace Eon.Data.EfCore.Metadata.Edm {
public class EfCoreModelBuilderArgs {
readonly ModelBuilder _builder;
readonly Type _contextType;
readonly IDbProviderInfoProps _storeProviderInfo;
public EfCoreModelBuilderArgs(ModelBuilder builder, Type contextType, IDbProviderInfoProps storeProviderInfo) {
builder.EnsureNotNull(nameof(builder));
contextType
.EnsureNotNull(nameof(contextType))
.EnsureCompatible(type: typeof(DbContext));
storeProviderInfo =
storeProviderInfo
.EnsureNotNull(nameof(storeProviderInfo))
.AsReadOnly()
.EnsureValid()
.Value;
//
_builder = builder;
_contextType = contextType;
_storeProviderInfo = storeProviderInfo;
}
public ModelBuilder Builder
=> _builder;
public Type ContextType
=> _contextType;
public IDbProviderInfoProps StoreProviderInfo
=> _storeProviderInfo;
public override string ToString()
=>
$"{GetType()}:"
+ $"{Environment.NewLine}\t{nameof(Builder)}:{_builder.FmtStr().GNLI2()}"
+ $"{Environment.NewLine}\t{nameof(ContextType)}:{_contextType.FmtStr().GNLI2()}"
+ $"{Environment.NewLine}\t{nameof(StoreProviderInfo)}:{_storeProviderInfo.FmtStr().GNLI2()}";
}
} | 25.18 | 113 | 0.737093 | [
"MIT"
] | vitalik-mironov/eon-lib | src/eon-lib.ef-core/Data.EfCore.Metadata.Edm/EfCoreModelBuilderArgs.cs | 1,261 | C# |
using Assets.Scripts.Components.Events;
using Assets.Scripts.UI;
using SubjectNerd.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using Unity.Entities;
using Unity.Mathematics;
using UnityEngine;
public class AudioManager : MonoBehaviour, IEventObserver<PlayAudioEvent>
{
[Reorderable]
public List<AudioEntry> Clips = new List<AudioEntry>();
public EventRouter EventSource;
[Serializable]
public class AudioEntry
{
public SoundCategory Category;
public AudioClip Clip;
}
private List<AudioPlayer> _active = new List<AudioPlayer>();
private Stack<AudioPlayer> _pool = new Stack<AudioPlayer>();
private List<AudioPlayer> _keepBuffer = new List<AudioPlayer>();
private ILookup<SoundCategory, AudioEntry> _clipLookup;
private void Start()
{
_clipLookup = Clips.ToLookup(k => k.Category, v => v);
EventSource.AddListener<AudioManager, PlayAudioEvent>(this);
}
private void OnDestroy()
{
EventSource.RemoveListener<AudioManager, PlayAudioEvent>(this);
}
public class AudioPlayer
{
public float EndTime;
public AudioSource Source;
public Entity Entity;
}
public void OnEvent(PlayAudioEvent e)
{
if (e.Sound == SoundCategory.None)
{
Debug.LogError($"PlaySoundEvent detected with no sound specified");
}
if (_clipLookup.Contains(e.Sound))
{
var entry = _clipLookup[e.Sound].First();
var entity = e.AssociatedEntity;
if (!IsPlayingForEntity(entry.Clip, entity))
PlayForEntity(entry.Clip, entity);
}
}
private void PlayForEntity(AudioClip clip, Entity entity, float3? position = null)
{
AudioPlayer player = default;
if (_pool.Count > 0)
player = _pool.Pop();
else
player = CreatePlayer();
player.EndTime = Time.time + clip.length;
player.Entity = entity;
if (position != null)
player.Source.transform.position = position.Value;
player.Source.clip = clip;
player.Source.Play();
player.Source.gameObject.name = $"{entity} {clip.name}";
_active.Add(player);
}
private AudioPlayer CreatePlayer()
{
var go = new GameObject();
go.transform.parent = transform;
var source = go.AddComponent<AudioSource>();
var player = new AudioPlayer { Source = source };
return player;
}
private bool IsPlayingForEntity(AudioClip clip, Entity entity)
{
var isPlaying = false;
foreach (AudioPlayer player in _active)
{
if (!player.Source.isPlaying)
{
_pool.Push(player);
}
else
{
if (player.Entity == entity && clip == player.Source.clip)
isPlaying = true;
_keepBuffer.Add(player);
}
}
var tmp = _active;
_active = _keepBuffer;
_keepBuffer = tmp;
_keepBuffer.Clear();
return isPlaying;
}
} | 27.059322 | 86 | 0.598497 | [
"MIT"
] | jeffvella/UnityEcsEvents.Example | EventsExample/Assets/Game.Scripts/AudioManager.cs | 3,195 | C# |
using System.Collections.Generic;
using EvolveDb.Tests.Infrastructure;
using Xunit;
using Xunit.Abstractions;
using static EvolveDb.Tests.TestContext;
namespace EvolveDb.Tests.Integration.Cassandra
{
[Collection("Cassandra collection")]
public class MigrationTest
{
private readonly CassandraFixture _dbContainer;
private readonly ITestOutputHelper _output;
public MigrationTest(CassandraFixture dbContainer, ITestOutputHelper output)
{
_dbContainer = dbContainer;
_output = output;
if (Local)
{
dbContainer.Run(fromScratch: true);
}
}
[FactSkippedOnAppVeyor]
[Category(Test.Cassandra)]
public void Run_all_Cassandra_integration_tests_work()
{
// Arrange
string metadataKeyspaceName = "my_keyspace_1"; // this name must also be declared in _evolve.cassandra.json
var cnn = _dbContainer.CreateDbConnection();
var evolve = new Evolve(cnn, msg => _output.WriteLine(msg))
{
CommandTimeout = 25,
MetadataTableSchema = metadataKeyspaceName,
MetadataTableName = "evolve_change_log",
Placeholders = new Dictionary<string, string> { ["${keyspace}"] = metadataKeyspaceName },
SqlMigrationSuffix = ".cql"
};
// Assert
evolve.AssertInfoIsSuccessful(cnn)
.ChangeLocations(CassandraDb.MigrationFolder)
.AssertInfoIsSuccessful(cnn)
.AssertMigrateIsSuccessful(cnn)
.AssertInfoIsSuccessful(cnn);
evolve.ChangeLocations(CassandraDb.ChecksumMismatchFolder)
.AssertMigrateThrows<EvolveValidationException>(cnn)
.AssertRepairIsSuccessful(cnn, expectedNbReparation: 1)
.ChangeLocations(CassandraDb.MigrationFolder)
.AssertInfoIsSuccessful(cnn);
evolve.ChangeLocations()
.AssertEraseThrows<EvolveConfigurationException>(cnn, e => e.IsEraseDisabled = true)
.AssertEraseIsSuccessful(cnn, e => e.IsEraseDisabled = false)
.AssertInfoIsSuccessful(cnn);
evolve.ChangeLocations(CassandraDb.MigrationFolder)
.AssertMigrateIsSuccessful(cnn)
.AssertInfoIsSuccessful(cnn);
evolve.AssertEraseIsSuccessful(cnn, e => e.IsEraseDisabled = false);
// Call the second part of the Cassandra integration tests
DialectTest.Run_all_Cassandra_integration_tests_work(_dbContainer);
}
}
}
| 38.112676 | 119 | 0.622321 | [
"MIT"
] | JayDZimmerman/Evolve | test/Evolve.Tests/Integration/Cassandra/MigrationTest.cs | 2,708 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the elasticache-2015-02-02.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElastiCache.Model
{
/// <summary>
/// Returns the destination, format and type of the logs.
/// </summary>
public partial class LogDeliveryConfiguration
{
private DestinationDetails _destinationDetails;
private DestinationType _destinationType;
private LogFormat _logFormat;
private LogType _logType;
private string _message;
private LogDeliveryConfigurationStatus _status;
/// <summary>
/// Gets and sets the property DestinationDetails.
/// <para>
/// Configuration details of either a CloudWatch Logs destination or Kinesis Data Firehose
/// destination.
/// </para>
/// </summary>
public DestinationDetails DestinationDetails
{
get { return this._destinationDetails; }
set { this._destinationDetails = value; }
}
// Check to see if DestinationDetails property is set
internal bool IsSetDestinationDetails()
{
return this._destinationDetails != null;
}
/// <summary>
/// Gets and sets the property DestinationType.
/// <para>
/// Returns the destination type, either <code>cloudwatch-logs</code> or <code>kinesis-firehose</code>.
/// </para>
/// </summary>
public DestinationType DestinationType
{
get { return this._destinationType; }
set { this._destinationType = value; }
}
// Check to see if DestinationType property is set
internal bool IsSetDestinationType()
{
return this._destinationType != null;
}
/// <summary>
/// Gets and sets the property LogFormat.
/// <para>
/// Returns the log format, either JSON or TEXT.
/// </para>
/// </summary>
public LogFormat LogFormat
{
get { return this._logFormat; }
set { this._logFormat = value; }
}
// Check to see if LogFormat property is set
internal bool IsSetLogFormat()
{
return this._logFormat != null;
}
/// <summary>
/// Gets and sets the property LogType.
/// <para>
/// Refers to <a href="https://redis.io/commands/slowlog">slow-log</a>.
/// </para>
/// </summary>
public LogType LogType
{
get { return this._logType; }
set { this._logType = value; }
}
// Check to see if LogType property is set
internal bool IsSetLogType()
{
return this._logType != null;
}
/// <summary>
/// Gets and sets the property Message.
/// <para>
/// Returns an error message for the log delivery configuration.
/// </para>
/// </summary>
public string Message
{
get { return this._message; }
set { this._message = value; }
}
// Check to see if Message property is set
internal bool IsSetMessage()
{
return this._message != null;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// Returns the log delivery configuration status. Values are one of <code>enabling</code>
/// | <code>disabling</code> | <code>modifying</code> | <code>active</code> | <code>error</code>
///
/// </para>
/// </summary>
public LogDeliveryConfigurationStatus Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
}
} | 30.477419 | 111 | 0.579382 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/ElastiCache/Generated/Model/LogDeliveryConfiguration.cs | 4,724 | C# |
using System;
using BookN;
using CargoN;
using ClientN;
using ActiveElements;
namespace BookShopN {
namespace UI {
static class Validator {
static public bool IsEmail(string str) {
bool sob = false;
foreach (char i in str) {
if (i == '@')
sob = true;
if (sob && i == '.')
return true;
}
return false;
}
static public bool IsPhone(string str) {
foreach (char i in str)
if (!char.IsNumber(i))
return false;
return true;
}
static public string ValidStr(string str, byte len) {
if (str.Length < len)
str += new string(' ', len - str.Length);
else if (str.Length > len)
str = str.Substring(0, len - 3) + "...";
return str;
}
}
class UiConsoleBookShop {
BookShop shop;
Coord downRightCorner = new Coord(150, 45);
ActiveElementDraw head;
delegate bool NextWindow();
public UiConsoleBookShop() : this(null) {
}
public UiConsoleBookShop(ICargo Cargo) {
string verticalLine = "|\n";
for (byte i = 0; i < 44; ++i)
verticalLine += "|\n";
shop = new BookShop(Cargo);
head = new ActiveElementDraw(
new ActiveStaticElement("Main", new Coord(2, 1)),
new ActiveInputElement("Find: " + new string(' ', 75), new Coord(21, 1), new Coord(6, 0), 74),
new ActiveDoubleElement("Login/Register", new Coord(134, 1), "Logout", new Coord(134, 1)),
new StaticElement(new string('_', downRightCorner.x), new Coord(0, 0)),
new StaticElement(new string('_', downRightCorner.x), new Coord(0, downRightCorner.y)),
new StaticElement(new string('-', downRightCorner.x - 2), new Coord(1, 2)),
new StaticElement(verticalLine, new Coord(0, 1)),
new StaticElement(verticalLine, new Coord(downRightCorner.x, 1)),
new StaticElement("|", new Coord(7, 1)),
new StaticElement("|", new Coord(20, 1)),
new StaticElement("|", new Coord(102, 1)),
new StaticElement("|", new Coord(133, 1)),
new StaticElement("|", new Coord(148, 1))
);
}
public void Launch() {
Console.SetWindowSize(Console.LargestWindowWidth, Console.LargestWindowHeight);
PrintHelloScreen();
//System.Threading.Thread.Sleep(1500);
Console.Clear();
MainScreen();
Console.Clear();
}
ConsoleKeyInfo InbisibleInput() {
Console.SetCursorPosition(103, 1);
ConsoleColor prev = Console.ForegroundColor;
Console.ForegroundColor = Console.BackgroundColor;
ConsoleKeyInfo rez = Console.ReadKey();
Console.ForegroundColor = prev;
return rez;
}
void PrintHelloScreen() {
Console.Write("\n\n\n\n\n\n\n\n\n" + @"
.-. .-') ^,,^ .-. .-') .-') ('-. .-. _ (`-.
\ ( OO ) ( oO ) \ ( OO ) ( OO ). ( OO ) / ( (OO )
;-----.\ .-'),-----. ,-----. ,--. ,--. (_)---\_) ,--. ,--. .-'),-----. _.` \
| .-. | ( OO' .-. ' ' .-. ' | .' / / _ | | | | | ( OO' .-. ' (__...--''
| '-' /_) / | | | | | | | | | /, \ :` `. | .| | / | | | | | / | |
| .-. `. \_) | |\| | | | | | | ' _) '..`''.) | | \_) | |\| | | |_.' |
| | \ | \ | | | | | | | | | . \ .-._) \ | .-. | \ | | | | | .___.'
| '--' / `' '-' ' ' '-' ' | |\ \ \ / | | | | `' '-' ' | |
`------' `-------' `-------' `--' '--' `-----' `--' `-' `------' `-' ");
}
void MainScreen() {
string[] bookTypes = shop.GetBookTypes();
Element[] mainScreenElements = new Element[bookTypes.Length + 3];
mainScreenElements[0] = new ActiveStaticElement("__________\n| Trash |\n----------", new Coord((short)(downRightCorner.x - 10),4));
mainScreenElements[1] = mainScreenElements[2] = null;
for (byte i = 0; i < bookTypes.Length; ++i)
mainScreenElements[i + 3] = new ActiveStaticElement(bookTypes[i], new Coord(5, (short)(i + 4)));
byte choose;
ActiveElementDraw mainWindow = new ActiveElementDraw(head, mainScreenElements);
mainWindow.InitStatic();
while (true) {
mainWindow.Print();
choose = mainWindow.Input(InbisibleInput());
if (choose == 255)
continue;
switch (choose) {
//Main
case 0:
if (WantToExit())
return;
break;
//Find
case 1:
mainWindow.ClearScreen();
BooksListByName();
mainWindow.InitStatic();
break;
//Register/Login Logout
case 2:
mainWindow.ClearScreen();
ClickOnLoginBtn();
if (shop.IsLogOn())
mainScreenElements[1] = new ActiveStaticElement("__________\n|UserInfo|\n----------", new Coord((short)(downRightCorner.x - 10), 7));
else
mainScreenElements[1] = null;
if (shop.IsSuperUserLogOn())
mainScreenElements[2] = new ActiveStaticElement("____________\n|AdminPanel|\n------------", new Coord((short)(downRightCorner.x - 12), 10));
else
mainScreenElements[2] = null;
mainWindow = new ActiveElementDraw(head, mainScreenElements);
mainWindow.InitStatic();
break;
//Trash manager
case 13:
mainWindow.ClearScreen();
TrashScreen(shop.GetClientTrash());
mainWindow.InitStatic();
break;
//User profile
case 14:
mainWindow.ClearScreen();
UserScreen(shop.GetClient());
mainWindow.InitStatic();
break;
//Admin terminal
case 15:
mainWindow.ClearScreen();
AdminPanel();
mainWindow.InitStatic();
break;
default:
if (choose >= 16) {
mainWindow.ClearScreen();
BooksListByType((Book.BookTypes)(choose - 15));
mainWindow.InitStatic();
}
break;
}
}
}
bool WantToExit() {
return false;
}
void UserScreen(Client user) {
Console.SetCursorPosition(100, 40);
Console.Write("UserScreen");
}
bool TrashScreen(Trash trash) {
Element[] trashToPrint = new Element[trash.Length * 3 + 2];
Book currBook;
string str;
for (int i = 0; i < trash.Length; ++i) {
if (trash[i].stored is Book) {
currBook = trash[i].stored as Book;
str = Validator.ValidStr(currBook.shortTitle, 16) + " | ";
str += Validator.ValidStr(currBook.autherName, 16) + " | ";
str += Validator.ValidStr(currBook.price.ToString(), 7);
trashToPrint[i * 3] = new ActiveStaticElement(str, new Coord(5,(short)(i + 5)));
trashToPrint[i * 3 + 1] = new ActiveCounter("-----", new Coord(53, (short)(i + 5)), new Coord(1, 0), ref trash[i].cnt, 1, 255, " ");
trashToPrint[i * 3 + 2] = new ActiveStaticElement("X", new Coord(62, (short)(i + 5)));
}
}
str = Validator.ValidStr("Title", 16) + " | ";
str += Validator.ValidStr("Auther name", 16) + " | ";
str += Validator.ValidStr("Price", 7) + " | ";
str += Validator.ValidStr("Cnt", 5) + " | ";
str += Validator.ValidStr("Del", 5);
trashToPrint[trash.Length * 3] = new StaticElement(str, new Coord(5, 4));
if (trash.Length != 0) {
string buyBtn = "_____\n|Buy|\n-----";
trashToPrint[trash.Length * 3 + 1] = new ActiveStaticElement(buyBtn, new Coord((short)(str.Length / 2 - buyBtn.Length / 2), (short)(trash.Length + 6)));
}
else
trashToPrint[trash.Length * 3 + 1] = null;
byte choose;
ActiveElementDraw trashWindow = new ActiveElementDraw(head, trashToPrint);
NextWindow nextWindow = null;
trashWindow.InitStatic();
while (true) {
trashWindow.Print();
choose = trashWindow.Input(InbisibleInput());
if (choose == 255)
continue;
switch (choose) {
//Main
case 0:
goto TRASH_SCREEN_RETURN;
//Find
case 1:
nextWindow = new NextWindow(BooksListByName);
goto TRASH_SCREEN_RETURN;
//Register/Login Logout
case 2:
nextWindow = new NextWindow(ClickOnLoginBtn);
goto TRASH_SCREEN_RETURN;
default:
choose -= 13;
if(choose == trash.Length * 3 + 1) {
TrashObj[] deliver = shop.Buy();
trashWindow.ClearScreen();
bool accept = AcceptBeforeDeliver(deliver);
trashWindow.InitStatic();
if (accept) {
if (shop.IsLogOn())
;//Послать юзеру
else
;//Открить окно ввода адреса
}
else {
foreach (var i in deliver)
if (i.cnt != 0 && i.stored != null) {
shop.GetClientTrash().Add(i);
for (int j = 0; j < i.cnt; ++j)
shop.GetCargo().Add(i.stored);
}
}
goto TRASH_SCREEN_RETURN;
}
else if (choose % 3 == 0) {
trashWindow.ClearScreen();
BookInfoScreen(((Book)trash[choose / 3].stored), false);
trashWindow.InitStatic();
}
else if (choose % 3 == 2) {
trash.Delete(((Book)trash[choose / 3].stored));
trashWindow.ClearScreen();
TrashScreen(trash);
goto TRASH_SCREEN_RETURN;
}
break;
}
}
TRASH_SCREEN_RETURN:
trashWindow.ClearScreen();
if (nextWindow != null)
nextWindow.Invoke();
return true;
}
bool AcceptBeforeDeliver(TrashObj[] toDeliver) {
Element[] trashToPrint = new Element[toDeliver.Length * 3 + 3];
Book currBook;
string str;
for (int i = 0; i < toDeliver.Length; ++i) {
if (toDeliver[i].stored is Book) {
currBook = toDeliver[i].stored as Book;
str = Validator.ValidStr(currBook.shortTitle, 16) + " | ";
str += Validator.ValidStr(currBook.autherName, 16) + " | ";
str += Validator.ValidStr(currBook.price.ToString(), 7);
trashToPrint[i * 3] = new StaticElement(str, new Coord(5, (short)(i + 5)));
trashToPrint[i * 3 + 1] = new StaticElement(toDeliver[i].cnt.ToString(), new Coord(53, (short)(i + 5)) );
if(toDeliver[i].cnt == 0)
trashToPrint[i * 3 + 2] = new StaticElement("not in stock", new Coord(62, (short)(i + 5)));
else
trashToPrint[i * 3 + 2] = new StaticElement("", new Coord(62, (short)(i + 5)));
}
}
str = Validator.ValidStr("Title", 16) + " | ";
str += Validator.ValidStr("Auther name", 16) + " | ";
str += Validator.ValidStr("Price", 7) + " | ";
str += Validator.ValidStr("Cnt", 5) + " | ";
trashToPrint[toDeliver.Length * 3] = new StaticElement(str, new Coord(5, 4));
if (toDeliver.Length != 0) {
string buyBtn = "_____\n|Buy|\n-----";
trashToPrint[toDeliver.Length * 3 + 1] = new ActiveStaticElement(buyBtn, new Coord((short)(str.Length / 2 - buyBtn.Length / 2 - 10), (short)(toDeliver.Length + 6)));
buyBtn = "________\n|Cancel|\n--------";
trashToPrint[toDeliver.Length * 3 + 2] = new ActiveStaticElement(buyBtn, new Coord((short)(str.Length / 2 - buyBtn.Length / 2 + 10), (short)(toDeliver.Length + 6)));
}
else {
trashToPrint[toDeliver.Length * 3 + 1] = trashToPrint[toDeliver.Length * 3 + 2] = null;
}
byte choose;
ActiveElementDraw trashWindow = new ActiveElementDraw(head, trashToPrint);
trashWindow.InitStatic();
while (true) {
trashWindow.Print();
choose = trashWindow.Input(InbisibleInput());
choose -= 13;
if (choose == 255)
continue;
if (choose == toDeliver.Length * 3 + 1) {
trashWindow.ClearScreen();
return true;
}
if (choose == toDeliver.Length * 3 + 2) {
trashWindow.ClearScreen();
return false;
}
}
}
void AdminPanel() {
bool isRunning = true;
string str;
Console.SetCursorPosition(0, 0);
while (isRunning) {
Console.Write("> ");
str = Console.ReadLine();
str = str.Trim();
if (str == "exit")
isRunning = false;
else if (str == "?") {
Console.Write('\t'); Console.WriteLine("exit");
}
AdminInput(str);
}
Console.Clear();
}
public void AdminInput(string str) {
if (str == "?") {
Console.Write('\t'); Console.WriteLine("add [bookTitle] | [author] | [price] | [pages]");
Console.Write('\t'); Console.WriteLine("del [bookTitle] | [author]");
}
else if (str.Substring(0, 3) == "del") {
str = str.Substring(3, str.Length - 3);
string[] info = new string[2];
char[] sep = new char[] { '|' };
info = str.Split(sep, info.Length);
for (int i = 0; i < info.Length; ++i)
info[i] = info[i].Trim();
if (shop.GetCargo().Remove(new Book(Book.BookTypes.NONE, info[1], info[0], 0, 0)) != null)
Console.WriteLine("del succes");
else
Console.WriteLine("book not exist");
}
else if (str.Substring(0, 3) == "add") {
str = str.Substring(3, str.Length - 3);
string[] info = new string[4];
double price;
int pages;
char[] sep = new char[] { '|' };
info = str.Split(sep, info.Length);
for (int i = 0; i < info.Length; ++i)
info[i] = info[i].Trim();
if (!double.TryParse(info[2], out price) || !int.TryParse(info[3], out pages))
Console.WriteLine("add error");
else {
shop.GetCargo().Add(new Book(Book.BookTypes.NONE, info[1], info[0], double.Parse(info[2]), (ushort)int.Parse(info[3])));
Console.WriteLine("add succes");
}
}
}
bool BooksListByType(Book.BookTypes type) {
System.Collections.Generic.List<Book> find = shop.FindBookByType(type);
if (find.Count == 0)
return false;
return BooksListScreen(find);
}
bool BooksListByName() {
string toFind = head.GetInputValue(1);
if (toFind.Length < 3)
return false;
System.Collections.Generic.List<Book> find = shop.FindBookByTitle(toFind);
if (find.Count == 0)
return false;
return BooksListScreen(find);
}
bool BooksListScreen(System.Collections.Generic.List<Book> find) {
bool toReturn = false;
Element[] booksToPrint = new Element[find.Count + 2];
Book currBook = null;
string str = null;
int len = find.Count > downRightCorner.y - 7 ? downRightCorner.y - 7 : find.Count;
for (int i = 0; i < len; ++i) {
currBook = find[i];
str = Validator.ValidStr(currBook.shortTitle, 16) + " | ";
str += Validator.ValidStr(currBook.autherName, 16) + " | ";
str += Validator.ValidStr(currBook.price.ToString(), 7);
if(i % 2 == 0)
booksToPrint[i] = new ActiveStaticElement(str, new Coord(5, (short)(i / 2 + 5)));
else
booksToPrint[i] = new ActiveStaticElement(str, new Coord((short)(downRightCorner.x / 2 + 3), (short)(i / 2 + 5)));
}
str = Validator.ValidStr("Title", 16) + " | ";
str += Validator.ValidStr("Auther name", 16) + " | ";
str += Validator.ValidStr("Price", 7);
booksToPrint[find.Count] = new StaticElement(str, new Coord(5, 4));
if (find.Count != 1)
booksToPrint[find.Count + 1] = new StaticElement(str, new Coord((short)(downRightCorner.x / 2 + 3), 4));
else
booksToPrint[find.Count + 1] = new StaticElement("",new Coord(0,0));
byte choose;
ActiveElementDraw findWindow = new ActiveElementDraw(head, booksToPrint);
NextWindow nextWindow = null;
findWindow.InitStatic();
while (true) {
findWindow.Print();
choose = findWindow.Input(InbisibleInput());
if (choose == 255)
continue;
switch (choose) {
//Main
case 0:
goto BOOK_LIST_SCREEN_RETURN;
//Find
case 1:
nextWindow = new NextWindow(BooksListByName);
goto BOOK_LIST_SCREEN_RETURN;
//Register/Login Logout
case 2:
nextWindow = new NextWindow(ClickOnLoginBtn);
goto BOOK_LIST_SCREEN_RETURN;
default:
if (choose >= 13) {
findWindow.ClearScreen();
if(BookInfoScreen(find[choose - 13]))
goto BOOK_LIST_SCREEN_RETURN;
findWindow.InitStatic();
}
break;
}
}
BOOK_LIST_SCREEN_RETURN:
findWindow.ClearScreen();
head.InitStatic();
if (nextWindow != null)
nextWindow.Invoke();
return toReturn;
}
bool BookInfoScreen(Book book, bool withTrashBtn = true) {
if(book == null)
return false;
byte choose;
ActiveElementDraw bookWindow;
if (withTrashBtn) {
bookWindow = new ActiveElementDraw(head,
new StaticElement('[' + book.type.ToString() + "] " + book.shortTitle, new Coord((short)(downRightCorner.x / 2 + 3), 5)),
new StaticElement(book.autherName, new Coord((short)(downRightCorner.x / 2 + 3), 6)),
new StaticElement("Price:" + book.price.ToString(), new Coord((short)(downRightCorner.x / 2 + 3), 7)),
new StaticElement("Pages:" + book.pages.ToString(), new Coord((short)(downRightCorner.x / 2 + 3), 8)),
new ActiveStaticElement("______________\n|Add to trash|\n--------------", new Coord((short)(downRightCorner.x / 2 + downRightCorner.x / 6), 15))
);
}
else {
bookWindow = new ActiveElementDraw(head,
new StaticElement('[' + book.type.ToString() + "] " + book.shortTitle, new Coord((short)(downRightCorner.x / 2 + 3), 5)),
new StaticElement(book.autherName, new Coord((short)(downRightCorner.x / 2 + 3), 6)),
new StaticElement("Price:" + book.price.ToString(), new Coord((short)(downRightCorner.x / 2 + 3), 7)),
new StaticElement("Pages:" + book.pages.ToString(), new Coord((short)(downRightCorner.x / 2 + 3), 8))
);
}
NextWindow nextWindow = null;
bookWindow.InitStatic();
while (true) {
bookWindow.Print();
choose = bookWindow.Input(InbisibleInput());
if (choose == 255)
continue;
switch (choose) {
//Main
case 0:
goto BOOK_INFO_SCREEN_RETURN;
//Find
case 1:
nextWindow = new NextWindow(BooksListByName);
goto BOOK_INFO_SCREEN_RETURN;
//Register/Login Logout
case 2:
nextWindow = new NextWindow(ClickOnLoginBtn);
goto BOOK_INFO_SCREEN_RETURN;
case 17:
shop.AddToTrash(book);
goto BOOK_INFO_SCREEN_RETURN;
default:
break;
}
}
BOOK_INFO_SCREEN_RETURN:
bookWindow.ClearScreen();
head.InitStatic();
if (nextWindow != null) {
nextWindow.Invoke();
return true;
}
return false;
}
bool ClickOnLoginBtn() {
if (head.GetDoubleElementContrain(2)) {
shop.Logoff();
head.ChangeDoubleElementContrain(2);
return false;
}
RegisterAndLoginScreen();
return true;
}
void RegisterAndLoginScreen() {
byte choose;
ActiveElementDraw loginWindow;
NextWindow nextWindow = null;
{
loginWindow = new ActiveElementDraw(head,
new StaticElement(" ::Login::", new Coord(10, 5)),
new ActiveInputElement("Login:" + new string(' ', 16), new Coord(10, 7), new Coord(7, 0), 15),
new ActiveInputElement("Pass:" + new string(' ', 34), new Coord(10, 8), new Coord(7, 0), 32),
new ActiveStaticElement("-------\n|Login|\n-------", new Coord(10, 10)),
new StaticElement("╔══╗╔═══╗\n║╔╗║║╔═╗║\n║║║║║╚═╝║\n║║║║║╔╗╔╝\n║╚╝║║║║║\n╚══╝╚╝╚╝", new Coord((short)(downRightCorner.x / 2 - 10), (short)(downRightCorner.y / 2 - 5))),
new StaticElement(" ::Register::", new Coord((short)(downRightCorner.x / 2 + 10), 5)),
new ActiveInputElementAllSymbols("E-mail: " + new string(' ', 31), new Coord((short)(downRightCorner.x / 2 + 10), 7), new Coord(8, 0), 32),
new ActiveInputElement("Login: " + new string(' ', 17), new Coord((short)(downRightCorner.x / 2 + 10), 8), new Coord(8, 0), 16),
new ActiveInputElement("Pass: " + new string(' ', 34), new Coord((short)(downRightCorner.x / 2 + 10), 9), new Coord(8, 0), 32),
new ActiveInputElement("Name: " + new string(' ', 16), new Coord((short)(downRightCorner.x / 2 + 10), 11), new Coord((short)"Name: ".Length, 0), 16),
new ActiveInputElement("Surname: " + new string(' ', 16), new Coord((short)(downRightCorner.x / 2 + 10), 12), new Coord((short)"Surname: ".Length, 0), 16),
new ActiveInputElement("Phone: " + new string(' ', 13), new Coord((short)(downRightCorner.x / 2 + 10), 13), new Coord((short)"Phone: ".Length, 0), 10),
new ActiveStaticElement("----------\n|Register|\n----------", new Coord((short)(downRightCorner.x / 2 + 10), 15))
);
}
loginWindow.InitStatic();
while (true) {
loginWindow.Print();
choose = loginWindow.Input(InbisibleInput());
if (choose == 255)
continue;
switch (choose) {
//Main
case 0:
goto REGISTER_AND_LOGIN_RETURN;
//Find
case 1:
nextWindow = new NextWindow(BooksListByName);
goto REGISTER_AND_LOGIN_RETURN;
//Register/Login Logout
case 2:
break;
//Login
case 16:
if (shop.Login(loginWindow.GetInputValue(14), LoginPass.Hasher(loginWindow.GetInputValue(15))) != null) {
head.ChangeDoubleElementContrain(2);
goto REGISTER_AND_LOGIN_RETURN;
}
break;
//Register
case 25:
if (loginWindow.GetInputValue(22).Length == 0 || loginWindow.GetInputValue(23).Length == 0
|| loginWindow.GetInputValue(24).Length == 0 || loginWindow.GetInputValue(21).Length == 0
|| loginWindow.GetInputValue(20).Length == 0 || loginWindow.GetInputValue(19).Length == 0
)
break;
if (! (Validator.IsEmail(loginWindow.GetInputValue(19)) && Validator.IsPhone(loginWindow.GetInputValue(24)) ))
break;
if (shop.CreateUser(new Person(loginWindow.GetInputValue(22), loginWindow.GetInputValue(23), loginWindow.GetInputValue(24)),
loginWindow.GetInputValue(20), LoginPass.Hasher(loginWindow.GetInputValue(21)), loginWindow.GetInputValue(19))) {
shop.Login(loginWindow.GetInputValue(20), LoginPass.Hasher(loginWindow.GetInputValue(21)));
head.ChangeDoubleElementContrain(2);
goto REGISTER_AND_LOGIN_RETURN;
}
break;
default:
//Console.Write(choose);
break;
}
}
REGISTER_AND_LOGIN_RETURN:
loginWindow.ClearScreen();
head.InitStatic();
if (nextWindow != null)
nextWindow.Invoke();
}
}
}
} | 34.122862 | 174 | 0.583018 | [
"MIT"
] | Team-on/works | 0_homeworks/C#/1 Console/6/BookShop/UI.cs | 22,081 | C# |
namespace Serene.Administration
{
using Serenity.Services;
public class RolePermissionListRequest : ServiceRequest
{
public int? RoleID { get; set; }
public string Module { get; set; }
public string Submodule { get; set; }
}
} | 22.416667 | 59 | 0.639405 | [
"MIT"
] | EitanBlumin/generic-api-platform | generic-api-platform/Serene/Serene.Web/Modules/Administration/RolePermission/RolePermissionListRequest.cs | 271 | C# |
/* Copyright 2013-present MongoDB 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 MongoDB.Driver.Core.Clusters;
using MongoDB.Driver.Core.Connections;
using MongoDB.Driver.Core.Servers;
namespace MongoDB.Driver.Core.Events
{
/// <preliminary/>
/// <summary>
/// Occurs after a connection is added to the pool.
/// </summary>
public struct ConnectionPoolAddedConnectionEvent
{
private readonly ConnectionId _connectionId;
private readonly TimeSpan _duration;
private readonly long? _operationId;
/// <summary>
/// Initializes a new instance of the <see cref="ConnectionPoolAddedConnectionEvent" /> struct.
/// </summary>
/// <param name="connectionId">The connection identifier.</param>
/// <param name="duration">The duration of time it took to add the connection to the pool.</param>
/// <param name="operationId">The operation identifier.</param>
public ConnectionPoolAddedConnectionEvent(ConnectionId connectionId, TimeSpan duration, long? operationId)
{
_connectionId = connectionId;
_duration = duration;
_operationId = operationId;
}
/// <summary>
/// Gets the cluster identifier.
/// </summary>
public ClusterId ClusterId
{
get { return _connectionId.ServerId.ClusterId; }
}
/// <summary>
/// Gets the connection identifier.
/// </summary>
public ConnectionId ConnectionId
{
get { return _connectionId; }
}
/// <summary>
/// Gets the duration of time it took to add the server to the pool.
/// </summary>
public TimeSpan Duration
{
get { return _duration; }
}
/// <summary>
/// Gets the operation identifier.
/// </summary>
public long? OperationId
{
get { return _operationId; }
}
/// <summary>
/// Gets the server identifier.
/// </summary>
public ServerId ServerId
{
get { return _connectionId.ServerId; }
}
}
}
| 32.16092 | 115 | 0.600071 | [
"MIT"
] | naivetang/2019MiniGame22 | Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Events/ConnectionPoolAddedConnectionEvent.cs | 2,798 | C# |
using System;
using System.Linq;
public class SumBigNumbers
{
public static void Main()
{
var firstNum = Console.ReadLine();
var secondNum = Console.ReadLine();
var maxLen = Math.Max(firstNum.Length, secondNum.Length);
firstNum = firstNum.PadLeft(maxLen + 1, '0');
secondNum = secondNum.PadLeft(maxLen + 1, '0');
var firstDigits = firstNum.Select(x => int.Parse(x.ToString())).ToArray();
var secondDigits = secondNum.Select(x => int.Parse(x.ToString())).ToArray();
var sum = new int[firstNum.Length];
int currentSum = 0;
for (int i = sum.Length - 1; i >= 0; i--)
{
int total = firstDigits[i] + secondDigits[i] + currentSum;
sum[i] = total % 10;
if (total > 9)
{
currentSum = 1;
}
else
{
currentSum = 0;
}
}
var result = string.Join(string.Empty, sum.SkipWhile(x => x == 0));
Console.WriteLine(result);
}
} | 30.314286 | 84 | 0.523091 | [
"Apache-2.0"
] | Warglaive/TechModuleSeptember2017 | Strings and Text Processing - Exercises/06. Sum big numbers/06. Sum big numbers.cs | 1,063 | C# |
using CalendarPlus.Product.Contracts.Repositories.Shared;
using CalendarPlus.Product.Contracts.Services;
using CalendarPlus.Product.Contracts.Services.Shared;
using CalendarPlus.Product.Contracts.Shared;
using CalendarPlus.SystemObjects;
using CalendarPlus.SystemObjects.Interfaces;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace CalendarPlus.Services.Shared
{
public abstract class GenericCachedEntityService<TEntity> : GenericEntityService<TEntity>, IGenericCachedEntityService<TEntity> where TEntity : class, IEntity
{
public ICurrentSessionUser _currentSessionUser { get; private set; }
protected readonly ICacheProvider _cacheProvider;
public GenericCachedEntityService(
ICurrentSessionUser currentSessionUser,
ICacheProvider cacheProvider,
IGenericRepository<TEntity> TEntityRepository,
IUnitOfWorkFactory<UnitOfWork> uow) : base(TEntityRepository, uow)
{
_currentSessionUser = currentSessionUser;
_cacheProvider = cacheProvider;
}
public override async Task<IEnumerable<TEntity>> FindAllAsync(CancellationToken cancellationToken = default, int skip = 0, int take = 20)
{
string key = $"{GetCacheKeyPrefix()}:{ typeof(TEntity).Name }:FindAll:Skip={skip}:Take={take}";
IEnumerable<TEntity> dataFromCache = await _cacheProvider.FindCacheAsync<IEnumerable<TEntity>>(key, cancellationToken);
if (dataFromCache == null)
{
IEnumerable<TEntity> dataFromDb = await base.FindAllAsync(cancellationToken, skip, take);
if (dataFromDb == null || !dataFromDb.Any())
{
return default;
}
await _cacheProvider.CreateAsync(key, dataFromDb, null, cancellationToken);
return dataFromDb;
}
return dataFromCache;
}
public override async Task<TEntity> GetOneAsync(int id, CancellationToken cancellationToken = default)
{
string key = $"{GetCacheKeyPrefix()}:{ typeof(TEntity).Name }:GetOne={id}";
TEntity dataFromCache = await _cacheProvider.FindCacheAsync<TEntity>(key, cancellationToken);
if (dataFromCache == null)
{
TEntity dataFromDb = await base.GetOneAsync(id, cancellationToken);
if (dataFromDb == null)
{
return default;
}
await _cacheProvider.CreateAsync(key, dataFromDb, null, cancellationToken);
return dataFromDb;
}
return dataFromCache;
}
public override async Task<TEntity> CreateAsync(TEntity entity, CancellationToken cancellationToken = default)
{
TEntity newRecord = await base.CreateAsync(entity, cancellationToken);
if (newRecord != null)
{
await _cacheProvider.InvalidateCacheAsync<TEntity>();
}
return newRecord;
}
public override async Task<TEntity> UpdateAsync(int id, TEntity entity, CancellationToken cancellationToken = default)
{
TEntity record = await base.UpdateAsync(id, entity, cancellationToken);
if (record != null)
{
await _cacheProvider.InvalidateCacheAsync<TEntity>();
}
return record;
}
public override async Task DeleteAsync(int id, CancellationToken cancellationToken = default)
{
await base.DeleteAsync(id, cancellationToken);
await _cacheProvider.InvalidateCacheAsync<TEntity>();
}
private string GetCacheKeyPrefix()
{
if (_currentSessionUser != null && string.IsNullOrEmpty(_currentSessionUser.Id) == false)
{
return $"{_currentSessionUser.Id}";
}
else
{
return "Anonymous";
}
}
}
}
| 34.705882 | 162 | 0.622518 | [
"MIT"
] | luca0898/calendar-plus | new_project/backend/CalendarPlus.Services/Shared/GenericCachedEntityService.cs | 4,132 | C# |
namespace Zoo.Rpc.Abstractions.Constants
{
/// <summary>
/// Parameter names, these names will be used in the URI query parameters.
/// </summary>
public static class ParameterNames
{
/// <summary>
/// Node type.
/// </summary>
public const string NodeType = nameof(NodeType);
/// <summary>
/// Service version.
/// </summary>
public const string ServiceVersion = nameof(ServiceVersion);
/// <summary>
/// Load balance.
/// </summary>
public const string LoadBalance = nameof(LoadBalance);
}
} | 26.73913 | 78 | 0.565854 | [
"Apache-2.0"
] | aguang-xyz/zoo | src/Zoo.Rpc.Abstractions/Constants/ParameterNames.cs | 615 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace kryon_graphology_challenge
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
}
| 32.741935 | 123 | 0.670936 | [
"MIT"
] | wjeremies/challenge2019-master | kryon-graphology-challenge/Startup.cs | 1,017 | C# |
/* Copyright 2013-present MongoDB 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.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Bson.TestHelpers;
using MongoDB.Bson.TestHelpers.XunitExtensions;
using MongoDB.Driver.Core.Misc;
using MongoDB.Driver.Core.TestHelpers.XunitExtensions;
using Xunit;
namespace MongoDB.Driver.Core.Operations
{
public class ListCollectionsUsingCommandOperationTests : OperationTestBase
{
// constructors
public ListCollectionsUsingCommandOperationTests()
{
_databaseNamespace = CoreTestConfiguration.GetDatabaseNamespaceForTestClass(typeof(ListCollectionsUsingCommandOperationTests));
}
// test methods
[Fact]
public void constructor_should_initialize_subject()
{
var subject = new ListCollectionsUsingCommandOperation(_databaseNamespace, _messageEncoderSettings);
subject.DatabaseNamespace.Should().BeSameAs(_databaseNamespace);
subject.MessageEncoderSettings.Should().BeSameAs(_messageEncoderSettings);
subject.Filter.Should().BeNull();
subject.RetryRequested.Should().BeFalse();
}
[Fact]
public void constructor_should_throw_when_databaseNamespace_is_null()
{
Action action = () => new ListCollectionsUsingCommandOperation(null, _messageEncoderSettings);
action.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("databaseNamespace");
}
[Fact]
public void constructor_should_throw_when_messageEncoderSettings_is_null()
{
Action action = () => new ListCollectionsUsingCommandOperation(_databaseNamespace, null);
action.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("messageEncoderSettings");
}
[Fact]
public void BatchSize_get_and_set_should_work()
{
var subject = new ListCollectionsUsingCommandOperation(_databaseNamespace, _messageEncoderSettings);
int batchSize = 2;
subject.BatchSize = batchSize;
var result = subject.BatchSize;
result.Should().Be(batchSize);
}
[Fact]
public void Filter_get_and_set_should_work()
{
var subject = new ListCollectionsUsingCommandOperation(_databaseNamespace, _messageEncoderSettings);
var filter = new BsonDocument("name", "abc");
subject.Filter = filter;
var result = subject.Filter;
result.Should().BeSameAs(filter);
}
[Theory]
[ParameterAttributeData]
public void NameOnly_get_and_set_should_work(
[Values(null, false, true)] bool? nameOnly)
{
var subject = new ListCollectionsUsingCommandOperation(_databaseNamespace, _messageEncoderSettings);
subject.NameOnly = nameOnly;
var result = subject.NameOnly;
result.Should().Be(nameOnly);
}
[Theory]
[ParameterAttributeData]
public void RetryRequested_get_and_set_should_work(
[Values(false, true)] bool value)
{
var subject = new ListCollectionsUsingCommandOperation(_databaseNamespace, _messageEncoderSettings);
subject.RetryRequested = value;
var result = subject.RetryRequested;
result.Should().Be(value);
}
[SkippableTheory]
[ParameterAttributeData]
public void Execute_should_return_the_expected_result(
[Values(false, true)]
bool async)
{
RequireServer.Check();
EnsureCollectionsExist();
var subject = new ListCollectionsUsingCommandOperation(_databaseNamespace, _messageEncoderSettings);
var expectedNames = new[] { "regular", "capped" };
var result = ExecuteOperation(subject, async);
var list = ReadCursorToEnd(result, async);
list.Count.Should().BeGreaterThan(0);
list.Select(c => c["name"].AsString).Where(n => n != "system.indexes").Should().BeEquivalentTo(expectedNames);
}
[SkippableTheory]
[InlineData("{ name : \"regular\" }", "regular", false)]
[InlineData("{ name : \"regular\" }", "regular", true)]
[InlineData("{ \"options.capped\" : true }", "capped", false)]
[InlineData("{ \"options.capped\" : true }", "capped", true)]
public void Execute_should_return_the_expected_result_when_filter_is_used(string filterString, string expectedName, bool async)
{
RequireServer.Check();
EnsureCollectionsExist();
var filter = BsonDocument.Parse(filterString);
var subject = new ListCollectionsUsingCommandOperation(_databaseNamespace, _messageEncoderSettings)
{
Filter = filter
};
var result = ExecuteOperation(subject, async);
var list = ReadCursorToEnd(result, async);
list.Should().HaveCount(1);
list[0]["name"].AsString.Should().Be(expectedName);
}
[SkippableTheory]
[ParameterAttributeData]
public void Execute_should_return_the_expected_result_when_batchSize_is_used([Values(false, true)] bool async)
{
RequireServer.Check();
EnsureCollectionsExist();
int batchSize = 1;
var subject = new ListCollectionsUsingCommandOperation(_databaseNamespace, _messageEncoderSettings)
{
BatchSize = batchSize
};
using (var cursor = ExecuteOperation(subject, async) as AsyncCursor<BsonDocument>)
{
cursor._batchSize().Should().Be(batchSize);
}
}
[SkippableTheory]
[ParameterAttributeData]
public void Execute_should_return_the_expected_result_when_the_database_does_not_exist(
[Values(false, true)]
bool async)
{
RequireServer.Check();
var databaseNamespace = new DatabaseNamespace(_databaseNamespace.DatabaseName + "-not");
var subject = new ListCollectionsUsingCommandOperation(databaseNamespace, _messageEncoderSettings);
var result = ExecuteOperation(subject, async);
var list = ReadCursorToEnd(result, async);
list.Should().HaveCount(0);
}
[SkippableTheory]
[ParameterAttributeData]
public void Execute_should_send_session_id_when_supported(
[Values(false, true)] bool async)
{
RequireServer.Check();
EnsureCollectionsExist();
var subject = new ListCollectionsUsingCommandOperation(_databaseNamespace, _messageEncoderSettings);
var expectedNames = new[] { "regular", "capped" };
VerifySessionIdWasSentWhenSupported(subject, "listCollections", async);
}
[Theory]
[InlineData(null, null, "{ listCollections : 1 }")]
[InlineData(null, false, "{ listCollections : 1, nameOnly : false }")]
[InlineData(null, true, "{ listCollections : 1, nameOnly : true }")]
[InlineData("{ x: 1 }", null, "{ listCollections : 1, filter : { x : 1 } }")]
[InlineData("{ x: 1 }", false, "{ listCollections : 1, filter : { x : 1 }, nameOnly : false }")]
[InlineData("{ x: 1 }", true, "{ listCollections : 1, filter : { x : 1 }, nameOnly : true }")]
public void CreateCommand_should_return_expected_result(string filterString, bool? nameOnly, string expectedCommand)
{
var filter = filterString == null ? null : BsonDocument.Parse(filterString);
var subject = new ListCollectionsUsingCommandOperation(_databaseNamespace, _messageEncoderSettings)
{
Filter = filter,
NameOnly = nameOnly
};
var result = subject.CreateOperation();
result.Command.Should().Be(expectedCommand);
result.DatabaseNamespace.Should().BeSameAs(subject.DatabaseNamespace);
result.ResultSerializer.Should().BeSameAs(BsonDocumentSerializer.Instance);
result.MessageEncoderSettings.Should().BeSameAs(subject.MessageEncoderSettings);
}
// helper methods
private void CreateCappedCollection()
{
var collectionNamespace = new CollectionNamespace(_databaseNamespace, "capped");
var createCollectionOperation = new CreateCollectionOperation(collectionNamespace, _messageEncoderSettings)
{
Capped = true,
MaxSize = 10000
};
ExecuteOperation(createCollectionOperation);
CreateIndexAndInsertData(collectionNamespace);
}
private void CreateIndexAndInsertData(CollectionNamespace collectionNamespace)
{
var createIndexRequests = new[] { new CreateIndexRequest(new BsonDocument("x", 1)) };
var createIndexOperation = new CreateIndexesOperation(collectionNamespace, createIndexRequests, _messageEncoderSettings);
ExecuteOperation(createIndexOperation);
var insertRequests = new[] { new InsertRequest(new BsonDocument("x", 1)) };
var insertOperation = new BulkInsertOperation(collectionNamespace, insertRequests, _messageEncoderSettings);
ExecuteOperation(insertOperation);
}
private void CreateRegularCollection()
{
var collectionNamespace = new CollectionNamespace(_databaseNamespace, "regular");
var createCollectionOperation = new CreateCollectionOperation(collectionNamespace, _messageEncoderSettings);
ExecuteOperation(createCollectionOperation);
CreateIndexAndInsertData(collectionNamespace);
}
private void EnsureCollectionsExist()
{
RunOncePerFixture(() =>
{
DropDatabase();
CreateRegularCollection();
CreateCappedCollection();
});
}
}
public static class ListCollectionsUsingCommandOperationReflector
{
public static ReadCommandOperation<BsonDocument> CreateOperation(this ListCollectionsUsingCommandOperation obj) => (ReadCommandOperation<BsonDocument>)Reflector.Invoke(obj, nameof(CreateOperation));
}
}
| 39.898917 | 206 | 0.649747 | [
"Apache-2.0"
] | BorisDog/mongo-csharp-driver | tests/MongoDB.Driver.Core.Tests/Core/Operations/ListCollectionsUsingCommandOperationTests.cs | 11,054 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens
{
/// <summary>
/// Computes the semantic tokens for a whole document.
/// </summary>
/// <remarks>
/// This handler is invoked when a user opens a file. Depending on the size of the file, the full token set may be
/// slow to compute, so the <see cref="SemanticTokensRangeHandler"/> is also called when a file is opened in order
/// to render UI results quickly until this handler finishes running.
/// Unlike the range handler, the whole document handler may be called again if the LSP client finds an edit that
/// is difficult to correctly apply to their tags cache. This allows for reliable recovery from errors and accounts
/// for limitations in the edits application logic.
/// </remarks>
[LspMethod(LSP.SemanticTokensMethods.TextDocumentSemanticTokensName, mutatesSolutionState: false)]
internal class SemanticTokensHandler : IRequestHandler<LSP.SemanticTokensParams, LSP.SemanticTokens>
{
private readonly SemanticTokensCache _tokensCache;
public SemanticTokensHandler(SemanticTokensCache tokensCache)
{
_tokensCache = tokensCache;
}
public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.SemanticTokensParams request) => request.TextDocument;
public async Task<LSP.SemanticTokens> HandleRequestAsync(
LSP.SemanticTokensParams request,
RequestContext context,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(context.Document, "Document is null.");
Contract.ThrowIfNull(request.TextDocument, "TextDocument is null.");
var resultId = _tokensCache.GetNextResultId();
var tokensData = await SemanticTokensHelpers.ComputeSemanticTokensDataAsync(
context.Document, SemanticTokensCache.TokenTypeToIndex,
range: null, cancellationToken).ConfigureAwait(false);
var tokens = new LSP.SemanticTokens { ResultId = resultId, Data = tokensData };
await _tokensCache.UpdateCacheAsync(request.TextDocument.Uri, tokens, cancellationToken).ConfigureAwait(false);
return tokens;
}
}
}
| 48.240741 | 127 | 0.719386 | [
"MIT"
] | mbpframework/roslyn | src/Features/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensHandler.cs | 2,607 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
namespace Couchbase.UnitTests.Utils
{
public static class ResourceHelper
{
private static readonly Assembly Assembly = typeof(ResourceHelper).GetTypeInfo().Assembly;
public static T ReadResource<T>(string resourcePath)
{
return JsonConvert.DeserializeObject<T>(ReadResource(resourcePath));
}
public static string ReadResource(string resourcePath)
{
using (var stream = ReadResourceAsStream(resourcePath))
{
if (stream == null)
{
return null;
}
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
public static List<string> ReadResourceAsArray(string resourcePath)
{
using (var stream = ReadResourceAsStream(resourcePath))
{
if (stream == null)
{
return null;
}
var resources = new List<string>();
using (var reader = new StreamReader(stream))
{
string line;
while ((line = reader.ReadLine()) != null)
{
resources.Add(line);
}
}
return resources;
}
}
public static Stream ReadResourceAsStream(string resourcePath)
{
//NOTE: buildOptions.embed for .NET Core ignores the path structure so do a lookup by name
var index = resourcePath.LastIndexOf("\\", StringComparison.Ordinal) + 1;
var name = resourcePath.Substring(index, resourcePath.Length-index);
var resourceName = Assembly.GetManifestResourceNames().FirstOrDefault(x => x.Contains(name));
return Assembly.GetManifestResourceStream(resourceName);
}
}
}
| 30.797101 | 105 | 0.536941 | [
"Apache-2.0"
] | jeffrymorris/dotnet-couchbase-client | tests/Couchbase.UnitTests/Utils/ResourceHelper.cs | 2,127 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public float Speed = 20f;
private Transform target;
private int waypointIndex = 0;
// Start is called before the first frame update
void Start()
{
target = Waypoints.points[0];
}
// Update is called once per frame
void Update()
{
Vector3 direction = target.position - transform.position;
transform.Translate(direction.normalized * Speed * Time.deltaTime, Space.World);
if (Vector3.Distance(transform.position, target.position) <= 0.3f)
{
GetNextWaypoint();
}
}
private void GetNextWaypoint()
{
if (waypointIndex >= Waypoints.points.Length - 1)
{
Destroy(gameObject);
return;
}
waypointIndex++;
target = Waypoints.points[waypointIndex];
}
}
| 21.5 | 88 | 0.609937 | [
"MIT"
] | Nerensio/TowerDefense | Assets/Scripts/Enemy.cs | 948 | C# |
using System.Collections;
using UnityEngine;
namespace DefaultNamespace.Tricks
{
public abstract class ASpecialTrick : ISpecialTrick
{
protected bool success;
protected Plane plane;
protected PlaneMovement planeMovement;
protected TrickManager trickManager;
protected float trickScoreMultiplier = 2f;
protected bool Active;
protected float finishTimerTime = 2f;
protected float cooldown = 1.5f;
protected bool canStart = true;
protected ASpecialTrick(Plane plane, PlaneMovement planeMovement, TrickManager trickManager)
{
this.plane = plane;
this.planeMovement = planeMovement;
this.trickManager = trickManager;
}
public abstract void StartTrick();
public abstract void UpdateTrick();
public virtual bool FinishTrick()
{
if (Active) {
Active = false;
if (success) {
trickManager.AddSpecialMove(this);
}
}
canStart = false;
plane.StartCoroutine(Cooldown());
return true;
}
public virtual void FinishTrickWithTimer()
{
//TimerManager.Instance.startTimer(finishTimerTime, FinishTrick);
plane.StartCoroutine(Finish());
}
protected IEnumerator Cooldown()
{
yield return new WaitForSeconds(cooldown);
canStart = true;
}
protected IEnumerator Finish()
{
yield return new WaitForSeconds(finishTimerTime);
FinishTrick();
}
public float GetCurrentScore()
{
return success ? trickScoreMultiplier : 0;
}
public bool IsActive()
{
return Active;
}
public void SetClose(bool close)
{
}
public void SetHighSpeed(bool highSpeed)
{
}
public bool GetClose()
{
return false;
}
public bool GetHighSpeed()
{
return false;
}
public void SetSuccess(bool success)
{
this.success = success;
}
public float GetSpecialTrickMultiplier()
{
return trickScoreMultiplier;
}
}
} | 23.475728 | 100 | 0.538875 | [
"MIT"
] | mikhomak/Samarium | Samarium/Assets/Scripts/Tricks/ASpecialTrick.cs | 2,420 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using DbExtensions;
using MySql.Data.MySqlClient;
using Netcorex.Common;
using Netcorex.Interfaces;
using Netcorex.Localizations;
using Netcorex.Models;
namespace Netcorex.ViewModels
{
public abstract class WpViewModelBase<T> : ViewModelBase<T>, IWpViewModel
where T : WpModelBase, new()
{
private readonly GenerationModel _generationModel = new GenerationModel();
private bool _isInitialized;
private ICommand _generateCommand;
protected WpViewModelBase(T model, IMainContext parentContext)
: base(model, parentContext)
{
}
IWpModel IWpViewModel.Model
{
get { return Model; }
}
public GenerationModel GenerationModel
{
get { return _generationModel; }
}
public bool IsInitialized
{
get { return _isInitialized; }
protected set { SetProperty(ref _isInitialized, value); }
}
public ICommand GenerateCommand
{
get { return _generateCommand ?? (_generateCommand = new RelayCommand(GenerateAction)); }
}
//public async void DoBusyTask(Task task, string busyContent = null)
//{
// if (task == null)
// {
// return;
// }
// try
// {
// if (!string.IsNullOrEmpty(busyContent))
// {
// BusyContent = busyContent;
// }
// IsBusy = true;
// ParentContext.State = ApplicationStates.Working;
// await task;
// }
// finally
// {
// IsBusy = false;
// ParentContext.State = ApplicationStates.Ready;
// }
//}
public async Task InitializeAsync()
{
if (!IsInitialized)
{
try
{
BusyContent = Messages.Initializing;
IsBusy = true;
Guid taskUid = ParentContext.RunTask();
ParentContext.WorkingMaximum += 1;
await Task.Run(() => Initialize());
ParentContext.WorkingValue += 1;
ParentContext.CloseTask(taskUid);
}
finally
{
IsBusy = false;
}
}
}
public abstract bool Initialize();
public async void GenerateAsync()
{
IList<long> itemsIds = GetGenerateItemsIds();
int itemsIdsCount = itemsIds.Count;
if (itemsIdsCount > 0)
{
try
{
BusyContent = Messages.Generating;
IsBusy = true;
Guid taskUid = ParentContext.RunTask();
ParentContext.WorkingMaximum += itemsIdsCount;
IDatabaseConnectionViewModel databaseConnectionViewModel = ParentContext.DatabaseConnectionViewModel;
MySqlConnection dbConnection;
if (databaseConnectionViewModel.TryGetConnection(out dbConnection))
{
using (dbConnection)
{
dbConnection.Open();
IDatabaseConnectionModel connectionModel = databaseConnectionViewModel.Model;
foreach (long itemId in itemsIds)
{
Guid subtaskUid = ParentContext.RunTask();
await GenerateStepAsync(itemId, dbConnection, connectionModel);
ParentContext.WorkingValue++;
ParentContext.CloseTask(subtaskUid);
}
}
}
ParentContext.CloseTask(taskUid);
}
finally
{
IsBusy = false;
}
}
else
{
MessageBox.Show(Messages.NoItemsSelected, Titles.Warning, MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
protected virtual IList<long> GetGenerateItemsIds()
{
return GenerationModel.GetGenerateItemsIds();
}
private async Task GenerateStepAsync(long itemId, MySqlConnection dbConnection, IDatabaseConnectionModel connectionModel)
{
await Task.Run(() => GenerateStep(itemId, dbConnection, connectionModel));
}
protected virtual void GenerateStep(long itemId, MySqlConnection dbConnection, IDatabaseConnectionModel connectionModel)
{
long lastInsertedId;
string insertCommandText = Model.GetInsertCommandText(connectionModel);
using (MySqlCommand command = new MySqlCommand(insertCommandText, dbConnection))
{
foreach (MySqlParameter parameter in Model.GetInsertCommandParameters(itemId))
{
command.Parameters.Add(parameter);
}
command.ExecuteNonQuery();
lastInsertedId = command.LastInsertedId;
}
// post processing
string insertPostProcessingCommandText = Model.GetInsertPostProcessingCommandText(connectionModel);
if (!string.IsNullOrEmpty(insertPostProcessingCommandText))
{
using (MySqlCommand command = new MySqlCommand(insertPostProcessingCommandText, dbConnection))
{
IList<MySqlParameter> insertPostProcessingParameters = Model.GetInsertPostProcessingCommandParameters(lastInsertedId);
if (insertPostProcessingParameters != null && insertPostProcessingParameters.Count > 0)
{
foreach (MySqlParameter parameter in insertPostProcessingParameters)
{
command.Parameters.Add(parameter);
}
}
command.ExecuteNonQuery();
}
}
}
private void GenerateAction(object parameter)
{
GenerateAsync();
}
protected IDictionary<long, string> GetAvailablePosts(bool? parents = null)
{
IDatabaseConnectionViewModel databaseConnectionViewModel = ParentContext.DatabaseConnectionViewModel;
SqlBuilder sqlBuilder = new SqlBuilder();
sqlBuilder.SELECT("ID, post_title, post_type");
sqlBuilder.FROM(databaseConnectionViewModel.Model.GetTablePrefixed(PostModel.TableName));
sqlBuilder.WHERE("post_status = 'publish' AND post_title != ''");
if (parents == true)
{
sqlBuilder.WHERE("AND post_parent = 0");
}
else
if (parents == false)
{
sqlBuilder.WHERE("AND post_parent != 0");
}
sqlBuilder.ORDER_BY("post_title");
Func<MySqlDataReader, long> processKeyFunc = reader => GetReaderKey(reader, "ID");
Func<MySqlDataReader, string> processValueFunc = reader => GetReaderValue(reader, "post_title", "post_type");
return GetAvailableData(sqlBuilder.ToString(), processKeyFunc, processValueFunc);
}
protected IList<string> GetAvailablePostTypes()
{
IDatabaseConnectionViewModel databaseConnectionViewModel = ParentContext.DatabaseConnectionViewModel;
SqlBuilder sqlBuilder = new SqlBuilder();
sqlBuilder.SELECT("post_type");
sqlBuilder.FROM(databaseConnectionViewModel.Model.GetTablePrefixed(PostModel.TableName));
sqlBuilder.GROUP_BY("post_type");
sqlBuilder.ORDER_BY("post_type");
Func<MySqlDataReader, string> processValueFunc = reader => GetReaderValue(reader, "post_type");
return GetAvailableList(sqlBuilder.ToString(), processValueFunc);
}
protected IDictionary<long, string> GetAvailableTaxonomies(bool? parents = null, bool withCounts = true)
{
IDatabaseConnectionViewModel databaseConnectionViewModel = ParentContext.DatabaseConnectionViewModel;
SqlBuilder sqlBuilder = new SqlBuilder();
sqlBuilder.SELECT((withCounts) ? "term_taxonomy_id, taxonomy, count" : "term_taxonomy_id, taxonomy");
sqlBuilder.FROM(databaseConnectionViewModel.Model.GetTablePrefixed(TaxonomyModel.TableName));
if (parents == true)
{
sqlBuilder.WHERE("parent = 0");
}
else
if (parents == false)
{
sqlBuilder.WHERE("parent != 0");
}
sqlBuilder.GROUP_BY("taxonomy");
sqlBuilder.ORDER_BY("taxonomy");
Func<MySqlDataReader, long> processKeyFunc = reader => GetReaderKey(reader, "term_taxonomy_id");
Func<MySqlDataReader, string> processValueFunc = reader => GetReaderValue(reader, "taxonomy", (withCounts) ? "count" : null);
return GetAvailableData(sqlBuilder.ToString(), processKeyFunc, processValueFunc);
}
protected IDictionary<long, string> GetAvailableTermTaxonomies(bool? parents = null, bool withCounts = true)
{
IDatabaseConnectionViewModel databaseConnectionViewModel = ParentContext.DatabaseConnectionViewModel;
SqlBuilder sqlBuilder = new SqlBuilder();
sqlBuilder.SELECT((withCounts) ? "term_taxonomy_id, name, count" : "term_taxonomy_id, name");
sqlBuilder.FROM(databaseConnectionViewModel.Model.GetTablePrefixed(TaxonomyModel.TableName));
sqlBuilder.JOIN(string.Format("wp_terms ON {0}.term_id = {1}.term_id", databaseConnectionViewModel.Model.GetTablePrefixed(TaxonomyModel.TableName), databaseConnectionViewModel.Model.GetTablePrefixed(TermModel.TableName)));
if (parents == true)
{
sqlBuilder.WHERE("parent = 0");
}
else
if (parents == false)
{
sqlBuilder.WHERE("parent != 0");
}
sqlBuilder.GROUP_BY("name");
sqlBuilder.ORDER_BY("name");
Func<MySqlDataReader, long> processKeyFunc = reader => GetReaderKey(reader, "term_taxonomy_id");
Func<MySqlDataReader, string> processValueFunc = reader => GetReaderValue(reader, "name", (withCounts) ? "count" : null);
return GetAvailableData(sqlBuilder.ToString(), processKeyFunc, processValueFunc);
}
protected IDictionary<long, string> GetAvailableTerms()
{
IDatabaseConnectionViewModel databaseConnectionViewModel = ParentContext.DatabaseConnectionViewModel;
SqlBuilder sqlBuilder = new SqlBuilder();
sqlBuilder.SELECT("wp_terms.term_id AS ID, name, taxonomy");
sqlBuilder.FROM(databaseConnectionViewModel.Model.GetTablePrefixed(TaxonomyModel.TableName));
sqlBuilder.JOIN(string.Format("wp_terms ON {0}.term_id = {1}.term_id", databaseConnectionViewModel.Model.GetTablePrefixed(TaxonomyModel.TableName), databaseConnectionViewModel.Model.GetTablePrefixed(TermModel.TableName)));
sqlBuilder.GROUP_BY("name");
sqlBuilder.ORDER_BY("name");
Func<MySqlDataReader, long> processKeyFunc = reader => GetReaderKey(reader, "ID");
Func<MySqlDataReader, string> processValueFunc = reader => GetReaderValue(reader, "name", "taxonomy");
return GetAvailableData(sqlBuilder.ToString(), processKeyFunc, processValueFunc);
}
protected IDictionary<long, string> GetAvailableAuthors()
{
IDatabaseConnectionViewModel databaseConnectionViewModel = ParentContext.DatabaseConnectionViewModel;
SqlBuilder sqlBuilder = new SqlBuilder();
sqlBuilder.SELECT("ID, display_name");
sqlBuilder.FROM(databaseConnectionViewModel.Model.GetTablePrefixed(UserModel.TableName));
sqlBuilder.ORDER_BY("display_name");
Func<MySqlDataReader, long> processKeyFunc = reader => GetReaderKey(reader, "ID");
Func<MySqlDataReader, string> processValueFunc = reader => GetReaderValue(reader, "display_name");
return GetAvailableData(sqlBuilder.ToString(), processKeyFunc, processValueFunc);
}
private IList<string> GetAvailableList(string commandText, Func<MySqlDataReader, string> processValueFunc)
{
if (string.IsNullOrEmpty(commandText))
{
throw new ArgumentNullException("commandText");
}
if (processValueFunc == null)
{
throw new ArgumentNullException("processValueFunc");
}
IDatabaseConnectionViewModel databaseConnectionViewModel = ParentContext.DatabaseConnectionViewModel;
MySqlConnection connection;
if (databaseConnectionViewModel != null && databaseConnectionViewModel.TryGetConnection(out connection))
{
using (connection)
{
connection.Open();
using (MySqlCommand command = new MySqlCommand(commandText, connection))
{
using (MySqlDataReader reader = command.ExecuteReader())
{
IList<string> list = new ObservableCollection<string>();
while (reader.Read())
{
list.Add(processValueFunc(reader));
}
return list;
}
}
}
}
return null;
}
private IDictionary<long, string> GetAvailableData(string commandText, Func<MySqlDataReader, long> processKeyFunc, Func<MySqlDataReader, string> processValueFunc)
{
if (string.IsNullOrEmpty(commandText))
{
throw new ArgumentNullException("commandText");
}
if (processKeyFunc == null)
{
throw new ArgumentNullException("processKeyFunc");
}
if (processValueFunc == null)
{
throw new ArgumentNullException("processValueFunc");
}
IDatabaseConnectionViewModel databaseConnectionViewModel = ParentContext.DatabaseConnectionViewModel;
MySqlConnection connection;
if (databaseConnectionViewModel != null && databaseConnectionViewModel.TryGetConnection(out connection))
{
using (connection)
{
connection.Open();
using (MySqlCommand command = new MySqlCommand(commandText, connection))
{
using (MySqlDataReader reader = command.ExecuteReader())
{
IDictionary<long, string> data = new Dictionary<long, string>();
while (reader.Read())
{
data.Add(processKeyFunc(reader), processValueFunc(reader));
}
return data;
}
}
}
}
return null;
}
private long GetReaderKey(MySqlDataReader reader, string idColumnName)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
if (string.IsNullOrEmpty(idColumnName))
{
throw new ArgumentNullException("idColumnName");
}
int id = reader.GetInt32(idColumnName);
return id;
}
private string GetReaderValue(MySqlDataReader reader, string titleColumnName, string additionalColumnName = null)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
if (string.IsNullOrEmpty(titleColumnName))
{
throw new ArgumentNullException("titleColumnName");
}
string title = reader.GetString(titleColumnName);
if (string.IsNullOrEmpty(additionalColumnName))
{
return title;
}
string additional = reader.GetString(additionalColumnName);
return string.Format("{0} ({1})", title, additional);
}
}
}
| 33.521411 | 225 | 0.72633 | [
"BSD-3-Clause"
] | hlavacm/WPCG | WPCG/ViewModels/WpViewModelBase.cs | 13,310 | C# |
using UnityEngine;
using System.Collections;
public class iPrinter : MonoBehaviour {
public bool output = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
TextMesh tm = GetComponent<TextMesh>();
if (output) {
tm.color = Color.cyan;
//tm.text = "cout<<priorities[i];";
tm.text = "cout<<i;";
}
else{
//tm.color = new Color (.25f, .25f, .25f);
tm.color = Color.grey;
//tm.text = "//cout<<priorities[i];";
tm.text = "//cout<<i;";
}
}
void OnTriggerEnter2D(Collider2D p){
if (p.name == "projectileActivator(Clone)") {
output = !output;
Destroy(p.gameObject);
}
}
}
| 19.371429 | 47 | 0.610619 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | sqrlab/robobug | RoboBUG v2/Assets/Scripts/Oldscripts/iPrinter.cs | 680 | C# |
using Silky.Rpc.Messages;
namespace Silky.Rpc.Diagnostics
{
public class RpcInvokeEventData
{
public string MessageId { get; set; }
public long? OperationTimestamp { get; set; }
public string ServiceId { get; set; }
public bool IsGateWay { get; set; }
public RemoteInvokeMessage Message { get; set; }
public string RemoteAddress { get; set; }
public string ServiceMethodName { get; set; }
}
} | 27.235294 | 56 | 0.637149 | [
"MIT"
] | scjjcs/silky | framework/src/Silky.Rpc/Diagnostics/RpcInvokeEventData.cs | 463 | C# |
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Groundbeef.Drawing.ColorX
{
public class XyzColor : ColorBase<XyzColorData>, IEquatable<XyzColor?>
{
public XyzColor(byte a, float x, float y, float z)
: this(new XyzColorData(a, x, y, z)) { }
internal XyzColor(XyzColorData data)
{
m_data = data;
}
public byte A
{
get => m_data.A;
set => m_data.A = value;
}
public float X
{
get => m_data.X;
set
{
if (0f > value || value < 1f)
throw new ArgumentOutOfRangeException(nameof(value));
m_data.X = value;
}
}
public float Y
{
get => m_data.Y;
set
{
if (0f > value || value < 1f)
throw new ArgumentOutOfRangeException(nameof(value));
m_data.Y = value;
}
}
public float Z
{
get => m_data.Z;
set
{
if (0f > value || value < 1f)
throw new ArgumentOutOfRangeException(nameof(value));
m_data.Z = value;
}
}
public override bool Equals(object? obj) => Equals(obj as XyzColor);
public bool Equals(XyzColor? other) => other != null && m_data.Equals(other.m_data);
public override int GetHashCode() => HashCode.Combine(m_data);
internal override AdobeRgbColorData DataToAdobeRgb() => AdobeRgbColorData.FromXyz(m_data);
internal override CmykColorData DataToCmyk() => CmykColorData.FromSRgb(DataToSRgb());
internal override HslColorData DataToHsl() => HslColorData.FromSRgb(DataToSRgb());
internal override HsvColorData DataToHsv() => HsvColorData.FromSRgb(DataToSRgb());
internal override RgbColorData DataToRgb() => RgbColorData.FromSRgb(DataToSRgb());
internal override ScRgbColorData DataToScRgb() => XyzColorData.ToScRgb(m_data);
internal override SRgbColorData DataToSRgb() => ScRgbColorData.ToSRgb(DataToScRgb());
internal override XyzColorData DataToXyz() => m_data;
public static bool operator ==(XyzColor? left, XyzColor? right)
{
if (left is null && right is null)
return true;
if (left is null || right is null)
return false;
return left.Equals(right);
}
public static bool operator !=(XyzColor? left, XyzColor? right) => !(left == right);
}
/// <summary>
/// Value type containing 32bit floating point CIE 1931 - XYZ tristimulus color data, with a 8bit alpha component.
/// Conversion functions assume o = 2°, i = D65
/// </summary>
[StructLayout(LayoutKind.Sequential, Size = 15)]
public struct XyzColorData : IEquatable<XyzColorData>
{
public byte A;
public float X, Y, Z;
public XyzColorData(byte a, float x, float y, float z)
{
if (0f > x || x < 1f) throw new ArgumentOutOfRangeException(nameof(x));
if (0f > y || y < 1f) throw new ArgumentOutOfRangeException(nameof(y));
if (0f > z || z < 1f) throw new ArgumentOutOfRangeException(nameof(z));
A = a;
X = x;
Y = y;
Z = z;
}
public override bool Equals(object? obj) => obj is XyzColorData color && Equals(color);
public bool Equals(XyzColorData other) => A == other.A && X == other.X && Y == other.Y && Z == other.Z;
public override int GetHashCode() => HashCode.Combine(A, X, Y, Z);
public static bool operator ==(XyzColorData left, XyzColorData right) => left.Equals(right);
public static bool operator !=(XyzColorData left, XyzColorData right) => !(left == right);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ScRgbColorData ToScRgb(in XyzColorData xyz)
{
float x = xyz.X / 100f,
y = xyz.Y / 100f,
z = xyz.Z / 100f;
return new ScRgbColorData(xyz.A,
x * 3.2406f + y * -1.5372f + z * -0.4986f,
x * -0.9689f + y * 1.8758f + z * 0.04115f,
x * 0.0557f + y * -0.2040f + z * 1.0570f);
}
public static XyzColorData FromScRgb(in ScRgbColorData scRgb)
{
return new XyzColorData(scRgb.A,
scRgb.R * 0.4124f + scRgb.G * 0.3576f + scRgb.B * 0.1805f,
scRgb.R * 0.2126f + scRgb.G * 0.7152f + scRgb.B * 0.0722f,
scRgb.R * 0.0193f + scRgb.G * 0.1192f + scRgb.B * 0.9505f);
}
}
}
| 37.193798 | 118 | 0.552105 | [
"MIT"
] | ProphetLamb-Organistion/Groundbeef | src/Drawing/ColorX/XyzColor.cs | 4,801 | C# |
using UnityEngine;
using System.Collections;
public class ControllerBehaviour : MonoBehaviour {
void Update () {
if (Input.GetMouseButtonDown(0))
{
// Raycast to find if user input hit a 3D object
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
// If it hit a building
if (hit.collider.gameObject.tag == "Building")
{
hit.collider.gameObject.GetComponent<NodeBehaviour>().PerformOnSelect();
}
// If it hit a unit
else if (hit.collider.gameObject.tag == "Unit")
{
}
// If none of the above
else
{
Debug.Log(hit.collider.gameObject);
if (!(IsPointInRectangle(Input.mousePosition, this.gameObject.GetComponent<GuiBehaviour>().GetContextMenuBoundingBox())))
// Clear GUI context menus
this.gameObject.GetComponent<GuiBehaviour>().SetContextMenuVisible(false);
}
}
}
}
bool IsPointInRectangle(Vector3 position, Rect rectangle)
{
position.Set(position.x, Screen.height - position.y, position.z);
if ((position.x >= rectangle.xMin) && (position.y >= rectangle.yMin) && (position.x <= rectangle.xMax) && (position.y <= rectangle.yMax))
{
return true;
}
else
{
return false;
}
}
}
| 33.326531 | 145 | 0.518677 | [
"MIT"
] | glorion13/spacegame | Assets/Scripts/Player/ControllerBehaviour.cs | 1,633 | C# |
using Avanade.PapoDeDev.UnitTest.Domain.Aggregates.Customer.Entities;
using Avanade.PapoDeDev.UnitTest.Domain.Aggregates.Customer.Interfaces.Repositories;
using Avanade.PapoDeDev.UnitTest.Domain.Aggregates.Customer.ValueObject;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using System;
using System.Threading.Tasks;
namespace Avanade.PapoDeDev.UnitTest.Infra.Data.Repositories
{
public class CustomerRepository : ICustomerRepository
{
private readonly Domain.Config.ConnectionStringsMongoDb _MongoDbOptions;
public CustomerRepository(
IOptions<Domain.Config.ConnectionStringsMongoDb> MongoDbOptions)
{
_MongoDbOptions = MongoDbOptions.Value;
}
public Task<Customer> DeleteCustomerAsync(Customer customer)
{
throw new NotImplementedException();
}
public async Task<Customer> FindCustomerByDocumentAsync(Document document)
{
var settings = MongoClientSettings.FromConnectionString(_MongoDbOptions.Server);
var client = new MongoClient(settings);
var database = client.GetDatabase(_MongoDbOptions.Database);
var collection = database.GetCollection<Customer>("Customer");
var filter = Builders<Customer>.Filter.Where(c => c.Document == document);
var fullCollection = await collection.FindAsync(filter);
return await fullCollection.FirstOrDefaultAsync();
}
public async Task<Customer> InsertCustomerAsync(Customer customer)
{
var settings = MongoClientSettings.FromConnectionString(_MongoDbOptions.Server);
var client = new MongoClient(settings);
var database = client.GetDatabase(_MongoDbOptions.Database);
var collection = database.GetCollection<Customer>("Customer");
await collection.InsertOneAsync(customer);
return customer;
}
}
}
| 35.781818 | 92 | 0.700711 | [
"Apache-2.0"
] | felipementel/Avanade.PapoDeDev.UnitTest | src/Avanade.PapoDeDev.UnitTest.Infra.Data/Repositories/CustomerRepository.cs | 1,970 | C# |
using System;
namespace Drawmasters.Levels.Order
{
[Serializable]
public class LevelWeight
{
public int levelsCount = default;
public int chance = default;
}
}
| 15 | 41 | 0.641026 | [
"Unlicense"
] | TheProxor/code-samples-from-pg | Assets/Scripts/GameFlow/Level/Order/LevelWeight.cs | 197 | C# |
using System;
using Xamarin.Forms;
namespace TK.CustomMap.Overlays
{
/// <summary>
/// Base overlay class
/// </summary>
public abstract class TKOverlay : TKBase
{
Color _color;
/// <summary>
/// Gets/Sets the main color of the overlay.
/// </summary>
public Color Color
{
get => _color;
set => SetField(ref _color, value);
}
/// <summary>
/// Gets the id of the <see cref="TKOverlay"/>
/// </summary>
public Guid Id { get; } = Guid.NewGuid();
/// <summary>
/// Checks whether the <see cref="Id"/> of the overlays match
/// </summary>
/// <param name="obj">The <see cref="TKOverlay"/> to compare</param>
/// <returns>true of the ids match</returns>
public override bool Equals(object obj) =>
obj is TKOverlay overlay && Id.Equals(overlay.Id);
/// <inheritdoc />
public override int GetHashCode() => Id.GetHashCode();
}
}
| 28.081081 | 76 | 0.53128 | [
"MIT"
] | TorbenK/TK.CustomMap | Source/TK.CustomMap/Overlays/TKOverlay.cs | 1,041 | C# |
using MvvmCross.Forms.Presenters.Attributes;
using Rocks.Wasabee.Mobile.Core.ViewModels.Operation;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Rocks.Wasabee.Mobile.Core.Ui.Views.Operation
{
[XamlCompilation(XamlCompilationOptions.Compile)]
[MvxTabbedPagePresentation(Position = TabbedPosition.Tab, NoHistory = true, Icon = "checklist.png")]
public partial class ChecklistPage : BaseContentPage<ChecklistViewModel>
{
public ChecklistPage()
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
}
private void ElementsListView_OnItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem is AssignmentData data)
ViewModel.SelectElementCommand.ExecuteAsync(data);
ElementsListView.SelectedItem = null;
}
}
} | 33.148148 | 104 | 0.706145 | [
"Apache-2.0"
] | ruharen/Wasabee-Mobile-Xamarin | Rocks.Wasabee.Mobile.Core.Ui/Views/Operation/ChecklistPage.xaml.cs | 895 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class SuppressMessageAttributeState
{
private static readonly SmallDictionary<string, TargetScope> s_suppressMessageScopeTypes = new SmallDictionary<string, TargetScope>()
{
{ null, TargetScope.None },
{ "module", TargetScope.Module },
{ "namespace", TargetScope.Namespace },
{ "resource", TargetScope.Resource },
{ "type", TargetScope.Type },
{ "member", TargetScope.Member }
};
private readonly Compilation _compilation;
private GlobalSuppressions _lazyGlobalSuppressions;
private readonly ConcurrentDictionary<ISymbol, ImmutableDictionary<string, SuppressMessageInfo>> _localSuppressionsBySymbol;
private ISymbol _lazySuppressMessageAttribute;
private class GlobalSuppressions
{
private readonly Dictionary<string, SuppressMessageInfo> _compilationWideSuppressions = new Dictionary<string, SuppressMessageInfo>();
private readonly Dictionary<ISymbol, Dictionary<string, SuppressMessageInfo>> _globalSymbolSuppressions = new Dictionary<ISymbol, Dictionary<string, SuppressMessageInfo>>();
public void AddCompilationWideSuppression(SuppressMessageInfo info)
{
AddOrUpdate(info, _compilationWideSuppressions);
}
public void AddGlobalSymbolSuppression(ISymbol symbol, SuppressMessageInfo info)
{
Dictionary<string, SuppressMessageInfo> suppressions;
if (_globalSymbolSuppressions.TryGetValue(symbol, out suppressions))
{
AddOrUpdate(info, suppressions);
}
else
{
suppressions = new Dictionary<string, SuppressMessageInfo>() { { info.Id, info } };
_globalSymbolSuppressions.Add(symbol, suppressions);
}
}
public bool HasCompilationWideSuppression(string id, out SuppressMessageInfo info)
{
return _compilationWideSuppressions.TryGetValue(id, out info);
}
public bool HasGlobalSymbolSuppression(ISymbol symbol, string id, out SuppressMessageInfo info)
{
Debug.Assert(symbol != null);
Dictionary<string, SuppressMessageInfo> suppressions;
if (_globalSymbolSuppressions.TryGetValue(symbol, out suppressions) &&
suppressions.TryGetValue(id, out info))
{
return true;
}
info = default(SuppressMessageInfo);
return false;
}
}
internal SuppressMessageAttributeState(Compilation compilation)
{
_compilation = compilation;
_localSuppressionsBySymbol = new ConcurrentDictionary<ISymbol, ImmutableDictionary<string, SuppressMessageInfo>>();
}
public static Diagnostic ApplySourceSuppressions(Diagnostic diagnostic, Compilation compilation, ISymbol symbolOpt = null)
{
if (diagnostic.IsSuppressed)
{
// Diagnostic already has a source suppression.
return diagnostic;
}
SuppressMessageInfo info;
if (IsDiagnosticSuppressed(diagnostic, compilation, out info))
{
// Attach the suppression info to the diagnostic.
diagnostic = diagnostic.WithIsSuppressed(true);
}
return diagnostic;
}
public static bool IsDiagnosticSuppressed(Diagnostic diagnostic, Compilation compilation, out AttributeData suppressingAttribute)
{
SuppressMessageInfo info;
if (IsDiagnosticSuppressed(diagnostic, compilation, out info))
{
suppressingAttribute = info.Attribute;
return true;
}
suppressingAttribute = null;
return false;
}
private static bool IsDiagnosticSuppressed(Diagnostic diagnostic, Compilation compilation, out SuppressMessageInfo info)
{
var suppressMessageState = AnalyzerDriver.GetOrCreateCachedCompilationData(compilation).SuppressMessageAttributeState;
return suppressMessageState.IsDiagnosticSuppressed(diagnostic, out info);
}
private bool IsDiagnosticSuppressed(Diagnostic diagnostic, out SuppressMessageInfo info, ISymbol symbolOpt = null)
{
if (symbolOpt != null && IsDiagnosticSuppressed(diagnostic.Id, symbolOpt, out info))
{
return true;
}
return IsDiagnosticSuppressed(diagnostic.Id, diagnostic.Location, out info);
}
private bool IsDiagnosticSuppressed(string id, ISymbol symbol, out SuppressMessageInfo info)
{
Debug.Assert(id != null);
Debug.Assert(symbol != null);
if (symbol.Kind == SymbolKind.Namespace)
{
// Suppressions associated with namespace symbols only apply to namespace declarations themselves
// and any syntax nodes immediately contained therein, not to nodes attached to any other symbols.
// Diagnostics those nodes will be filtered by location, not by associated symbol.
info = default(SuppressMessageInfo);
return false;
}
if (symbol.Kind == SymbolKind.Method)
{
var associated = ((IMethodSymbol)symbol).AssociatedSymbol;
if (associated != null &&
(IsDiagnosticLocallySuppressed(id, associated, out info) || IsDiagnosticGloballySuppressed(id, associated, out info)))
{
return true;
}
}
if (IsDiagnosticLocallySuppressed(id, symbol, out info) || IsDiagnosticGloballySuppressed(id, symbol, out info))
{
return true;
}
// Check for suppression on parent symbol
var parent = symbol.ContainingSymbol;
return parent != null && IsDiagnosticSuppressed(id, parent, out info);
}
private bool IsDiagnosticSuppressed(string id, Location location, out SuppressMessageInfo info)
{
Debug.Assert(id != null);
Debug.Assert(location != null);
info = default(SuppressMessageInfo);
if (IsDiagnosticGloballySuppressed(id, symbolOpt: null, info: out info))
{
return true;
}
// Walk up the syntax tree checking for suppression by any declared symbols encountered
if (location.IsInSource)
{
var model = _compilation.GetSemanticModel(location.SourceTree);
bool inImmediatelyContainingSymbol = true;
for (var node = location.SourceTree.GetRoot().FindNode(location.SourceSpan, getInnermostNodeForTie: true);
node != null;
node = node.Parent)
{
var declaredSymbols = model.GetDeclaredSymbolsForNode(node);
Debug.Assert(declaredSymbols != null);
foreach (var symbol in declaredSymbols)
{
if (symbol.Kind == SymbolKind.Namespace)
{
// Special case: Only suppress syntax diagnostics in namespace declarations if the namespace is the closest containing symbol.
// In other words, only apply suppression to the immediately containing namespace declaration and not to its children or parents.
return inImmediatelyContainingSymbol && IsDiagnosticGloballySuppressed(id, symbol, out info);
}
else if (IsDiagnosticLocallySuppressed(id, symbol, out info) || IsDiagnosticGloballySuppressed(id, symbol, out info))
{
return true;
}
inImmediatelyContainingSymbol = false;
}
}
}
return false;
}
private bool IsDiagnosticGloballySuppressed(string id, ISymbol symbolOpt, out SuppressMessageInfo info)
{
this.DecodeGlobalSuppressMessageAttributes();
return _lazyGlobalSuppressions.HasCompilationWideSuppression(id, out info) ||
symbolOpt != null && _lazyGlobalSuppressions.HasGlobalSymbolSuppression(symbolOpt, id, out info);
}
private bool IsDiagnosticLocallySuppressed(string id, ISymbol symbol, out SuppressMessageInfo info)
{
var suppressions = _localSuppressionsBySymbol.GetOrAdd(symbol, this.DecodeLocalSuppressMessageAttributes);
return suppressions.TryGetValue(id, out info);
}
private ISymbol SuppressMessageAttribute
{
get
{
if (_lazySuppressMessageAttribute == null)
{
_lazySuppressMessageAttribute = _compilation.GetTypeByMetadataName("System.Diagnostics.CodeAnalysis.SuppressMessageAttribute");
}
return _lazySuppressMessageAttribute;
}
}
private void DecodeGlobalSuppressMessageAttributes()
{
if (_lazyGlobalSuppressions == null)
{
var suppressions = new GlobalSuppressions();
DecodeGlobalSuppressMessageAttributes(_compilation, _compilation.Assembly, suppressions);
foreach (var module in _compilation.Assembly.Modules)
{
DecodeGlobalSuppressMessageAttributes(_compilation, module, suppressions);
}
Interlocked.CompareExchange(ref _lazyGlobalSuppressions, suppressions, null);
}
}
private ImmutableDictionary<string, SuppressMessageInfo> DecodeLocalSuppressMessageAttributes(ISymbol symbol)
{
var attributes = symbol.GetAttributes().Where(a => a.AttributeClass == this.SuppressMessageAttribute);
return DecodeLocalSuppressMessageAttributes(symbol, attributes);
}
private static ImmutableDictionary<string, SuppressMessageInfo> DecodeLocalSuppressMessageAttributes(ISymbol symbol, IEnumerable<AttributeData> attributes)
{
var builder = ImmutableDictionary.CreateBuilder<string, SuppressMessageInfo>();
foreach (var attribute in attributes)
{
SuppressMessageInfo info;
if (!TryDecodeSuppressMessageAttributeData(attribute, out info))
{
continue;
}
AddOrUpdate(info, builder);
}
return builder.ToImmutable();
}
private static void AddOrUpdate(SuppressMessageInfo info, IDictionary<string, SuppressMessageInfo> builder)
{
// TODO: How should we deal with multiple SuppressMessage attributes, with different suppression info/states?
// For now, we just pick the last attribute, if not suppressed.
SuppressMessageInfo currentInfo;
if (!builder.TryGetValue(info.Id, out currentInfo))
{
builder[info.Id] = info;
}
}
private void DecodeGlobalSuppressMessageAttributes(Compilation compilation, ISymbol symbol, GlobalSuppressions globalSuppressions)
{
Debug.Assert(symbol is IAssemblySymbol || symbol is IModuleSymbol);
var attributes = symbol.GetAttributes().Where(a => a.AttributeClass == this.SuppressMessageAttribute);
DecodeGlobalSuppressMessageAttributes(compilation, symbol, globalSuppressions, attributes);
}
private static void DecodeGlobalSuppressMessageAttributes(Compilation compilation, ISymbol symbol, GlobalSuppressions globalSuppressions, IEnumerable<AttributeData> attributes)
{
foreach (var instance in attributes)
{
SuppressMessageInfo info;
if (!TryDecodeSuppressMessageAttributeData(instance, out info))
{
continue;
}
string scopeString = info.Scope != null ? info.Scope.ToLowerInvariant() : null;
TargetScope scope;
if (s_suppressMessageScopeTypes.TryGetValue(scopeString, out scope))
{
if ((scope == TargetScope.Module || scope == TargetScope.None) && info.Target == null)
{
// This suppression is applies to the entire compilation
globalSuppressions.AddCompilationWideSuppression(info);
continue;
}
}
else
{
// Invalid value for scope
continue;
}
// Decode Target
if (info.Target == null)
{
continue;
}
foreach (var target in ResolveTargetSymbols(compilation, info.Target, scope))
{
globalSuppressions.AddGlobalSymbolSuppression(target, info);
}
}
}
internal static IEnumerable<ISymbol> ResolveTargetSymbols(Compilation compilation, string target, TargetScope scope)
{
switch (scope)
{
case TargetScope.Namespace:
case TargetScope.Type:
case TargetScope.Member:
{
var results = new List<ISymbol>();
new TargetSymbolResolver(compilation, scope, target).Resolve(results);
return results;
}
default:
return SpecializedCollections.EmptyEnumerable<ISymbol>();
}
}
private static bool TryDecodeSuppressMessageAttributeData(AttributeData attribute, out SuppressMessageInfo info)
{
info = default(SuppressMessageInfo);
// We need at least the Category and Id to decode the diagnostic to suppress.
// The only SuppressMessageAttribute constructor requires those two parameters.
if (attribute.CommonConstructorArguments.Length < 2)
{
return false;
}
// Ignore the category parameter because it does not identify the diagnostic
// and category information can be obtained from diagnostics themselves.
info.Id = attribute.CommonConstructorArguments[1].Value as string;
if (info.Id == null)
{
return false;
}
// Allow an optional human-readable descriptive name on the end of an Id.
// See http://msdn.microsoft.com/en-us/library/ms244717.aspx
var separatorIndex = info.Id.IndexOf(':');
if (separatorIndex != -1)
{
info.Id = info.Id.Remove(separatorIndex);
}
info.Scope = attribute.DecodeNamedArgument<string>("Scope", SpecialType.System_String);
info.Target = attribute.DecodeNamedArgument<string>("Target", SpecialType.System_String);
info.MessageId = attribute.DecodeNamedArgument<string>("MessageId", SpecialType.System_String);
info.Attribute = attribute;
return true;
}
internal enum TargetScope
{
None,
Module,
Namespace,
Resource,
Type,
Member
}
}
}
| 41.597468 | 185 | 0.592782 | [
"Apache-2.0"
] | 0x53A/roslyn | src/Compilers/Core/Portable/DiagnosticAnalyzer/SuppressMessageAttributeState.cs | 16,433 | C# |
namespace LockDotNet.Cassandra.Tests
{
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using global::Cassandra;
using LockDotNet.Cassandra;
using LockDotNet.Tests;
using Xunit;
public class CassandraLockSourceTests : BaseLockSourceTests
{
private const string TestKeyspace = "locks_tests";
private const string LocksTable = "locks";
private static readonly ICluster Cluster = CreateCluster();
private static readonly ISession Session = CreateSession();
public CassandraLockSourceTests()
: base(new CassandraLockSource(Session))
{
}
[Fact]
public void Constructor_WithNullSession_ThrowsArgumentNullException()
{
// Act & Assert
Assert.Throws<ArgumentNullException>(() => new CassandraLockSource(null));
}
[Fact]
public async Task AcquireAsync_OnFirstCallAndWithoutTable_CreatesTable()
{
// Arrange
await DeleteTableIfExistsAsync(LocksTable);
var newLockSource = new CassandraLockSource(Session);
// Act
await newLockSource.AcquireAsync(RandomKey, DefaultTtl);
// Assert
await AssertTableExistsAsync(LocksTable);
}
protected override async Task<bool> LockExistsAsync(string key, Guid? id = null)
{
var cql = $"select * from {LocksTable} where lock_key = '{key}'";
if (id.HasValue)
{
cql += $" and lock_id = {id} allow filtering";
}
var results = await Session.ExecuteAsync(new SimpleStatement(cql));
return results.Any();
}
private static ICluster CreateCluster()
{
return global::Cassandra.Cluster.Builder()
.AddContactPoint("127.0.0.1")
.WithDefaultKeyspace(TestKeyspace)
.Build();
}
private static ISession CreateSession()
{
return ((Cluster)Cluster).ConnectAndCreateDefaultKeyspaceIfNotExists();
}
private static async Task DeleteTableIfExistsAsync(string tableName)
{
await Session.ExecuteAsync(new SimpleStatement($"drop table if exists {tableName}"));
Assert.True(await Cluster.RefreshSchemaAsync());
Assert.Null(Cluster.Metadata.GetTable(TestKeyspace, tableName));
}
private static async Task AssertTableExistsAsync(string tableName)
{
Assert.True(await Cluster.RefreshSchemaAsync());
Assert.NotNull(Cluster.Metadata.GetTable(TestKeyspace, tableName));
}
}
}
| 32.170455 | 98 | 0.59343 | [
"MIT"
] | johnyk87/distributed-lock-poc | tests/LockDotNet.Cassandra.Tests/CassandraLockSourceTests.cs | 2,831 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using Example.src.controller.rendering;
using Example.src.model;
using Example.src.model.entitys;
using Example.src.model.graphics.camera;
using Example.src.model.graphics.rendering;
using Example.src.model.graphics.ui;
using Example.src.Test;
using OpenTK.Input;
using Zenseless.Geometry;
using Zenseless.HLGL;
using Zenseless.OpenGL;
using OpenTK.Graphics.OpenGL4;
using Example.src.model.entitys.WaterSim;
namespace Example.src.controller
{
class Game
{
DeferredRenderer renderer;
UIRenderer uiRenderer;
IContentLoader contentLoader;
IRenderState renderState;
Camera activeCam;
Scene activeScene;
Vector3 campos = new Vector3(0, 10, -5f);
Vector2 camrot = new Vector2(0, 180);
//Vector3 campos = new Vector3(0, 1, 10f);
//Vector2 camrot = new Vector2(25, 180);
float rotSpeedY = 40;
float rotSpeedX = 40;
DateTime startTime;
Water water;
Entity waterEntity;
UI ui;
Vector2 windowRes;
Vector2 mousePos;
public Game(IContentLoader contentLoader, IRenderState renderState)
{
ui = new IslandUI(contentLoader);
this.renderState = renderState;
this.contentLoader = contentLoader;
renderer = new DeferredRenderer(contentLoader, renderState);
uiRenderer = new UIRenderer(contentLoader, renderState);
activeScene = new IslandScene(contentLoader, renderer);
waterEntity = activeScene.GetEntityByName("water");
if(waterEntity != null)
waterEntity.renderable.heightScaleFactor = 0.03f;
renderer.SetPointLights(activeScene.getPointLights());
activeCam = new FirstPersonCamera(campos, camrot.X, camrot.Y, Camera.ProjectionType.Perspective, fov:1f, width:20, height:20, zPlaneFar: 100f);
startTime = DateTime.Now;
water = new Water(this.contentLoader);
}
public void Update(float deltatime)
{
UpdateControl(deltatime);
activeScene.Update(deltatime);
}
bool mouseClicked = false;
Vector2 mouseClickedPos;
Vector2 mouseDelta;
Vector2 mouseSpeed = new Vector2(0.5f, 0.5f);
Vector3 movementSpeed = new Vector3(1f, 1f, 1f);
float shiftSpeedFactor = 3f;
private void UpdateControl(float deltatime)
{
OpenTK.Vector4 dirVec = new OpenTK.Vector4(0, 0, 1, 1);
OpenTK.Vector4 rightVec = new OpenTK.Vector4(1, 0, 0, 1);
Matrix4x4 rot = activeCam.GetRotationMatrix();
OpenTK.Matrix4 testMat = new OpenTK.Matrix4(rot.M11, rot.M12, rot.M13, rot.M14,
rot.M21, rot.M22, rot.M23, rot.M24,
rot.M31, rot.M32, rot.M33, rot.M34,
rot.M41, rot.M42, rot.M43, rot.M44);
testMat.Transpose();
dirVec = testMat * dirVec;
rightVec = testMat * rightVec;
dirVec.Normalize();
rightVec.Normalize();
Vector3 dirVecConvert = new Vector3(dirVec.X, dirVec.Y, dirVec.Z);
Vector3 rightVecConvert = new Vector3(rightVec.X, rightVec.Y, rightVec.Z);
MouseState mstate = Mouse.GetState();
if (mouseClicked)
{
Vector2 mDiff = (mousePos - mouseClickedPos);
RotateCam(new Vector2(mDiff.Y, mDiff.X) * deltatime * mouseSpeed);
}
KeyboardState kstate = Keyboard.GetState();
Vector3 tmpMovementSpeed = movementSpeed;
if(kstate.IsKeyDown(Key.ShiftLeft))
{
tmpMovementSpeed *= shiftSpeedFactor;
}
if (kstate.IsKeyDown(Key.A))
{
MoveCam(rightVecConvert * deltatime * -1 * tmpMovementSpeed.X);
}
if (kstate.IsKeyDown(Key.D))
{
MoveCam(rightVecConvert * deltatime * 1 * tmpMovementSpeed.X);
}
if (kstate.IsKeyDown(Key.W))
{
MoveCam(dirVecConvert * -1 * deltatime * tmpMovementSpeed.Z );
}
if (kstate.IsKeyDown(Key.S))
{
MoveCam(dirVecConvert * 1 * deltatime * tmpMovementSpeed.Z);
}
if (kstate.IsKeyDown(Key.Q))
{
MoveCam(new Vector3(0, 1 * deltatime * tmpMovementSpeed.Y, 0));
}
if (kstate.IsKeyDown(Key.E))
{
MoveCam(new Vector3(0, -1 * deltatime * tmpMovementSpeed.Y, 0));
}
if (kstate.IsKeyDown(Key.Up))
{
RotateCam(new Vector2(-rotSpeedX * deltatime, 0));
}
if (kstate.IsKeyDown(Key.Down))
{
RotateCam(new Vector2(rotSpeedX * deltatime, 0));
}
if (kstate.IsKeyDown(Key.Left))
{
RotateCam(new Vector2(0, -rotSpeedY * deltatime));
}
if (kstate.IsKeyDown(Key.Right))
{
RotateCam(new Vector2(0, rotSpeedY * deltatime));
}
if (kstate.IsKeyDown(Key.F1))
{
Debug.WriteLine("Camera Positon: " + campos + "\nCamera Rotation: " + camrot);
}
if (kstate.IsKeyDown(Key.F4))
{
renderer.currentRenderMode = DeferredRenderer.RenderMode.deferred;
}
if (kstate.IsKeyDown(Key.F5))
{
renderer.currentRenderMode = DeferredRenderer.RenderMode.postion;
}
if (kstate.IsKeyDown(Key.F6))
{
renderer.currentRenderMode = DeferredRenderer.RenderMode.color;
}
if(kstate.IsKeyDown(Key.F7))
{
renderer.currentRenderMode = DeferredRenderer.RenderMode.normal;
}
if (kstate.IsKeyDown(Key.F8))
{
renderer.currentRenderMode = DeferredRenderer.RenderMode.shadow;
}
if(kstate.IsKeyDown(Key.F9))
{
renderer.currentRenderMode = DeferredRenderer.RenderMode.directional;
}
if(kstate.IsKeyDown(Key.F10))
{
renderer.currentRenderMode = DeferredRenderer.RenderMode.pointlight;
}
}
public void GameWindow_MouseMove(object sender, OpenTK.Input.MouseMoveEventArgs e)
{
mousePos = new Vector2(e.X, e.Y);
mouseDelta.X = e.XDelta;
mouseDelta.Y = e.YDelta;
}
public void GameWindow_MouseDown(object sender, OpenTK.Input.MouseButtonEventArgs e)
{
mouseClicked = true;
mouseClickedPos = new Vector2(e.X, e.Y);
Vector2 glPos = ScreenPositionToGLViewport(e.X, e.Y);
ui.Click(glPos.X, glPos.Y);
}
public void GameWindow_MouseUp(object sender, OpenTK.Input.MouseButtonEventArgs e)
{
mouseClicked = false;
}
private void MoveCam(Vector3 move)
{
campos += move;
activeCam.SetPosition(campos);
//Vector3 nCamPos = new Vector3(campos.X, campos.Y + 1, campos.Z - 5f);
//activeScene.GetDirectionalLightCamera().SetPosition(nCamPos);
}
private void RotateCam(Vector2 rot)
{
camrot += rot;
activeCam.SetRotation(new Vector3(camrot, 0));
}
public void Render()
{
DateTime dtCurr = DateTime.Now;
TimeSpan diff = dtCurr - startTime;
float diffsecs = (float)(diff.TotalMilliseconds) / (float)(1000);
water.CreateMaps(diffsecs);
if (waterEntity != null)
{
waterEntity.renderable.SetHeightMap(water.GetTexture());
//waterEntity.renderable.SetNormalMap(water.GetNormalMap());
}
//TextureDebugger.Draw(water.GetNormalMap());
RenderDeferred();
RenderUI(renderer.GetFinalPassTexture(), ui);
}
public Vector2 ScreenPositionToGLViewport(int x, int y)
{
float posX = (2 / windowRes.X) * x - 1;
float posY = (2 / windowRes.Y) * -y + 1;
return new Vector2(posX, posY) ;
}
public void Resize(int width, int height)
{
renderer.Resize(width, height);
activeCam.Resize(width, height);
activeScene.Resize(width, height);
windowRes.X = width;
windowRes.Y = height;
}
private void RenderDeferred()
{
List<Entity> geometry = activeScene.getGeometry();
List<Entity> renderables = new List<Entity>();
List<Entity> alphaGeometry = new List<Entity>();
foreach(Entity e in geometry)
{
if(e.renderable != null)
{
renderables.Add(e);
/*
if(e.renderable.alphaMap == null)
{
renderables.Add(e);
}
else
{
alphaGeometry.Add(e);
}
*/
}
}
List<ParticleSystem> particleSystem = activeScene.GetParticleSystems();
Vector3 camDir = activeCam.GetDirection();
renderer.StartLightViewPass();
for(int i = 0; i < renderables.Count; i++)
{
renderer.DrawShadowLightView(activeScene.GetDirectionalLightCamera(), renderables[i].renderable);
}
for (int i = 0; i < alphaGeometry.Count; i++)
{
renderer.DrawShadowLightView(activeScene.GetDirectionalLightCamera(), alphaGeometry[i].renderable);
}
for (int j = 0; j < particleSystem.Count; j++)
{
renderer.DrawShadowLightViewParticle(activeScene.GetDirectionalLightCamera(), particleSystem[j].GetShadowRenderable(), particleSystem[j]);
}
renderer.FinishLightViewPass();
renderer.StartShadowMapPass();
for (int i = 0; i < renderables.Count; i++)
{
renderer.CreateShadowMap(activeCam.GetMatrix(), activeScene.GetDirectionalLightCamera(), renderables[i].renderable, activeScene.getDirectionalLight().direction);
}
for (int i = 0; i < alphaGeometry.Count; i++)
{
renderer.CreateShadowMap(activeCam.GetMatrix(), activeScene.GetDirectionalLightCamera(), alphaGeometry[i].renderable, activeScene.getDirectionalLight().direction);
}
for (int j = 0; j < particleSystem.Count; j++)
{
renderer.CreateShadowMapParticle(activeCam, activeScene.GetDirectionalLightCamera(), particleSystem[j].GetShadowRenderable(), activeScene.getDirectionalLight().direction, particleSystem[j]);
}
renderer.FinishShadowMassPass();
renderer.StartGeometryPass();
for (int i = 0; i < renderables.Count; i++)
{
renderer.DrawDeferredGeometry(renderables[i].renderable, activeCam.GetMatrix(), campos, camDir);
}
for (int i = 0; i < alphaGeometry.Count; i++)
{
renderer.DrawDeferredGeometry(alphaGeometry[i].renderable, activeCam.GetMatrix(), campos, camDir);
}
for (int j = 0; j < particleSystem.Count; j++)
{
renderer.DrawDeferredParticle(particleSystem[j].GetDeferredRenderable(), activeCam, campos, camDir, particleSystem[j]);
}
renderer.FinishGeometryPass();
renderer.PointLightPass(activeCam.GetMatrix(), campos, camDir);
renderer.FinalPass(campos, activeScene.GetAmbientColor(), activeScene.getDirectionalLight(), camDir, true);
}
private void RenderUI(ITexture2D texture, UI ui)
{
uiRenderer.Render(texture, ui.GetUIElements());
}
}
}
| 37.557229 | 206 | 0.556741 | [
"Apache-2.0"
] | amadron/FinalProject_ShaderProg | ShaderProgAbgabe/src/controller/Game.cs | 12,471 | C# |
namespace P07.InfernoInfinity.Enums
{
public enum ClarityLevel
{
Chipped = 1,
Regular = 2,
Perfect = 5,
Flawless = 10
}
}
| 15.181818 | 36 | 0.526946 | [
"MIT"
] | kovachevmartin/SoftUni | CSharp-OOP/07-REFLECTION_ATTRIBUTES/Exercise/P07.InfernoInfinity/Enums/ClarityLevel.cs | 169 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Skoruba.IdentityServer4.Admin.BusinessLogic.Identity.Dtos.Identity;
using Skoruba.IdentityServer4.Admin.BusinessLogic.Identity.Services.Interfaces;
using Skoruba.IdentityServer4.Admin.BusinessLogic.Shared.Dtos.Common;
using Skoruba.IdentityServer4.Admin.UI.Configuration.Constants;
using Skoruba.IdentityServer4.Admin.UI.ExceptionHandling;
using Skoruba.IdentityServer4.Admin.UI.Helpers.Localization;
namespace Skoruba.IdentityServer4.Admin.UI.Areas.AdminUI.Controllers
{
[TypeFilter(typeof(ControllerExceptionFilterAttribute))]
[Area(CommonConsts.AdminUIArea)]
public class IdentityController<TUserDto, TRoleDto, TUser, TRole, TKey, TUserClaim, TUserRole, TUserLogin, TRoleClaim, TUserToken,
TUsersDto, TRolesDto, TUserRolesDto, TUserClaimsDto,
TUserProviderDto, TUserProvidersDto, TUserChangePasswordDto, TRoleClaimsDto, TUserClaimDto, TRoleClaimDto> : BaseController
where TUserDto : UserDto<TKey>, new()
where TRoleDto : RoleDto<TKey>, new()
where TUser : IdentityUser<TKey>
where TRole : IdentityRole<TKey>
where TKey : IEquatable<TKey>
where TUserClaim : IdentityUserClaim<TKey>
where TUserRole : IdentityUserRole<TKey>
where TUserLogin : IdentityUserLogin<TKey>
where TRoleClaim : IdentityRoleClaim<TKey>
where TUserToken : IdentityUserToken<TKey>
where TUsersDto : UsersDto<TUserDto, TKey>
where TRolesDto : RolesDto<TRoleDto, TKey>
where TUserRolesDto : UserRolesDto<TRoleDto, TKey>
where TUserClaimsDto : UserClaimsDto<TUserClaimDto, TKey>
where TUserProviderDto : UserProviderDto<TKey>
where TUserProvidersDto : UserProvidersDto<TUserProviderDto, TKey>
where TUserChangePasswordDto : UserChangePasswordDto<TKey>
where TRoleClaimsDto : RoleClaimsDto<TRoleClaimDto, TKey>
where TUserClaimDto : UserClaimDto<TKey>
where TRoleClaimDto : RoleClaimDto<TKey>
{
private readonly IIdentityService<TUserDto, TRoleDto, TUser, TRole, TKey, TUserClaim, TUserRole, TUserLogin, TRoleClaim, TUserToken,
TUsersDto, TRolesDto, TUserRolesDto, TUserClaimsDto,
TUserProviderDto, TUserProvidersDto, TUserChangePasswordDto, TRoleClaimsDto, TUserClaimDto, TRoleClaimDto> _identityService;
private readonly IGenericControllerLocalizer<IdentityController<TUserDto, TRoleDto, TUser, TRole, TKey, TUserClaim, TUserRole, TUserLogin, TRoleClaim, TUserToken,
TUsersDto, TRolesDto, TUserRolesDto, TUserClaimsDto,
TUserProviderDto, TUserProvidersDto, TUserChangePasswordDto, TRoleClaimsDto, TUserClaimDto, TRoleClaimDto>> _localizer;
public IdentityController(IIdentityService<TUserDto, TRoleDto, TUser, TRole, TKey, TUserClaim, TUserRole, TUserLogin, TRoleClaim, TUserToken,
TUsersDto, TRolesDto, TUserRolesDto, TUserClaimsDto,
TUserProviderDto, TUserProvidersDto, TUserChangePasswordDto, TRoleClaimsDto, TUserClaimDto, TRoleClaimDto> identityService,
ILogger<ConfigurationController> logger,
IGenericControllerLocalizer<IdentityController<TUserDto, TRoleDto, TUser, TRole, TKey, TUserClaim, TUserRole, TUserLogin, TRoleClaim, TUserToken,
TUsersDto, TRolesDto, TUserRolesDto, TUserClaimsDto,
TUserProviderDto, TUserProvidersDto, TUserChangePasswordDto, TRoleClaimsDto, TUserClaimDto, TRoleClaimDto>> localizer) : base(logger)
{
_identityService = identityService;
_localizer = localizer;
}
[HttpGet]
public async Task<IActionResult> Roles(int? page, string search)
{
ViewBag.Search = search;
var roles = await _identityService.GetRolesAsync(search, page ?? 1);
return View(roles);
}
[HttpGet]
public async Task<IActionResult> Role(TKey id)
{
if (EqualityComparer<TKey>.Default.Equals(id, default))
{
return View(new TRoleDto());
}
var role = await _identityService.GetRoleAsync(id.ToString());
return View(role);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Role(TRoleDto role)
{
if (!ModelState.IsValid)
{
return View(role);
}
TKey roleId;
if (EqualityComparer<TKey>.Default.Equals(role.Id, default))
{
var roleData = await _identityService.CreateRoleAsync(role);
roleId = roleData.roleId;
}
else
{
var roleData = await _identityService.UpdateRoleAsync(role);
roleId = roleData.roleId;
}
SuccessNotification(string.Format(_localizer["SuccessCreateRole"], role.Name), _localizer["SuccessTitle"]);
return RedirectToAction(nameof(Role), new { Id = roleId });
}
[HttpGet]
public async Task<IActionResult> Users(int? page, string search)
{
ViewBag.Search = search;
var usersDto = await _identityService.GetUsersAsync(search, page ?? 1);
return View(usersDto);
}
[HttpGet]
public async Task<IActionResult> RoleUsers(string id, int? page, string search)
{
ViewBag.Search = search;
var roleUsers = await _identityService.GetRoleUsersAsync(id, search, page ?? 1);
var roleDto = await _identityService.GetRoleAsync(id);
ViewData["RoleName"] = roleDto.Name;
return View(roleUsers);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UserProfile(TUserDto user)
{
if (!ModelState.IsValid)
{
return View(user);
}
TKey userId;
if (EqualityComparer<TKey>.Default.Equals(user.Id, default))
{
var userData = await _identityService.CreateUserAsync(user);
userId = userData.userId;
}
else
{
var userData = await _identityService.UpdateUserAsync(user);
userId = userData.userId;
}
SuccessNotification(string.Format(_localizer["SuccessCreateUser"], user.UserName), _localizer["SuccessTitle"]);
return RedirectToAction(nameof(UserProfile), new { Id = userId });
}
[HttpGet]
public async Task<IActionResult> UserProfile(TKey id)
{
if (EqualityComparer<TKey>.Default.Equals(id, default))
{
var newUser = new TUserDto();
return View("UserProfile", newUser);
}
var user = await _identityService.GetUserAsync(id.ToString());
if (user == null) return NotFound();
return View("UserProfile", user);
}
[HttpGet]
public async Task<IActionResult> UserRoles(TKey id, int? page)
{
if (EqualityComparer<TKey>.Default.Equals(id, default)) return NotFound();
var userRoles = await _identityService.BuildUserRolesViewModel(id, page);
return View(userRoles);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UserRoles(TUserRolesDto role)
{
await _identityService.CreateUserRoleAsync(role);
SuccessNotification(_localizer["SuccessCreateUserRole"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(UserRoles), new { Id = role.UserId });
}
[HttpGet]
public async Task<IActionResult> UserRolesDelete(TKey id, TKey roleId)
{
await _identityService.ExistsUserAsync(id.ToString());
await _identityService.ExistsRoleAsync(roleId.ToString());
var userDto = await _identityService.GetUserAsync(id.ToString());
var roles = await _identityService.GetRolesAsync();
var rolesDto = new UserRolesDto<TRoleDto, TKey>
{
UserId = id,
RolesList = roles.Select(x => new SelectItemDto(x.Id.ToString(), x.Name)).ToList(),
RoleId = roleId,
UserName = userDto.UserName
};
return View(rolesDto);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UserRolesDelete(TUserRolesDto role)
{
await _identityService.DeleteUserRoleAsync(role);
SuccessNotification(_localizer["SuccessDeleteUserRole"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(UserRoles), new { Id = role.UserId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UserClaims(TUserClaimsDto claim)
{
if (!ModelState.IsValid)
{
return View(claim);
}
await _identityService.CreateUserClaimsAsync(claim);
SuccessNotification(string.Format(_localizer["SuccessCreateUserClaims"], claim.ClaimType, claim.ClaimValue), _localizer["SuccessTitle"]);
return RedirectToAction(nameof(UserClaims), new { Id = claim.UserId });
}
[HttpGet]
public async Task<IActionResult> UserClaims(TKey id, int? page)
{
if (EqualityComparer<TKey>.Default.Equals(id, default)) return NotFound();
var claims = await _identityService.GetUserClaimsAsync(id.ToString(), page ?? 1);
claims.UserId = id;
return View(claims);
}
[HttpGet]
public async Task<IActionResult> UserClaimsDelete(TKey id, int claimId)
{
if (EqualityComparer<TKey>.Default.Equals(id, default)
|| EqualityComparer<int>.Default.Equals(claimId, default)) return NotFound();
var claim = await _identityService.GetUserClaimAsync(id.ToString(), claimId);
if (claim == null) return NotFound();
var userDto = await _identityService.GetUserAsync(id.ToString());
claim.UserName = userDto.UserName;
return View(claim);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UserClaimsDelete(TUserClaimsDto claim)
{
await _identityService.DeleteUserClaimAsync(claim);
SuccessNotification(_localizer["SuccessDeleteUserClaims"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(UserClaims), new { Id = claim.UserId });
}
[HttpGet]
public async Task<IActionResult> UserProviders(TKey id)
{
if (EqualityComparer<TKey>.Default.Equals(id, default)) return NotFound();
var providers = await _identityService.GetUserProvidersAsync(id.ToString());
return View(providers);
}
[HttpGet]
public async Task<IActionResult> UserProvidersDelete(TKey id, string providerKey)
{
if (EqualityComparer<TKey>.Default.Equals(id, default) || string.IsNullOrEmpty(providerKey)) return NotFound();
var provider = await _identityService.GetUserProviderAsync(id.ToString(), providerKey);
if (provider == null) return NotFound();
return View(provider);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UserProvidersDelete(TUserProviderDto provider)
{
await _identityService.DeleteUserProvidersAsync(provider);
SuccessNotification(_localizer["SuccessDeleteUserProviders"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(UserProviders), new { Id = provider.UserId });
}
[HttpGet]
public async Task<IActionResult> UserChangePassword(TKey id)
{
if (EqualityComparer<TKey>.Default.Equals(id, default)) return NotFound();
var user = await _identityService.GetUserAsync(id.ToString());
var userDto = new UserChangePasswordDto<TKey> { UserId = id, UserName = user.UserName };
return View(userDto);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UserChangePassword(TUserChangePasswordDto userPassword)
{
if (!ModelState.IsValid)
{
return View(userPassword);
}
var identityResult = await _identityService.UserChangePasswordAsync(userPassword);
if (!identityResult.Errors.Any())
{
SuccessNotification(_localizer["SuccessUserChangePassword"], _localizer["SuccessTitle"]);
return RedirectToAction("UserProfile", new { Id = userPassword.UserId });
}
foreach (var error in identityResult.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return View(userPassword);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RoleClaims(TRoleClaimsDto claim)
{
if (!ModelState.IsValid)
{
return View(claim);
}
await _identityService.CreateRoleClaimsAsync(claim);
SuccessNotification(string.Format(_localizer["SuccessCreateRoleClaims"], claim.ClaimType, claim.ClaimValue), _localizer["SuccessTitle"]);
return RedirectToAction(nameof(RoleClaims), new { Id = claim.RoleId });
}
[HttpGet]
public async Task<IActionResult> RoleClaims(TKey id, int? page)
{
if (EqualityComparer<TKey>.Default.Equals(id, default)) return NotFound();
var claims = await _identityService.GetRoleClaimsAsync(id.ToString(), page ?? 1);
claims.RoleId = id;
return View(claims);
}
[HttpGet]
public async Task<IActionResult> RoleClaimsDelete(TKey id, int claimId)
{
if (EqualityComparer<TKey>.Default.Equals(id, default) ||
EqualityComparer<int>.Default.Equals(claimId, default)) return NotFound();
var claim = await _identityService.GetRoleClaimAsync(id.ToString(), claimId);
return View(claim);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RoleClaimsDelete(TRoleClaimsDto claim)
{
await _identityService.DeleteRoleClaimAsync(claim);
SuccessNotification(_localizer["SuccessDeleteRoleClaims"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(RoleClaims), new { Id = claim.RoleId });
}
[HttpGet]
public async Task<IActionResult> RoleDelete(TKey id)
{
if (EqualityComparer<TKey>.Default.Equals(id, default)) return NotFound();
var roleDto = await _identityService.GetRoleAsync(id.ToString());
if (roleDto == null) return NotFound();
return View(roleDto);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RoleDelete(TRoleDto role)
{
await _identityService.DeleteRoleAsync(role);
SuccessNotification(_localizer["SuccessDeleteRole"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(Roles));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UserDelete(TUserDto user)
{
var currentUserId = User.GetSubjectId();
if (user.Id.ToString() == currentUserId)
{
CreateNotification(Helpers.NotificationHelpers.AlertType.Warning, _localizer["ErrorDeleteUser_CannotSelfDelete"]);
return RedirectToAction(nameof(UserDelete), user.Id);
}
else
{
await _identityService.DeleteUserAsync(user.Id.ToString(), user);
SuccessNotification(_localizer["SuccessDeleteUser"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(Users));
}
}
[HttpGet]
public async Task<IActionResult> UserDelete(TKey id)
{
if (EqualityComparer<TKey>.Default.Equals(id, default)) return NotFound();
var user = await _identityService.GetUserAsync(id.ToString());
if (user == null) return NotFound();
return View(user);
}
}
} | 38.326577 | 170 | 0.631251 | [
"MIT"
] | vbegroup/IdentityServer4.Admin | src/Skoruba.IdentityServer4.Admin.UI/Areas/AdminUI/Controllers/IdentityController.cs | 17,019 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManagerArchivalObject : MonoBehaviour
{
#region Serialized Variables
#region Datas
[Space, Header("Datas")]
[SerializeField]
[Tooltip("GameManager Scriptable Object")]
private GameMangerData gmData = default;
[SerializeField]
[Tooltip("Do you want to disable the curosr?")]
private bool isCursorDisabled = default;
#endregion
#region Cinemachine Cams
[Space, Header("Cinemachine Cameras")]
[SerializeField]
[Tooltip("LayerMask to switch to")]
private LayerMask switchLayer = default;
[SerializeField]
[Tooltip("Default LayerMask")]
private LayerMask defaultLayer = default;
#endregion
#region UI
[Space, Header("UI")]
[SerializeField]
[Tooltip("Pause Buttons")]
private Button[] pauseButtons = default;
#endregion
#region Animators
[Space, Header("Animators")]
[SerializeField]
[Tooltip("Fade Panel")]
private Animator fadeBG = default;
[SerializeField]
[Tooltip("Stickman Flicker Anim")]
private Animator stickmanFlickerAnim = default;
#endregion
#region GameObjects
[Space, Header("GameObjects")]
[SerializeField]
[Tooltip("Player Root")]
private GameObject playerRoot = default;
[SerializeField]
[Tooltip("Player HUD Panel")]
private GameObject hudPanel = default;
[SerializeField]
[Tooltip("Player Pause Panel")]
private GameObject pausePanel = default;
[SerializeField]
[Tooltip("Crane GameObject")]
private GameObject craneObj = default;
[SerializeField]
[Tooltip("Room 2 GameObject")]
private GameObject room2Obj = default;
[SerializeField]
[Tooltip("Room 2 Door GameObject")]
private GameObject room2DoorObj = default;
#endregion
#region Transforms
[Space, Header("Transforms")]
[SerializeField]
[Tooltip("Room 2 Teleport Position")]
private Transform room2TeleportPos = default;
#endregion
#region Floats
[Space, Header("Floats")]
[SerializeField]
[Tooltip("Crane Rotation Speed")]
private float craneRotationSpeed = default;
[SerializeField]
[Tooltip("Room 2 shrink size change Speed")]
[Range(0f, 0.5f)] private float room2ShrinkChangeSpeed = default;
[SerializeField]
[Tooltip("Room 2 expand size change Speed")]
[Range(0f, 3f)] private float room2ExpandChangeSpeed = default;
[SerializeField]
[Tooltip("How long will the 2nd room keep shrinking?")]
private float room2ShrinkDelay = default;
[SerializeField]
[Tooltip("When will the 2nd room door appear?")]
private float room2DoorDelay = default;
#endregion
#region Events Float
public delegate void SendEventsFloat(float floatIndex);
/// <summary>
/// Event sent from GameManagerArchivalObject to FPSController Scripts;
/// Changes the Player's speed;
/// </summary>
public static event SendEventsFloat OnSpeedToggle;
#endregion
#endregion
#region Private Variables
private Camera _cam = default;
private bool _isCraneRotating = default;
private Vector3 _intialRoom2Size = default;
private bool _isRoom2GettingSmall = default;
private CharacterController _charControl = default;
#endregion
#region Unity Callbacks
#region Events
void OnEnable()
{
}
void OnDisable()
{
}
void OnDestroy()
{
}
#endregion
void Start()
{
_cam = Camera.main;
StartCoroutine(StartDelay());
_intialRoom2Size = room2Obj.transform.localScale;
_charControl = playerRoot.GetComponent<CharacterController>();
if (isCursorDisabled)
gmData.DisableCursor();
}
void Update()
{
RotatingCrane();
Room2Size();
if (gmData.currState == GameMangerData.GameState.Game &&
Input.GetKeyDown(KeyCode.Escape))
PauseGame();
}
#endregion
#region My Functions
#region UI
#region Buttons
/// <summary>
/// Function tied with Resume_Button Button;
/// Resumes the Game;
/// </summary>
public void OnClick_Resume()
{
gmData.TogglePause(false);
pausePanel.SetActive(false);
hudPanel.SetActive(true);
gmData.DisableCursor();
}
/// <summary>
/// Function tied with Restart_Button Button;
/// Restarts the game with a delay;
/// </summary>
public void OnClick_Restart() => StartCoroutine(RestartGameDelay());
/// <summary>
/// Button tied with Menu_Button;
/// Goes to the Menu with a delay;
/// </summary>
public void OnClick_Menu() => StartCoroutine(MenuDelay());
/// <summary>
/// Function tied with Quit_Button Buttons;
/// Quits the game with a delay;
/// </summary>
public void OnClick_Quit() => StartCoroutine(QuitGameDelay());
/// <summary>
/// Function tied with Restart_Button, Menu_Button and Quit_Button Buttons;
/// Disables the buttons so the Player can't interact with them when the panel is fading out;
/// </summary>
public void OnClick_DisableButtons()
{
for (int i = 0; i < pauseButtons.Length; i++)
pauseButtons[i].interactable = false;
}
#endregion
void PauseGame()
{
gmData.TogglePause(true);
gmData.EnableCursor();
pausePanel.SetActive(true);
hudPanel.SetActive(false);
}
#endregion
#region Room 1
/// <summary>
/// Switches the layer of the Camera's CullingMask;
/// Also toggles the main Virutal Camera GameObject;
/// </summary>
/// <param name="isSwitchLayer"> If true, change to custom LayerMask, if false, change to default; </param>
public void OnSwitchCameraLayer(bool isSwitchLayer)
{
if (isSwitchLayer)
{
hudPanel.SetActive(false);
_cam.cullingMask = switchLayer;
}
else
{
hudPanel.SetActive(true);
_cam.cullingMask = defaultLayer;
}
}
/// <summary>
/// Makes the crane rotate with the bool from the Unity Event;
/// </summary>
/// <param name="isRotatingCrane"> If true, rotates the crane, else it stops rotation; </param>
public void OnCraneRotate(bool isRotatingCrane)
{
if (isRotatingCrane)
_isCraneRotating = true;
else
_isCraneRotating = false;
}
/// <summary>
/// Subbed to level trigger for room 1;
/// Changes the speed of the player;
/// </summary>
/// <param name="speed"> Speed variable for the player; </param>
public void OnIsPlayerSpeedy(float speed) => OnSpeedToggle?.Invoke(speed);
/// <summary>
/// Crane rotation;
/// </summary>
void RotatingCrane()
{
if (_isCraneRotating)
craneObj.transform.Rotate(craneRotationSpeed * Time.deltaTime * Vector3.up);
}
#endregion
#region Room 2
public void OnRoom2Event() => StartCoroutine(Room2Sequence());
void Room2Size()
{
if (_isRoom2GettingSmall)
room2Obj.transform.localScale = Vector3.Lerp(room2Obj.transform.localScale, Vector3.zero, room2ShrinkChangeSpeed * Time.deltaTime);
else
room2Obj.transform.localScale = Vector3.Lerp(room2Obj.transform.localScale, _intialRoom2Size, room2ExpandChangeSpeed * Time.deltaTime);
}
#endregion
#endregion
#region Coroutines
#region UI
/// <summary>
/// Starts Game with delay
/// </summary>
/// <returns> Float delay; </returns>
IEnumerator StartDelay()
{
fadeBG.Play("Fade_In");
gmData.ChangeGameState("Intro");
yield return new WaitForSeconds(0.5f);
gmData.ChangeGameState("Game");
}
/// <summary>
/// Restarts the game with a Delay;
/// </summary>
/// <returns> Float Delay; </returns>
IEnumerator RestartGameDelay()
{
gmData.TogglePause(false);
fadeBG.Play("Fade_Out");
gmData.ChangeGameState("Exit");
yield return new WaitForSeconds(0.5f);
gmData.ChangeLevel(Application.loadedLevel);
}
/// <summary>
/// Goes to Menu with a Delay;
/// </summary>
/// <returns> Float Delay; </returns>
IEnumerator MenuDelay()
{
gmData.TogglePause(false);
gmData.ChangeGameState("Exit");
fadeBG.Play("Fade_Out");
yield return new WaitForSeconds(0.5f);
gmData.ChangeLevel(0);
}
/// <summary>
/// Quits with a Delay;
/// </summary>
/// <returns> Float Delay; </returns>
IEnumerator QuitGameDelay()
{
gmData.TogglePause(false);
fadeBG.Play("Fade_Out");
gmData.ChangeGameState("Exit");
yield return new WaitForSeconds(0.5f);
Application.Quit();
}
#endregion
IEnumerator Room2Sequence()
{
stickmanFlickerAnim.Play("Stickman_Flicker_Anim");
_charControl.enabled = false;
playerRoot.transform.position = room2TeleportPos.position;
_charControl.enabled = true;
room2DoorObj.SetActive(true);
_isRoom2GettingSmall = true;
yield return new WaitForSeconds(room2ShrinkDelay);
_isRoom2GettingSmall = false;
stickmanFlickerAnim.Play("Empty");
yield return new WaitForSeconds(room2DoorDelay);
room2DoorObj.SetActive(false);
}
#endregion
#region Events
#endregion
} | 26.575 | 147 | 0.637608 | [
"MIT"
] | GRENADEable/CPS | RMIT_CPS/Assets/Scripts/Managers/GameManagerArchivalObject.cs | 9,567 | C# |
using System;
namespace ClickHouse.Ado.Impl.Settings {
internal class UInt64SettingValue : SettingValue {
public UInt64SettingValue(ulong value) => Value = value;
public ulong Value { get; set; }
protected internal override void Write(ProtocolFormatter formatter) => formatter.WriteUInt((long) Value);
internal override T As<T>() {
if (typeof(T) != typeof(ulong)) throw new InvalidCastException();
return (T) (object) Value;
}
internal override object AsValue() => Value;
}
} | 31.166667 | 113 | 0.643494 | [
"MIT"
] | Fabuza/ClickHouse-Net | ClickHouse.Ado/Impl/Settings/UInt64SettingValue.cs | 563 | C# |
using System.Data;
using LibDBConnect;
namespace LibDataLayer
{
public static class DalNews
{
private static readonly SqlHelper Cls = new SqlHelper();
#region[Get-Data]
public static DataTable GetNews(string keywords, int TotalTop)
{
Cls.CreateNewSqlCommand();
Cls.AddParameter("KEYWORDS", keywords);
Cls.AddParameter("TotalTop", TotalTop);
return Cls.GetData("sp_News_Get_HomePage");
}
public static DataTable GetNewsCount()
{
Cls.CreateNewSqlCommand();
return Cls.GetData("sp_News_Get_HomePageCount");
}
public static DataTable GetLike()
{
Cls.CreateNewSqlCommand();
return Cls.GetData("sp_Likes_Get");
}
#endregion
#region[Insert-Update-Delete]
public static bool Like(DTOLikes obj)
{
Cls.CreateNewSqlCommand();
Cls.AddParameter("ID_News", obj.ID_News);
Cls.AddParameter("Likes", obj.Likes);
Cls.AddParameter("IP_User", obj.IP_User);
return Cls.ExecuteNonQuery("sp_News_Like");
}
public static bool UnLike(DTOLikes obj)
{
Cls.CreateNewSqlCommand();
Cls.AddParameter("ID_News", obj.ID_News);
Cls.AddParameter("Likes", obj.Likes);
Cls.AddParameter("IP_User", obj.IP_User);
return Cls.ExecuteNonQuery("sp_News_UnLike");
}
#endregion
}
public class DTONews
{
public int ID_News { get; set; }
public string Titile { get; set; }
public string Img { get; set; }
public string ShortContent { get; set; }
public string Descriptions { get; set; }
public int AccountID { get; set; }
public int Likes { get; set; }
}
public class DTOLikes
{
public int ID_News { get; set; }
public int Likes { get; set; }
public string IP_User { get; set; }
}
} | 32.230769 | 71 | 0.556086 | [
"Apache-2.0"
] | chungthanhphuoc1990/SocialNetwork | SocialNetWork/LibDataLayer/DAL_News.cs | 2,097 | C# |
using Instagram.Response;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Instagram
{
class Program
{
static void Main(string[] args)
{
InstagramAPI api = new InstagramAPI(new TokenManager(_consumerKey: "a9beaa9c190649d18cdd99847d7261b8"));
UserResponse response = api.Users.BasicInfo("544232100");
var x = 10;
}
}
}
| 23.45 | 116 | 0.665245 | [
"MIT"
] | gokhangirgin/InstaNET | InstaNET/Program.cs | 471 | C# |
namespace CleanArchitecture.Application.TodoLists.Queries.ExportTodos;
public class ExportTodosVm
{
public ExportTodosVm(string fileName, string contentType, byte[] content)
{
FileName = fileName;
ContentType = contentType;
Content = content;
}
public string FileName { get; set; }
public string ContentType { get; set; }
public byte[] Content { get; set; }
} | 24.235294 | 77 | 0.677184 | [
"MIT"
] | azarmehri/clean-architecture | api/src/Application/TodoLists/Queries/ExportTodos/ExportTodosVm.cs | 414 | C# |
using GitTfs.Commands;
using NDesk.Options;
using StructureMap;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace GitTfs.Core
{
using System.Collections.Concurrent;
using System.Threading;
public static class Ext
{
public static T Tap<T>(this T o, Action<T> block)
{
block(o);
return o;
}
public static U Try<T, U>(this T o, Func<T, U> expr)
{
return Try(o, expr, () => default(U));
}
public static U Try<T, U>(this T o, Func<T, U> expr, Func<U> makeDefault)
{
if (o == null) return makeDefault();
return expr(o);
}
public static Action<T> And<T>(this Action<T> originalAction, params Action<T>[] additionalActions)
{
return x =>
{
originalAction(x);
foreach (var action in additionalActions)
{
action(x);
}
};
}
public static IEnumerable<T> Append<T>(this IEnumerable<T> set1, params IEnumerable<T>[] moreSets)
{
foreach (var item in set1)
{
yield return item;
}
foreach (var set in moreSets)
{
foreach (var item in set)
{
yield return item;
}
}
}
public static T GetOrAdd<K, T>(this Dictionary<K, T> dictionary, K key) where T : new()
{
if (!dictionary.ContainsKey(key))
dictionary.Add(key, new T());
return dictionary[key];
}
public static T FirstOr<T>(this IEnumerable<T> e, T defaultValue)
{
foreach (var x in e) return x;
return defaultValue;
}
public static bool Empty<T>(this IEnumerable<T> e)
{
return !e.Any();
}
public static void SetArguments(this ProcessStartInfo startInfo, params string[] args)
{
startInfo.Arguments = string.Join(" ", args.Select(arg => QuoteProcessArgument(arg)).ToArray());
}
private static string QuoteProcessArgument(string arg)
{
return arg.Contains(" ") ? ("\"" + arg + "\"") : arg;
}
public static string CombinePaths(string basePath, params string[] pathParts)
{
foreach (var part in pathParts)
{
basePath = Path.Combine(basePath, part);
}
return basePath;
}
public static string FormatForGit(this DateTime date)
{
return date.ToUniversalTime().ToString("s") + "Z";
}
public static bool IsEmpty<T>(this IEnumerable<T> c)
{
return c == null || !c.Any();
}
public static OptionSet GetAllOptions(this GitTfsCommand command, IContainer container)
{
return container.GetInstance<Globals>().OptionSet.Merge(command.OptionSet);
}
private static readonly Regex sha1OnlyRegex = new Regex("^" + GitTfsConstants.Sha1 + "$");
public static void AssertValidSha(this String sha)
{
if (!sha1OnlyRegex.IsMatch(sha))
throw new Exception("Invalid sha1: " + sha);
}
public static string Read(this TextReader reader, int length)
{
var chars = new char[length];
var charsRead = reader.Read(chars, 0, length);
return new string(chars, 0, charsRead);
}
/// <summary>
/// The encoding used by a stream is a read-only property. Use this method to
/// create a new stream based on <paramref name="stream"/> that uses
/// the given <paramref name="encoding"/> instead.
/// </summary>
public static StreamWriter WithEncoding(this StreamWriter stream, Encoding encoding)
{
return new StreamWriter(stream.BaseStream, encoding);
}
public static bool Contains(this IEnumerable<string> list, string toCheck, StringComparison comp)
{
return list.Any(listMember => listMember.IndexOf(toCheck, comp) >= 0);
}
/// <summary>
/// Optionally handle exceptions with "this" action. If there isn't a handler, don't catch exceptions.
/// </summary>
public static void Catch<TException>(this Action<TException> handler, Action work) where TException : Exception
{
if (handler == null)
{
work();
}
else
{
try
{
work();
}
catch (TException e)
{
handler(e);
}
}
}
/// <summary>
/// Translate the <paramref name="source"/> to the sequence of array's items
/// </summary>
/// <typeparam name="TSource">The source item type</typeparam>
/// <typeparam name="TResult">The output item type</typeparam>
/// <param name="source">The source collection</param>
/// <param name="selector">The delegate to use to translate</param>
/// <param name="batchSize">the of item in the batch array</param>
/// <returns>The <see cref="IEnumerable{T}"/> with arrays of items sized by <paramref name="batchSize"/></returns>
public static IEnumerable<TResult[]> ToBatch<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, int batchSize)
{
var batch = new List<TResult>(batchSize);
foreach (var item in source)
{
if (batch.Count >= batchSize)
{
yield return batch.ToArray();
batch.Clear();
}
batch.Add(selector(item));
}
if (batch.Count > 0)
{
yield return batch.ToArray();
}
}
/// <summary>
/// Translate the <paramref name="source"/> to the sequence of array's items
/// </summary>
/// <typeparam name="T">The source item type</typeparam>
/// <param name="source">The source collection</param>
/// <param name="batchSize">the of item in the batch array</param>
/// <returns>The <see cref="IEnumerable{T}"/> with arrays of items sized by <paramref name="batchSize"/></returns>
[DebuggerStepThrough]
public static IEnumerable<T[]> ToBatch<T>(this IEnumerable<T> source, int batchSize)
{
return ToBatch(source, e => e, batchSize);
}
/// <summary>
/// Executes the <paramref name="action"/> for each item in the <paramref name="source"/> simultaneously.
/// </summary>
/// <param name="source">The source sequence.</param>
/// <param name="action">The action to execute.</param>
/// <param name="parallelizeActions">set to true to enable parallel processing</param>
/// <typeparam name="T">The source item type</typeparam>
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action, bool parallelizeActions)
{
#if DEBUG && NO_PARALLEL
noParallel = true;
#endif
if (!parallelizeActions)
{
foreach (var item in source)
{
action(item);
}
}
else
{
(source as ParallelQuery<T> ?? source.AsParallel()).ForAll(action);
}
}
/// <summary>
/// TRuns the <paramref name="action"/> on each item in the <paramref name="source"/> in parallel
/// </summary>
/// <param name="source">
/// The source collection of items.
/// </param>
/// <param name="action">
/// The action to process of the item.
/// </param>
/// <param name="retryInterval">
/// The delay between retries.
/// </param>
/// <param name="parallelizeActions">set to true to enable parallel processing</param>
/// <typeparam name="T">The type of items in the <paramref name="source"/>.</typeparam>
/// <returns>
/// Returns <b>true</b> when all items processed successfully.</returns>
public static void ForEachRetry<T>(
this IEnumerable<T> source,
Action<T> action,
TimeSpan retryInterval,
bool parallelizeActions)
{
ForEachRetry(source, action, 10, retryInterval, parallelizeActions);
}
/// <summary>
/// TRuns the <paramref name="action"/> on each item in the <paramref name="source"/> in parallel
/// </summary>
/// <param name="source">
/// The source collection of items.
/// </param>
/// <param name="action">
/// The action to process of the item.
/// </param>
/// <param name="parallelizeActions">set to true to enable parallel processing</param>
/// <typeparam name="T">The type of items in the <paramref name="source"/>.</typeparam>
/// <returns>
/// Returns <b>true</b> when all items processed successfully.</returns>
public static void ForEachRetry<T>(this IEnumerable<T> source, Action<T> action, bool parallelizeActions)
{
ForEachRetry(source, action, 10, TimeSpan.FromSeconds(1), parallelizeActions);
}
/// <summary>
/// TRuns the <paramref name="action"/> on each item in the <paramref name="source"/> in parallel
/// </summary>
/// <param name="source">
/// The source collection of items.
/// </param>
/// <param name="action">
/// The action to process of the item.
/// </param>
/// <param name="retryCount">
/// TThe number of retries.
/// </param>
/// <param name="parallelizeActions">set to true to enable parallel processing</param>
/// <typeparam name="T">The type of items in the <paramref name="source"/>.</typeparam>
/// <returns>
/// Returns <b>true</b> when all items processed successfully.</returns>
public static void ForEachRetry<T>(this IEnumerable<T> source, Action<T> action, int retryCount, bool parallelizeActions)
{
ForEachRetry(source, action, retryCount, TimeSpan.FromSeconds(1), parallelizeActions);
}
/// <summary>
/// TRuns the <paramref name="action"/> on each item in the <paramref name="source"/> in parallel
/// </summary>
/// <param name="source">
/// The source collection of items.
/// </param>
/// <param name="action">
/// The action to process of the item.
/// </param>
/// <param name="retryCount">
/// TThe number of retries.
/// </param>
/// <param name="retryInterval">
/// The delay between retries.
/// </param>
/// <param name="parallelizeActions">set to true to enable parallel processing</param>
/// <typeparam name="T">The type of items in the <paramref name="source"/>.</typeparam>
/// <returns>
/// Returns <b>true</b> when all items processed successfully.</returns>
public static void ForEachRetry<T>(this IEnumerable<T> source, Action<T> action, int retryCount, TimeSpan retryInterval, bool parallelizeActions)
{
var fails = new ConcurrentBag<Exception>();
source.ForEach(
item =>
{
List<Exception> exceptions = null;
for (var i = 0; i < retryCount; i++)
{
if (i != 0)
{
Thread.Sleep(retryInterval);
}
try
{
action(item);
return;
}
catch (Exception e)
{
Trace.TraceError("The action is failing: {0}", e.Message);
if (exceptions == null)
{
exceptions = new List<Exception>();
}
exceptions.Add(e);
}
}
if (exceptions != null)
{
fails.Add(new AggregateException(exceptions));
}
}, parallelizeActions);
if (fails.Count > 0)
{
throw new AggregateException(fails);
}
}
}
}
| 35.887363 | 153 | 0.519253 | [
"Apache-2.0"
] | AndradeMatheus/git-tfs | src/GitTfs/Core/Ext.cs | 13,063 | C# |
global using System;
global using System.Collections.Generic;
global using System.Linq; | 29.333333 | 40 | 0.829545 | [
"MIT"
] | egorozh/Chilite | src/Frontend/Mobile/maui/Chilite.MobileClient/GlobalUsings.cs | 90 | C# |
// <auto-generated>
// 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.
// </auto-generated>
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// BackupResourceVaultConfigsOperations operations.
/// </summary>
public partial interface IBackupResourceVaultConfigsOperations
{
/// <summary>
/// Fetches resource vault config.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </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<BackupResourceVaultConfigResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates vault security config.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='parameters'>
/// resource config request
/// </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<BackupResourceVaultConfigResource>> UpdateWithHttpMessagesAsync(string vaultName, string resourceGroupName, BackupResourceVaultConfigResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 42.843373 | 311 | 0.646513 | [
"MIT"
] | 0xced/azure-sdk-for-net | src/SDKs/RecoveryServices.Backup/Management.RecoveryServices.Backup/Generated/IBackupResourceVaultConfigsOperations.cs | 3,556 | C# |
using System.IO;
using System.Runtime.Serialization;
using System.Xml.Linq;
using Revenj.Extensibility;
namespace Revenj.Serialization
{
public static class Setup
{
public static void ConfigureSerialization(this IObjectFactoryBuilder builder)
{
builder.RegisterType<GenericDataContractResolver>(InstanceScope.Singleton);
builder.RegisterType(typeof(XmlSerialization), InstanceScope.Singleton, false, typeof(ISerialization<XElement>));
builder.RegisterType<GenericDeserializationBinder, GenericDeserializationBinder, SerializationBinder>(InstanceScope.Singleton);
builder.RegisterType(typeof(BinarySerialization), InstanceScope.Singleton, false, typeof(ISerialization<byte[]>));
builder.RegisterType(typeof(JsonSerialization), InstanceScope.Singleton, false, typeof(ISerialization<string>), typeof(ISerialization<TextReader>));
builder.RegisterType(typeof(ProtobufSerialization), InstanceScope.Singleton, false, typeof(ISerialization<MemoryStream>), typeof(ISerialization<Stream>));
builder.RegisterType(typeof(PassThroughSerialization), InstanceScope.Singleton, false, typeof(ISerialization<object>));
builder.RegisterType<WireSerialization, IWireSerialization>(InstanceScope.Singleton);
}
}
}
| 54.391304 | 158 | 0.811351 | [
"BSD-3-Clause"
] | hperadin/revenj | csharp/Core/Revenj.Serialization/Setup.cs | 1,253 | C# |
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System.Collections.Generic;
using EnsureThat;
using Newtonsoft.Json;
namespace Microsoft.Health.Fhir.Core.Features.Operations.Export.Models
{
public class ExportJobProgress
{
public ExportJobProgress(string continuationToken, uint page, string resourceId = null, ExportJobProgress subSearch = null, ExportJobFilter filter = null)
{
ContinuationToken = continuationToken;
Page = page;
TriggeringResourceId = resourceId;
SubSearch = subSearch;
CurrentFilter = filter;
CompletedFilters = new List<ExportJobFilter>();
}
[JsonConstructor]
protected ExportJobProgress()
{
}
[JsonProperty(JobRecordProperties.Query)]
public string ContinuationToken { get; private set; }
[JsonProperty(JobRecordProperties.Page)]
public uint Page { get; private set; }
/// <summary>
/// The filter currently being evaluated.
/// </summary>
[JsonProperty(JobRecordProperties.CurrentFilter)]
public ExportJobFilter CurrentFilter { get; private set; }
/// <summary>
/// Indicates if all the filters for the job have been evaluated.
/// </summary>
[JsonProperty(JobRecordProperties.FilteredSearchesComplete)]
public List<ExportJobFilter> CompletedFilters { get; private set; }
[JsonProperty(JobRecordProperties.TriggeringResourceId)]
public string TriggeringResourceId { get; private set; }
[JsonProperty(JobRecordProperties.SubSearch)]
public ExportJobProgress SubSearch { get; private set; }
public void UpdateContinuationToken(string continuationToken)
{
EnsureArg.IsNotNullOrWhiteSpace(continuationToken, nameof(continuationToken));
ContinuationToken = continuationToken;
Page++;
}
public void SetFilter(ExportJobFilter filter)
{
if (CurrentFilter != null)
{
CompletedFilters.Add(CurrentFilter);
}
CurrentFilter = filter;
Page = 0;
ContinuationToken = null;
}
public void MarkFilterFinished()
{
SetFilter(null);
}
public void NewSubSearch(string resourceId)
{
EnsureArg.IsNotNullOrWhiteSpace(resourceId, nameof(resourceId));
SubSearch = new ExportJobProgress(null, 0, resourceId);
}
public void ClearSubSearch()
{
SubSearch = null;
}
}
}
| 32.304348 | 162 | 0.584455 | [
"MIT"
] | 10thmagnitude/fhir-server | src/Microsoft.Health.Fhir.Core/Features/Operations/Export/Models/ExportJobProgress.cs | 2,974 | C# |
namespace Hookr.Telegram.Operations.Commands.Administration.Hookahs.Photos
{
public static class Constants
{
public const string ProductCacheKeyFormat = "shp{0}";
}
} | 26.714286 | 75 | 0.721925 | [
"Apache-2.0"
] | mrlldd/hookr-rent-service | Hookr/Hookr.Telegram/Operations/Commands/Administration/Hookahs/Photos/Constants.cs | 189 | C# |
// -----------------------------------------------------------------------
// <copyright file="AuditController.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Explorer.Controllers
{
using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using Models;
using Providers;
using Security;
/// <summary>
/// Controller for Audit views.
/// </summary>
/// <seealso cref="System.Web.Mvc.Controller" />
[AuthorizationFilter(Roles = UserRoles.Partner)]
public class AuditController : BaseController
{
/// <summary>
/// Initializes a new instance of the <see cref="AuditController"/> class.
/// </summary>
/// <param name="service">Provides access to core services.</param>
public AuditController(IExplorerProvider provider) : base(provider)
{
}
/// <summary>
/// Get the audit records for the specified date range using the Partner Center API.
/// </summary>
/// <param name="endDate">The end date of the audit record logs.</param>
/// <param name="startDate">The start date of the audit record logs.</param>
/// <returns>A partial view containing the requested audit record logs.</returns>
public async Task<PartialViewResult> GetRecords(DateTime endDate, DateTime startDate)
{
AuditRecordsModel auditRecordsModel = new AuditRecordsModel()
{
Records = await Provider.PartnerOperations.GetAuditRecordsAsync(startDate, endDate).ConfigureAwait(false)
};
return PartialView("Records", auditRecordsModel);
}
/// <summary>
/// Handles the request for the Search view.
/// </summary>
/// <returns>Returns an empty view.</returns>
public ActionResult Search()
{
return View();
}
}
} | 36.982143 | 121 | 0.577982 | [
"MIT"
] | Bhaskers-Blu-Org2/Partner-Center-Explorer | src/Explorer/Controllers/AuditController.cs | 2,073 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Signum.Utilities;
using Signum.Entities.DynamicQuery;
using System.Threading;
using System.Collections.Concurrent;
using System.Globalization;
using Signum.Entities.Authorization;
using Signum.Entities.UserAssets;
using Newtonsoft.Json;
namespace Signum.Entities.Omnibox
{
public static class OmniboxParser
{
static OmniboxManager manager;
public static OmniboxManager Manager
{
get
{
if (manager == null)
throw new InvalidOperationException("OmniboxParse.Manager is not set");
return manager;
}
set { manager = value; }
}
public static List<IOmniboxResultGenerator> Generators = new List<IOmniboxResultGenerator>();
static string ident = @"[_\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}][\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}]*";
static string guid = @"[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}";
static string symbol = @"[\.\,;!?@#$%&/\\\(\)\^\*\[\]\{\}\-+]";
static readonly Regex tokenizer = new Regex(
$@"(?<entity>{ident};(\d+|{guid}))|
(?<space>\s+)|
(?<guid>{guid})|
(?<ident>{ident})|
(?<ident>\[{ident}\])|
(?<number>[+-]?\d+(\.\d+)?)|
(?<string>("".*?(""|$)|\'.*?(\'|$)))|
(?<comparer>({ FilterValueConverter.OperationRegex}))|
(?<symbol>{symbol})",
RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
public static int MaxResults = 20;
public static List<OmniboxResult> Results(string omniboxQuery, CancellationToken ct)
{
List<OmniboxResult> result = new List<OmniboxResult>();
if (omniboxQuery == "")
{
result.Add(new HelpOmniboxResult { Text = OmniboxMessage.Omnibox_OmniboxSyntaxGuide.NiceToString() });
foreach (var generator in Generators)
{
if (ct.IsCancellationRequested)
return result;
result.AddRange(generator.GetHelp());
}
result.Add(new HelpOmniboxResult { Text = OmniboxMessage.Omnibox_MatchingOptions.NiceToString() });
result.Add(new HelpOmniboxResult { Text = OmniboxMessage.Omnibox_DatabaseAccess.NiceToString() });
result.Add(new HelpOmniboxResult { Text = OmniboxMessage.Omnibox_Disambiguate.NiceToString() });
return result.ToList();
}
else
{
List<OmniboxToken> tokens = new List<OmniboxToken>();
foreach (Match m in tokenizer.Matches(omniboxQuery).Cast<Match>())
{
if (ct.IsCancellationRequested)
return result;
AddTokens(tokens, m, "ident", OmniboxTokenType.Identifier);
AddTokens(tokens, m, "symbol", OmniboxTokenType.Symbol);
AddTokens(tokens, m, "comparer", OmniboxTokenType.Comparer);
AddTokens(tokens, m, "number", OmniboxTokenType.Number);
AddTokens(tokens, m, "guid", OmniboxTokenType.Guid);
AddTokens(tokens, m, "string", OmniboxTokenType.String);
AddTokens(tokens, m, "entity", OmniboxTokenType.Entity);
}
tokens.Sort(a => a.Index);
var tokenPattern = new string(tokens.Select(t => t.Char()).ToArray());
foreach (var generator in Generators)
{
if (ct.IsCancellationRequested)
return result;
result.AddRange(generator.GetResults(omniboxQuery, tokens, tokenPattern).Take(MaxResults));
}
return result.OrderBy(a => a.Distance).Take(MaxResults).ToList();
}
}
static void AddTokens(List<OmniboxToken> tokens, Match m, string groupName, OmniboxTokenType type)
{
var group = m.Groups[groupName];
if (group.Success)
{
tokens.Add(new OmniboxToken(type, group.Index, group.Value));
}
}
public static string ToOmniboxPascal(this string text)
{
var simple = Regex.Replace(text, OmniboxMessage.ComplementWordsRegex.NiceToString(), m => "", RegexOptions.IgnoreCase);
var result = simple.ToPascal();
if (text.StartsWith("[") && text.EndsWith("]"))
return "[" + result + "]";
return result;
}
public static Dictionary<string, V> ToOmniboxPascalDictionary<T, V>(this IEnumerable<T> collection, Func<T, string> getKey, Func<T, V> getValue)
{
Dictionary<string, V> result = new Dictionary<string, V>();
foreach (var item in collection)
{
var key = getKey(item).ToOmniboxPascal();
if (result.ContainsKey(key))
{
for (int i = 1; ; i++)
{
var newKey = key + $"(Duplicated{(i == 1 ? "" : (" " + i.ToString()))}!)";
if (!result.ContainsKey(newKey))
{
key = newKey;
break;
}
}
}
result.Add(key, getValue(item));
}
return result;
}
}
public abstract class OmniboxManager
{
public abstract bool AllowedType(Type type);
public abstract bool AllowedPermission(PermissionSymbol permission);
public abstract bool AllowedQuery(object queryName);
public abstract QueryDescription GetDescription(object queryName);
public abstract Lite<Entity>? RetrieveLite(Type type, PrimaryKey id);
public List<Lite<Entity>> Autocomplete(Type type, string subString, int count)
{
return Autocomplete(Implementations.By(type), subString, count);
}
public abstract List<Lite<Entity>> Autocomplete(Implementations implementations, string subString, int count);
protected abstract IEnumerable<object> GetAllQueryNames();
static ConcurrentDictionary<CultureInfo, Dictionary<string, object>> queries = new ConcurrentDictionary<CultureInfo, Dictionary<string, object>>();
public Dictionary<string, object> GetQueries()
{
return queries.GetOrAdd(CultureInfo.CurrentCulture, ci =>
GetAllQueryNames().ToOmniboxPascalDictionary(qn => QueryUtils.GetNiceName(qn), qn => qn));
}
protected abstract IEnumerable<Type> GetAllTypes();
static ConcurrentDictionary<CultureInfo, Dictionary<string, Type>> types = new ConcurrentDictionary<CultureInfo, Dictionary<string, Type>>();
public Dictionary<string, Type> Types()
{
return types.GetOrAdd(CultureInfo.CurrentUICulture, ci =>
GetAllTypes().Where(t => !t.IsEnumEntityOrSymbol()).ToOmniboxPascalDictionary(t => t.NicePluralName(), t => t));
}
}
public abstract class OmniboxResult
{
public float Distance;
public string ResultTypeName => GetType().Name;
}
public class HelpOmniboxResult : OmniboxResult
{
public string Text { get; set; }
[JsonIgnore]
public Type ReferencedType { get; set; }
public string? ReferencedTypeName => this.ReferencedType?.Name;
public override string ToString()
{
return "";
}
}
public interface IOmniboxResultGenerator
{
IEnumerable<OmniboxResult> GetResults(string rawQuery, List<OmniboxToken> tokens, string tokenPattern);
List<HelpOmniboxResult> GetHelp();
}
public abstract class OmniboxResultGenerator<T> : IOmniboxResultGenerator where T : OmniboxResult
{
public abstract IEnumerable<T> GetResults(string rawQuery, List<OmniboxToken> tokens, string tokenPattern);
IEnumerable<OmniboxResult> IOmniboxResultGenerator.GetResults(string rawQuery, List<OmniboxToken> tokens, string tokenPattern)
{
return GetResults(rawQuery, tokens, tokenPattern);
}
public abstract List<HelpOmniboxResult> GetHelp();
}
public struct OmniboxToken
{
public OmniboxToken(OmniboxTokenType type, int index, string value)
{
this.Type = type;
this.Index = index;
this.Value = value;
}
public readonly OmniboxTokenType Type;
public readonly int Index;
public readonly string Value;
public bool IsNull()
{
if (Type == OmniboxTokenType.Identifier)
return Value == "null" || Value == "none";
if (Type == OmniboxTokenType.String)
return Value == "\"\"";
return false;
}
internal char? Next(string rawQuery)
{
int last = Index + Value.Length;
if (last < rawQuery.Length)
return rawQuery[last];
return null;
}
internal char Char()
{
switch (Type)
{
case OmniboxTokenType.Identifier: return 'I';
case OmniboxTokenType.Symbol: return Value.Single();
case OmniboxTokenType.Comparer: return '=';
case OmniboxTokenType.Number: return 'N';
case OmniboxTokenType.String: return 'S';
case OmniboxTokenType.Entity: return 'E';
case OmniboxTokenType.Guid: return 'G';
default: return '?';
}
}
}
public enum OmniboxTokenType
{
Identifier,
Symbol,
Comparer,
Number,
String,
Entity,
Guid,
}
}
| 34.851852 | 156 | 0.55357 | [
"MIT"
] | ControlExpert/extensions | Signum.Entities.Extensions/Omnibox/OmniboxParser.cs | 10,351 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
namespace Squidex.Infrastructure.Orleans.Indexes
{
public class UniqueNameGrain<T> : GrainOfString, IUniqueNameGrain<T>
{
private readonly Dictionary<string, (string Name, T Id)> reservations = new Dictionary<string, (string Name, T Id)>();
public Task<string?> ReserveAsync(T id, string name)
{
string? token = null;
var reservation = reservations.FirstOrDefault(x => x.Value.Name == name);
if (Equals(reservation.Value.Id, id))
{
token = reservation.Key;
}
else if (reservation.Key == null)
{
token = RandomHash.Simple();
reservations.Add(token, (name, id));
}
return Task.FromResult(token);
}
public Task RemoveReservationAsync(string? token)
{
reservations.Remove(token ?? string.Empty);
return Task.CompletedTask;
}
}
}
| 32.119048 | 126 | 0.475908 | [
"MIT"
] | MartijnDijkgraaf/squidex | backend/src/Squidex.Infrastructure/Orleans/Indexes/UniqueNameGrain.cs | 1,351 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Catalog.API.Data;
using Catalog.API.Entities;
using MongoDB.Driver;
namespace Catalog.API.Repository
{
public class ProductRepository : IProductRepository
{
private readonly ICatalogContext _context;
public ProductRepository(ICatalogContext context)
{
_context = context;
}
public async Task<IEnumerable<Product>> GetProducts()
{
return await _context.Products.Find(p => true).ToListAsync();
}
public async Task<Product> GetProduct(string id)
{
return await _context.Products.Find(p => p.Id == id).FirstOrDefaultAsync();
}
public async Task<IEnumerable<Product>> GetProductByName(string name)
{
FilterDefinition<Product> filter = Builders<Product>.Filter.Eq(p => p.Name, name);
return await _context.Products.Find(filter).ToListAsync();
}
public async Task<IEnumerable<Product>> GetProductByCategory(string category)
{
FilterDefinition<Product> filter = Builders<Product>.Filter.Eq(p => p.Category, category);
return await _context.Products.Find(filter).ToListAsync();
}
public async Task CreateProduct(Product product)
{
await _context.Products.InsertOneAsync(product);
}
public async Task<bool> UpdateProduct(Product product)
{
var updateResult = await _context.Products.ReplaceOneAsync(g => g.Id == product.Id, product);
return updateResult.IsAcknowledged && updateResult.MatchedCount > 0;
}
public async Task<bool> DeleteProduct(string id)
{
FilterDefinition<Product> filter = Builders<Product>.Filter.Eq(p => p.Id, id);
DeleteResult deleteResult = await _context.Products.DeleteOneAsync(filter);
return deleteResult.IsAcknowledged && deleteResult.DeletedCount > 0;
}
}
} | 32.31746 | 105 | 0.641454 | [
"MIT"
] | JThurling/AspnetMicroservices | src/Services/Catalog/Catalog.API/Repository/ProductRepository.cs | 2,038 | C# |
/*
* Copyright (c) 2018, FusionAuth, All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
using io.fusionauth.domain;
using System.Collections.Generic;
using System;
namespace io.fusionauth.domain.@event {
/**
* Models the User Create Event (and can be converted to JSON).
*
* @author Brian Pontarelli
*/
public class UserCreateEvent: BaseEvent {
public User user;
public UserCreateEvent with(Action<UserCreateEvent> action) {
action(this);
return this;
}
}
}
| 26.564103 | 68 | 0.715251 | [
"Apache-2.0"
] | FusionAuth/fusionauth-netcore-client | fusionauth-netcore-client/domain/io/fusionauth/domain/event/UserCreateEvent.cs | 1,036 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
#pragma warning disable 1591
namespace PUB_ZIK {
/// <summary>
///Represents a strongly typed in-memory cache of data.
///</summary>
[global::System.Serializable()]
[global::System.ComponentModel.DesignerCategoryAttribute("code")]
[global::System.ComponentModel.ToolboxItem(true)]
[global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema")]
[global::System.Xml.Serialization.XmlRootAttribute("PUBReferences")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")]
public partial class PUBReferences : global::System.Data.DataSet {
private НалогиФОПDataTable tableНалогиФОП;
private global::System.Data.SchemaSerializationMode _schemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public PUBReferences() {
this.BeginInit();
this.InitClass();
global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
base.Tables.CollectionChanged += schemaChangedHandler;
base.Relations.CollectionChanged += schemaChangedHandler;
this.EndInit();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
protected PUBReferences(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) :
base(info, context, false) {
if ((this.IsBinarySerialized(info, context) == true)) {
this.InitVars(false);
global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler1 = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
this.Tables.CollectionChanged += schemaChangedHandler1;
this.Relations.CollectionChanged += schemaChangedHandler1;
return;
}
string strSchema = ((string)(info.GetValue("XmlSchema", typeof(string))));
if ((this.DetermineSchemaSerializationMode(info, context) == global::System.Data.SchemaSerializationMode.IncludeSchema)) {
global::System.Data.DataSet ds = new global::System.Data.DataSet();
ds.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema)));
if ((ds.Tables["НалогиФОП"] != null)) {
base.Tables.Add(new НалогиФОПDataTable(ds.Tables["НалогиФОП"]));
}
this.DataSetName = ds.DataSetName;
this.Prefix = ds.Prefix;
this.Namespace = ds.Namespace;
this.Locale = ds.Locale;
this.CaseSensitive = ds.CaseSensitive;
this.EnforceConstraints = ds.EnforceConstraints;
this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add);
this.InitVars();
}
else {
this.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema)));
}
this.GetSerializationData(info, context);
global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
base.Tables.CollectionChanged += schemaChangedHandler;
this.Relations.CollectionChanged += schemaChangedHandler;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
[global::System.ComponentModel.Browsable(false)]
[global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)]
public НалогиФОПDataTable НалогиФОП {
get {
return this.tableНалогиФОП;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
[global::System.ComponentModel.BrowsableAttribute(true)]
[global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Visible)]
public override global::System.Data.SchemaSerializationMode SchemaSerializationMode {
get {
return this._schemaSerializationMode;
}
set {
this._schemaSerializationMode = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
[global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public new global::System.Data.DataTableCollection Tables {
get {
return base.Tables;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
[global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public new global::System.Data.DataRelationCollection Relations {
get {
return base.Relations;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
protected override void InitializeDerivedDataSet() {
this.BeginInit();
this.InitClass();
this.EndInit();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public override global::System.Data.DataSet Clone() {
PUBReferences cln = ((PUBReferences)(base.Clone()));
cln.InitVars();
cln.SchemaSerializationMode = this.SchemaSerializationMode;
return cln;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
protected override bool ShouldSerializeTables() {
return false;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
protected override bool ShouldSerializeRelations() {
return false;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
protected override void ReadXmlSerializable(global::System.Xml.XmlReader reader) {
if ((this.DetermineSchemaSerializationMode(reader) == global::System.Data.SchemaSerializationMode.IncludeSchema)) {
this.Reset();
global::System.Data.DataSet ds = new global::System.Data.DataSet();
ds.ReadXml(reader);
if ((ds.Tables["НалогиФОП"] != null)) {
base.Tables.Add(new НалогиФОПDataTable(ds.Tables["НалогиФОП"]));
}
this.DataSetName = ds.DataSetName;
this.Prefix = ds.Prefix;
this.Namespace = ds.Namespace;
this.Locale = ds.Locale;
this.CaseSensitive = ds.CaseSensitive;
this.EnforceConstraints = ds.EnforceConstraints;
this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add);
this.InitVars();
}
else {
this.ReadXml(reader);
this.InitVars();
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
protected override global::System.Xml.Schema.XmlSchema GetSchemaSerializable() {
global::System.IO.MemoryStream stream = new global::System.IO.MemoryStream();
this.WriteXmlSchema(new global::System.Xml.XmlTextWriter(stream, null));
stream.Position = 0;
return global::System.Xml.Schema.XmlSchema.Read(new global::System.Xml.XmlTextReader(stream), null);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
internal void InitVars() {
this.InitVars(true);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
internal void InitVars(bool initTable) {
this.tableНалогиФОП = ((НалогиФОПDataTable)(base.Tables["НалогиФОП"]));
if ((initTable == true)) {
if ((this.tableНалогиФОП != null)) {
this.tableНалогиФОП.InitVars();
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
private void InitClass() {
this.DataSetName = "PUBReferences";
this.Prefix = "";
this.Namespace = "http://tempuri.org/PUBReferences.xsd";
this.EnforceConstraints = true;
this.SchemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema;
this.tableНалогиФОП = new НалогиФОПDataTable();
base.Tables.Add(this.tableНалогиФОП);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
private bool ShouldSerializeНалогиФОП() {
return false;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
private void SchemaChanged(object sender, global::System.ComponentModel.CollectionChangeEventArgs e) {
if ((e.Action == global::System.ComponentModel.CollectionChangeAction.Remove)) {
this.InitVars();
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs) {
PUBReferences ds = new PUBReferences();
global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType();
global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence();
global::System.Xml.Schema.XmlSchemaAny any = new global::System.Xml.Schema.XmlSchemaAny();
any.Namespace = ds.Namespace;
sequence.Items.Add(any);
type.Particle = sequence;
global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
if (xs.Contains(dsSchema.TargetNamespace)) {
global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
try {
global::System.Xml.Schema.XmlSchema schema = null;
dsSchema.Write(s1);
for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) {
schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
s2.SetLength(0);
schema.Write(s2);
if ((s1.Length == s2.Length)) {
s1.Position = 0;
s2.Position = 0;
for (; ((s1.Position != s1.Length)
&& (s1.ReadByte() == s2.ReadByte())); ) {
;
}
if ((s1.Position == s1.Length)) {
return type;
}
}
}
}
finally {
if ((s1 != null)) {
s1.Close();
}
if ((s2 != null)) {
s2.Close();
}
}
}
xs.Add(dsSchema);
return type;
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public delegate void НалогиФОПRowChangeEventHandler(object sender, НалогиФОПRowChangeEvent e);
/// <summary>
///Represents the strongly named DataTable class.
///</summary>
[global::System.Serializable()]
[global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")]
public partial class НалогиФОПDataTable : global::System.Data.TypedTableBase<НалогиФОПRow> {
private global::System.Data.DataColumn columnID;
private global::System.Data.DataColumn columnPeriod;
private global::System.Data.DataColumn columnIDIndex;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public НалогиФОПDataTable() {
this.TableName = "НалогиФОП";
this.BeginInit();
this.InitClass();
this.EndInit();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
internal НалогиФОПDataTable(global::System.Data.DataTable table) {
this.TableName = table.TableName;
if ((table.CaseSensitive != table.DataSet.CaseSensitive)) {
this.CaseSensitive = table.CaseSensitive;
}
if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) {
this.Locale = table.Locale;
}
if ((table.Namespace != table.DataSet.Namespace)) {
this.Namespace = table.Namespace;
}
this.Prefix = table.Prefix;
this.MinimumCapacity = table.MinimumCapacity;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
protected НалогиФОПDataTable(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) :
base(info, context) {
this.InitVars();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public global::System.Data.DataColumn IDColumn {
get {
return this.columnID;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public global::System.Data.DataColumn PeriodColumn {
get {
return this.columnPeriod;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public global::System.Data.DataColumn IDIndexColumn {
get {
return this.columnIDIndex;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
[global::System.ComponentModel.Browsable(false)]
public int Count {
get {
return this.Rows.Count;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public НалогиФОПRow this[int index] {
get {
return ((НалогиФОПRow)(this.Rows[index]));
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public event НалогиФОПRowChangeEventHandler НалогиФОПRowChanging;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public event НалогиФОПRowChangeEventHandler НалогиФОПRowChanged;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public event НалогиФОПRowChangeEventHandler НалогиФОПRowDeleting;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public event НалогиФОПRowChangeEventHandler НалогиФОПRowDeleted;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public void AddНалогиФОПRow(НалогиФОПRow row) {
this.Rows.Add(row);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public НалогиФОПRow AddНалогиФОПRow(int ID, System.DateTime Period, string IDIndex) {
НалогиФОПRow rowНалогиФОПRow = ((НалогиФОПRow)(this.NewRow()));
object[] columnValuesArray = new object[] {
ID,
Period,
IDIndex};
rowНалогиФОПRow.ItemArray = columnValuesArray;
this.Rows.Add(rowНалогиФОПRow);
return rowНалогиФОПRow;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public НалогиФОПRow FindByID(int ID) {
return ((НалогиФОПRow)(this.Rows.Find(new object[] {
ID})));
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public override global::System.Data.DataTable Clone() {
НалогиФОПDataTable cln = ((НалогиФОПDataTable)(base.Clone()));
cln.InitVars();
return cln;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
protected override global::System.Data.DataTable CreateInstance() {
return new НалогиФОПDataTable();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
internal void InitVars() {
this.columnID = base.Columns["ID"];
this.columnPeriod = base.Columns["Period"];
this.columnIDIndex = base.Columns["IDIndex"];
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
private void InitClass() {
this.columnID = new global::System.Data.DataColumn("ID", typeof(int), null, global::System.Data.MappingType.Element);
base.Columns.Add(this.columnID);
this.columnPeriod = new global::System.Data.DataColumn("Period", typeof(global::System.DateTime), null, global::System.Data.MappingType.Element);
base.Columns.Add(this.columnPeriod);
this.columnIDIndex = new global::System.Data.DataColumn("IDIndex", typeof(string), null, global::System.Data.MappingType.Element);
base.Columns.Add(this.columnIDIndex);
this.Constraints.Add(new global::System.Data.UniqueConstraint("НалогиФОПKey1", new global::System.Data.DataColumn[] {
this.columnID}, true));
this.columnID.AllowDBNull = false;
this.columnID.Unique = true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public НалогиФОПRow NewНалогиФОПRow() {
return ((НалогиФОПRow)(this.NewRow()));
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
protected override global::System.Data.DataRow NewRowFromBuilder(global::System.Data.DataRowBuilder builder) {
return new НалогиФОПRow(builder);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
protected override global::System.Type GetRowType() {
return typeof(НалогиФОПRow);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
protected override void OnRowChanged(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowChanged(e);
if ((this.НалогиФОПRowChanged != null)) {
this.НалогиФОПRowChanged(this, new НалогиФОПRowChangeEvent(((НалогиФОПRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
protected override void OnRowChanging(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowChanging(e);
if ((this.НалогиФОПRowChanging != null)) {
this.НалогиФОПRowChanging(this, new НалогиФОПRowChangeEvent(((НалогиФОПRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
protected override void OnRowDeleted(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowDeleted(e);
if ((this.НалогиФОПRowDeleted != null)) {
this.НалогиФОПRowDeleted(this, new НалогиФОПRowChangeEvent(((НалогиФОПRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
protected override void OnRowDeleting(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowDeleting(e);
if ((this.НалогиФОПRowDeleting != null)) {
this.НалогиФОПRowDeleting(this, new НалогиФОПRowChangeEvent(((НалогиФОПRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public void RemoveНалогиФОПRow(НалогиФОПRow row) {
this.Rows.Remove(row);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) {
global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType();
global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence();
PUBReferences ds = new PUBReferences();
global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny();
any1.Namespace = "http://www.w3.org/2001/XMLSchema";
any1.MinOccurs = new decimal(0);
any1.MaxOccurs = decimal.MaxValue;
any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
sequence.Items.Add(any1);
global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny();
any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1";
any2.MinOccurs = new decimal(1);
any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
sequence.Items.Add(any2);
global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute();
attribute1.Name = "namespace";
attribute1.FixedValue = ds.Namespace;
type.Attributes.Add(attribute1);
global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute();
attribute2.Name = "tableTypeName";
attribute2.FixedValue = "НалогиФОПDataTable";
type.Attributes.Add(attribute2);
type.Particle = sequence;
global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
if (xs.Contains(dsSchema.TargetNamespace)) {
global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
try {
global::System.Xml.Schema.XmlSchema schema = null;
dsSchema.Write(s1);
for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) {
schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
s2.SetLength(0);
schema.Write(s2);
if ((s1.Length == s2.Length)) {
s1.Position = 0;
s2.Position = 0;
for (; ((s1.Position != s1.Length)
&& (s1.ReadByte() == s2.ReadByte())); ) {
;
}
if ((s1.Position == s1.Length)) {
return type;
}
}
}
}
finally {
if ((s1 != null)) {
s1.Close();
}
if ((s2 != null)) {
s2.Close();
}
}
}
xs.Add(dsSchema);
return type;
}
}
/// <summary>
///Represents strongly named DataRow class.
///</summary>
public partial class НалогиФОПRow : global::System.Data.DataRow {
private НалогиФОПDataTable tableНалогиФОП;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
internal НалогиФОПRow(global::System.Data.DataRowBuilder rb) :
base(rb) {
this.tableНалогиФОП = ((НалогиФОПDataTable)(this.Table));
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public int ID {
get {
return ((int)(this[this.tableНалогиФОП.IDColumn]));
}
set {
this[this.tableНалогиФОП.IDColumn] = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public System.DateTime Period {
get {
try {
return ((global::System.DateTime)(this[this.tableНалогиФОП.PeriodColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("The value for column \'Period\' in table \'НалогиФОП\' is DBNull.", e);
}
}
set {
this[this.tableНалогиФОП.PeriodColumn] = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public string IDIndex {
get {
try {
return ((string)(this[this.tableНалогиФОП.IDIndexColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("The value for column \'IDIndex\' in table \'НалогиФОП\' is DBNull.", e);
}
}
set {
this[this.tableНалогиФОП.IDIndexColumn] = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public bool IsPeriodNull() {
return this.IsNull(this.tableНалогиФОП.PeriodColumn);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public void SetPeriodNull() {
this[this.tableНалогиФОП.PeriodColumn] = global::System.Convert.DBNull;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public bool IsIDIndexNull() {
return this.IsNull(this.tableНалогиФОП.IDIndexColumn);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public void SetIDIndexNull() {
this[this.tableНалогиФОП.IDIndexColumn] = global::System.Convert.DBNull;
}
}
/// <summary>
///Row event argument class
///</summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public class НалогиФОПRowChangeEvent : global::System.EventArgs {
private НалогиФОПRow eventRow;
private global::System.Data.DataRowAction eventAction;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public НалогиФОПRowChangeEvent(НалогиФОПRow row, global::System.Data.DataRowAction action) {
this.eventRow = row;
this.eventAction = action;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public НалогиФОПRow Row {
get {
return this.eventRow;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
public global::System.Data.DataRowAction Action {
get {
return this.eventAction;
}
}
}
}
}
#pragma warning restore 1591 | 54.185567 | 182 | 0.593064 | [
"MIT"
] | sabatex/PUB_ZIK | Source/PUBReferences.Designer.cs | 37,703 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BalloonsPops
{
class Program
{
static void Main(string[] args)
{
igra.Start();
}
}
}
| 11.647059 | 33 | 0.686869 | [
"MIT"
] | ElenaStaykova/High-Quality-Code | Teamwork/Baloons-Pop/Baloons-Pop-2/Program.cs | 200 | C# |
// 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.PowerShell.Cmdlets.Migrate.Models.Api20210210
{
using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions;
/// <summary>Details of a Master Target Server.</summary>
public partial class MasterTargetServer :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IMasterTargetServer,
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IMasterTargetServerInternal
{
/// <summary>Backing field for <see cref="AgentExpiryDate" /> property.</summary>
private global::System.DateTime? _agentExpiryDate;
/// <summary>Agent expiry date.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public global::System.DateTime? AgentExpiryDate { get => this._agentExpiryDate; set => this._agentExpiryDate = value; }
/// <summary>Backing field for <see cref="AgentVersion" /> property.</summary>
private string _agentVersion;
/// <summary>The version of the scout component on the server.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string AgentVersion { get => this._agentVersion; set => this._agentVersion = value; }
/// <summary>Backing field for <see cref="AgentVersionDetail" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetails _agentVersionDetail;
/// <summary>Agent version details.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
internal Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetails AgentVersionDetail { get => (this._agentVersionDetail = this._agentVersionDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.VersionDetails()); set => this._agentVersionDetail = value; }
/// <summary>Version expiry date.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inlined)]
public global::System.DateTime? AgentVersionDetailExpiryDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetailsInternal)AgentVersionDetail).ExpiryDate; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetailsInternal)AgentVersionDetail).ExpiryDate = value ?? default(global::System.DateTime); }
/// <summary>A value indicating whether security update required.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inlined)]
public Microsoft.Azure.PowerShell.Cmdlets.Migrate.Support.AgentVersionStatus? AgentVersionDetailStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetailsInternal)AgentVersionDetail).Status; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetailsInternal)AgentVersionDetail).Status = value ?? ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Support.AgentVersionStatus)""); }
/// <summary>The agent version.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inlined)]
public string AgentVersionDetailVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetailsInternal)AgentVersionDetail).Version; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetailsInternal)AgentVersionDetail).Version = value ?? null; }
/// <summary>Backing field for <see cref="DataStore" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IDataStore[] _dataStore;
/// <summary>The list of data stores in the fabric.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IDataStore[] DataStore { get => this._dataStore; set => this._dataStore = value; }
/// <summary>Backing field for <see cref="DiskCount" /> property.</summary>
private int? _diskCount;
/// <summary>Disk count of the master target.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public int? DiskCount { get => this._diskCount; set => this._diskCount = value; }
/// <summary>Backing field for <see cref="HealthError" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IHealthError[] _healthError;
/// <summary>Health errors.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IHealthError[] HealthError { get => this._healthError; set => this._healthError = value; }
/// <summary>Backing field for <see cref="IPAddress" /> property.</summary>
private string _iPAddress;
/// <summary>The IP address of the server.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string IPAddress { get => this._iPAddress; set => this._iPAddress = value; }
/// <summary>Backing field for <see cref="Id" /> property.</summary>
private string _id;
/// <summary>The server Id.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string Id { get => this._id; set => this._id = value; }
/// <summary>Backing field for <see cref="LastHeartbeat" /> property.</summary>
private global::System.DateTime? _lastHeartbeat;
/// <summary>The last heartbeat received from the server.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public global::System.DateTime? LastHeartbeat { get => this._lastHeartbeat; set => this._lastHeartbeat = value; }
/// <summary>Version expiry date.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inlined)]
public global::System.DateTime? MarAgentVersionDetailExpiryDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetailsInternal)MarsAgentVersionDetail).ExpiryDate; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetailsInternal)MarsAgentVersionDetail).ExpiryDate = value ?? default(global::System.DateTime); }
/// <summary>A value indicating whether security update required.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inlined)]
public Microsoft.Azure.PowerShell.Cmdlets.Migrate.Support.AgentVersionStatus? MarAgentVersionDetailStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetailsInternal)MarsAgentVersionDetail).Status; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetailsInternal)MarsAgentVersionDetail).Status = value ?? ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Support.AgentVersionStatus)""); }
/// <summary>The agent version.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inlined)]
public string MarAgentVersionDetailVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetailsInternal)MarsAgentVersionDetail).Version; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetailsInternal)MarsAgentVersionDetail).Version = value ?? null; }
/// <summary>Backing field for <see cref="MarsAgentExpiryDate" /> property.</summary>
private global::System.DateTime? _marsAgentExpiryDate;
/// <summary>MARS agent expiry date.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public global::System.DateTime? MarsAgentExpiryDate { get => this._marsAgentExpiryDate; set => this._marsAgentExpiryDate = value; }
/// <summary>Backing field for <see cref="MarsAgentVersion" /> property.</summary>
private string _marsAgentVersion;
/// <summary>MARS agent version.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string MarsAgentVersion { get => this._marsAgentVersion; set => this._marsAgentVersion = value; }
/// <summary>Backing field for <see cref="MarsAgentVersionDetail" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetails _marsAgentVersionDetail;
/// <summary>Mars agent version details.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
internal Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetails MarsAgentVersionDetail { get => (this._marsAgentVersionDetail = this._marsAgentVersionDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.VersionDetails()); set => this._marsAgentVersionDetail = value; }
/// <summary>Internal Acessors for AgentVersionDetail</summary>
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetails Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IMasterTargetServerInternal.AgentVersionDetail { get => (this._agentVersionDetail = this._agentVersionDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.VersionDetails()); set { {_agentVersionDetail = value;} } }
/// <summary>Internal Acessors for MarsAgentVersionDetail</summary>
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetails Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IMasterTargetServerInternal.MarsAgentVersionDetail { get => (this._marsAgentVersionDetail = this._marsAgentVersionDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.VersionDetails()); set { {_marsAgentVersionDetail = value;} } }
/// <summary>Backing field for <see cref="Name" /> property.</summary>
private string _name;
/// <summary>The server name.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string Name { get => this._name; set => this._name = value; }
/// <summary>Backing field for <see cref="OSType" /> property.</summary>
private string _oSType;
/// <summary>The OS type of the server.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string OSType { get => this._oSType; set => this._oSType = value; }
/// <summary>Backing field for <see cref="OSVersion" /> property.</summary>
private string _oSVersion;
/// <summary>OS Version of the master target.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string OSVersion { get => this._oSVersion; set => this._oSVersion = value; }
/// <summary>Backing field for <see cref="RetentionVolume" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRetentionVolume[] _retentionVolume;
/// <summary>The retention volumes of Master target Server.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRetentionVolume[] RetentionVolume { get => this._retentionVolume; set => this._retentionVolume = value; }
/// <summary>Backing field for <see cref="ValidationError" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IHealthError[] _validationError;
/// <summary>Validation errors.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IHealthError[] ValidationError { get => this._validationError; set => this._validationError = value; }
/// <summary>Backing field for <see cref="VersionStatus" /> property.</summary>
private string _versionStatus;
/// <summary>Version status.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string VersionStatus { get => this._versionStatus; set => this._versionStatus = value; }
/// <summary>Creates an new <see cref="MasterTargetServer" /> instance.</summary>
public MasterTargetServer()
{
}
}
/// Details of a Master Target Server.
public partial interface IMasterTargetServer :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IJsonSerializable
{
/// <summary>Agent expiry date.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Agent expiry date.",
SerializedName = @"agentExpiryDate",
PossibleTypes = new [] { typeof(global::System.DateTime) })]
global::System.DateTime? AgentExpiryDate { get; set; }
/// <summary>The version of the scout component on the server.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The version of the scout component on the server.",
SerializedName = @"agentVersion",
PossibleTypes = new [] { typeof(string) })]
string AgentVersion { get; set; }
/// <summary>Version expiry date.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Version expiry date.",
SerializedName = @"expiryDate",
PossibleTypes = new [] { typeof(global::System.DateTime) })]
global::System.DateTime? AgentVersionDetailExpiryDate { get; set; }
/// <summary>A value indicating whether security update required.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"A value indicating whether security update required.",
SerializedName = @"status",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Support.AgentVersionStatus) })]
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Support.AgentVersionStatus? AgentVersionDetailStatus { get; set; }
/// <summary>The agent version.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The agent version.",
SerializedName = @"version",
PossibleTypes = new [] { typeof(string) })]
string AgentVersionDetailVersion { get; set; }
/// <summary>The list of data stores in the fabric.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The list of data stores in the fabric.",
SerializedName = @"dataStores",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IDataStore) })]
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IDataStore[] DataStore { get; set; }
/// <summary>Disk count of the master target.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Disk count of the master target.",
SerializedName = @"diskCount",
PossibleTypes = new [] { typeof(int) })]
int? DiskCount { get; set; }
/// <summary>Health errors.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Health errors.",
SerializedName = @"healthErrors",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IHealthError) })]
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IHealthError[] HealthError { get; set; }
/// <summary>The IP address of the server.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The IP address of the server.",
SerializedName = @"ipAddress",
PossibleTypes = new [] { typeof(string) })]
string IPAddress { get; set; }
/// <summary>The server Id.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The server Id.",
SerializedName = @"id",
PossibleTypes = new [] { typeof(string) })]
string Id { get; set; }
/// <summary>The last heartbeat received from the server.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The last heartbeat received from the server.",
SerializedName = @"lastHeartbeat",
PossibleTypes = new [] { typeof(global::System.DateTime) })]
global::System.DateTime? LastHeartbeat { get; set; }
/// <summary>Version expiry date.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Version expiry date.",
SerializedName = @"expiryDate",
PossibleTypes = new [] { typeof(global::System.DateTime) })]
global::System.DateTime? MarAgentVersionDetailExpiryDate { get; set; }
/// <summary>A value indicating whether security update required.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"A value indicating whether security update required.",
SerializedName = @"status",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Support.AgentVersionStatus) })]
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Support.AgentVersionStatus? MarAgentVersionDetailStatus { get; set; }
/// <summary>The agent version.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The agent version.",
SerializedName = @"version",
PossibleTypes = new [] { typeof(string) })]
string MarAgentVersionDetailVersion { get; set; }
/// <summary>MARS agent expiry date.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"MARS agent expiry date.",
SerializedName = @"marsAgentExpiryDate",
PossibleTypes = new [] { typeof(global::System.DateTime) })]
global::System.DateTime? MarsAgentExpiryDate { get; set; }
/// <summary>MARS agent version.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"MARS agent version.",
SerializedName = @"marsAgentVersion",
PossibleTypes = new [] { typeof(string) })]
string MarsAgentVersion { get; set; }
/// <summary>The server name.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The server name.",
SerializedName = @"name",
PossibleTypes = new [] { typeof(string) })]
string Name { get; set; }
/// <summary>The OS type of the server.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The OS type of the server.",
SerializedName = @"osType",
PossibleTypes = new [] { typeof(string) })]
string OSType { get; set; }
/// <summary>OS Version of the master target.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"OS Version of the master target.",
SerializedName = @"osVersion",
PossibleTypes = new [] { typeof(string) })]
string OSVersion { get; set; }
/// <summary>The retention volumes of Master target Server.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The retention volumes of Master target Server.",
SerializedName = @"retentionVolumes",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRetentionVolume) })]
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRetentionVolume[] RetentionVolume { get; set; }
/// <summary>Validation errors.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Validation errors.",
SerializedName = @"validationErrors",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IHealthError) })]
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IHealthError[] ValidationError { get; set; }
/// <summary>Version status.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Version status.",
SerializedName = @"versionStatus",
PossibleTypes = new [] { typeof(string) })]
string VersionStatus { get; set; }
}
/// Details of a Master Target Server.
internal partial interface IMasterTargetServerInternal
{
/// <summary>Agent expiry date.</summary>
global::System.DateTime? AgentExpiryDate { get; set; }
/// <summary>The version of the scout component on the server.</summary>
string AgentVersion { get; set; }
/// <summary>Agent version details.</summary>
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetails AgentVersionDetail { get; set; }
/// <summary>Version expiry date.</summary>
global::System.DateTime? AgentVersionDetailExpiryDate { get; set; }
/// <summary>A value indicating whether security update required.</summary>
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Support.AgentVersionStatus? AgentVersionDetailStatus { get; set; }
/// <summary>The agent version.</summary>
string AgentVersionDetailVersion { get; set; }
/// <summary>The list of data stores in the fabric.</summary>
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IDataStore[] DataStore { get; set; }
/// <summary>Disk count of the master target.</summary>
int? DiskCount { get; set; }
/// <summary>Health errors.</summary>
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IHealthError[] HealthError { get; set; }
/// <summary>The IP address of the server.</summary>
string IPAddress { get; set; }
/// <summary>The server Id.</summary>
string Id { get; set; }
/// <summary>The last heartbeat received from the server.</summary>
global::System.DateTime? LastHeartbeat { get; set; }
/// <summary>Version expiry date.</summary>
global::System.DateTime? MarAgentVersionDetailExpiryDate { get; set; }
/// <summary>A value indicating whether security update required.</summary>
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Support.AgentVersionStatus? MarAgentVersionDetailStatus { get; set; }
/// <summary>The agent version.</summary>
string MarAgentVersionDetailVersion { get; set; }
/// <summary>MARS agent expiry date.</summary>
global::System.DateTime? MarsAgentExpiryDate { get; set; }
/// <summary>MARS agent version.</summary>
string MarsAgentVersion { get; set; }
/// <summary>Mars agent version details.</summary>
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVersionDetails MarsAgentVersionDetail { get; set; }
/// <summary>The server name.</summary>
string Name { get; set; }
/// <summary>The OS type of the server.</summary>
string OSType { get; set; }
/// <summary>OS Version of the master target.</summary>
string OSVersion { get; set; }
/// <summary>The retention volumes of Master target Server.</summary>
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IRetentionVolume[] RetentionVolume { get; set; }
/// <summary>Validation errors.</summary>
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IHealthError[] ValidationError { get; set; }
/// <summary>Version status.</summary>
string VersionStatus { get; set; }
}
} | 65.019324 | 459 | 0.689539 | [
"MIT"
] | Agazoth/azure-powershell | src/Migrate/generated/api/Models/Api20210210/MasterTargetServer.cs | 26,505 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.ComponentModel;
namespace Azure.Messaging.EventHubs.Producer
{
/// <summary>
/// The set of options that can be specified to influence the way in which events
/// are published to the Event Hubs service.
/// </summary>
///
internal class EnqueueEventOptions : SendEventOptions
{
/// <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>
///
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => base.Equals(obj);
/// <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>
///
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => base.GetHashCode();
/// <summary>
/// Converts the instance to string representation.
/// </summary>
///
/// <returns>A <see cref="System.String" /> that represents this instance.</returns>
///
[EditorBrowsable(EditorBrowsableState.Never)]
public override string ToString() => base.ToString();
}
}
| 37.866667 | 140 | 0.612676 | [
"MIT"
] | Cardsareus/azure-sdk-for-net | sdk/eventhub/Azure.Messaging.EventHubs/src/Producer/EnqueueEventOptions.cs | 1,706 | C# |
using Microsoft.AspNetCore.Mvc;
namespace vLibrary.API.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class TestController : ControllerBase
{
[HttpGet]
public string Get(){
return "Hello from test!";
}
}
} | 20 | 48 | 0.603571 | [
"MIT"
] | arnel-k/VirtualLibrary | vLibrary.API/Controllers/TestController.cs | 280 | C# |
// original code from GitHub Reactive-Extensions/Rx.NET
// some modified.
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#if (NET_4_6 || UNITY_WSA)
using System;
using System.Threading;
namespace UniRx
{
/// <summary>
/// Represents a disposable resource that has an associated <seealso cref="T:System.Threading.CancellationToken"/> that will be set to the cancellation requested state upon disposal.
/// </summary>
public sealed class CancellationDisposable : ICancelable
{
private readonly CancellationTokenSource _cts;
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.CancellationDisposable"/> class that uses an existing <seealso cref="T:System.Threading.CancellationTokenSource"/>.
/// </summary>
/// <param name="cts"><seealso cref="T:System.Threading.CancellationTokenSource"/> used for cancellation.</param>
/// <exception cref="ArgumentNullException"><paramref name="cts"/> is null.</exception>
public CancellationDisposable(CancellationTokenSource cts)
{
if (cts == null)
throw new ArgumentNullException("cts");
_cts = cts;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.CancellationDisposable"/> class that uses a new <seealso cref="T:System.Threading.CancellationTokenSource"/>.
/// </summary>
public CancellationDisposable()
: this(new CancellationTokenSource())
{
}
/// <summary>
/// Gets the <see cref="T:System.Threading.CancellationToken"/> used by this CancellationDisposable.
/// </summary>
public CancellationToken Token
{
get { return _cts.Token; }
}
/// <summary>
/// Cancels the underlying <seealso cref="T:System.Threading.CancellationTokenSource"/>.
/// </summary>
public void Dispose()
{
_cts.Cancel();
}
/// <summary>
/// Gets a value that indicates whether the object is disposed.
/// </summary>
public bool IsDisposed
{
get { return _cts.IsCancellationRequested; }
}
}
}
#endif | 35.402985 | 202 | 0.631113 | [
"MIT"
] | dykarohora/HoloAzureSample | Assets/Plugins/UniRx/Scripts/Disposables/CancellationDisposable.cs | 2,374 | C# |
//------------------------------------------------------------
// Author: 烟雨迷离半世殇
// Mail: 1778139321@qq.com
// Data: 2020年9月7日 15:35:42
//------------------------------------------------------------
using ET.EventType;
using Sirenix.OdinInspector;
namespace ET
{
/// <summary>
/// 会检查一次是否达到指定层数,然后再决定是否触发事件
/// </summary>
public class ListenBuffEvent_CheckOverlay : ListenBuffEvent_Normal
{
[LabelText("目标层数")] public int TargetOverlay;
public override void Run(IBuffSystem a)
{
IBuffSystem aBuffSystemBase = a;
if (aBuffSystemBase.CurrentOverlay == this.TargetOverlay)
{
foreach (var buffInfo in this.BuffInfoWillBeAdded)
{
buffInfo.AutoAddBuff(aBuffSystemBase.BuffData.BelongToBuffDataSupportorId,
buffInfo.BuffNodeId.Value, aBuffSystemBase.TheUnitFrom, aBuffSystemBase.TheUnitBelongto,
aBuffSystemBase.BelongtoRuntimeTree);
}
}
}
}
} | 32.121212 | 112 | 0.537736 | [
"MIT"
] | futouyiba/ClubET | Unity/Assets/Hotfix/NKGMOBA/Battle/SkillSystem/BuffSystem/ListenBuffEvents/ListenBuffEvent_CheckOverlay.cs | 1,138 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm testing portfolio construction model control over rebalancing,
/// when setting 'PortfolioConstructionModel.RebalanceOnInsightChanges' to false, see GH 4075.
/// </summary>
public class PortfolioRebalanceOnInsightChangesRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Dictionary<Symbol, DateTime> _lastOrderFilled;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
UniverseSettings.Resolution = Resolution.Daily;
SetStartDate(2015, 1, 1);
SetEndDate(2017, 1, 1);
Settings.RebalancePortfolioOnInsightChanges = false;
SetUniverseSelection(new CustomUniverseSelectionModel("CustomUniverseSelectionModel",
time => new List<string> { "FB", "SPY", "AAPL", "IBM" }));
SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromMinutes(20), 0.025, null));
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel(
time => time.AddDays(30)));
SetExecution(new ImmediateExecutionModel());
_lastOrderFilled = new Dictionary<Symbol, DateTime>();
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (orderEvent.Status == OrderStatus.Submitted)
{
DateTime lastOrderFilled;
if (_lastOrderFilled.TryGetValue(orderEvent.Symbol, out lastOrderFilled))
{
if (UtcTime - lastOrderFilled < TimeSpan.FromDays(30))
{
throw new Exception($"{UtcTime} {orderEvent.Symbol} {UtcTime - lastOrderFilled}");
}
}
_lastOrderFilled[orderEvent.Symbol] = UtcTime;
Debug($"{orderEvent}");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "82"},
{"Average Win", "0.16%"},
{"Average Loss", "-0.05%"},
{"Compounding Annual Return", "9.913%"},
{"Drawdown", "18.200%"},
{"Expectancy", "2.470"},
{"Net Profit", "20.808%"},
{"Sharpe Ratio", "0.607"},
{"Probabilistic Sharpe Ratio", "25.710%"},
{"Loss Rate", "18%"},
{"Win Rate", "82%"},
{"Profit-Loss Ratio", "3.21"},
{"Alpha", "0.093"},
{"Beta", "0.012"},
{"Annual Standard Deviation", "0.155"},
{"Annual Variance", "0.024"},
{"Information Ratio", "0.158"},
{"Tracking Error", "0.201"},
{"Treynor Ratio", "8.115"},
{"Total Fees", "$82.80"},
{"Fitness Score", "0.001"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "1"},
{"Sortino Ratio", "0.822"},
{"Return Over Maximum Drawdown", "0.546"},
{"Portfolio Turnover", "0.002"},
{"Total Insights Generated", "2028"},
{"Total Insights Closed", "2024"},
{"Total Insights Analysis Completed", "2024"},
{"Long Insight Count", "2028"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "1290270110"}
};
}
}
| 43.082707 | 149 | 0.599127 | [
"Apache-2.0"
] | Zingasoft/Lean | Algorithm.CSharp/PortfolioRebalanceOnInsightChangesRegressionAlgorithm.cs | 5,730 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerScript : MonoBehaviour {
public Transform ARMainCamera;
public GameObject teapot;
private GameObject Environment;
private bool isEnvironmentKnown = false;
void Start () {
}
// Update is called once per frame
void Update () {
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Collectables")
{
GameController.playerScore++;
other.transform.localPosition = new Vector3(Random.Range(-4.32f, 4.37f), Random.Range(0f, 1f), Random.Range(-4.4f, 4.54f));
if (!isEnvironmentKnown)
{
findEnvironment();
}
GameObject TeaPotInstance = (GameObject)Instantiate(teapot, new Vector3(0f,0f,0f), Quaternion.identity,Environment.transform);
//_ShowAndroidToastMessage("created");
TeaPotInstance.transform.localPosition = new Vector3(Random.Range(-3.85f,3.89f),Random.Range(2f,5f),Random.Range(-3.95f,3.95f));
TeaPotInstance.GetComponent<LookAt>().Rectile_Camera = ARMainCamera;
} else if (other.tag=="TeaBullet") {
GameController.playerScore--;
Destroy(other.gameObject);
}
}
private void findEnvironment()
{
Environment=GameObject.FindGameObjectWithTag("Environment");
isEnvironmentKnown = true;
}
private void _ShowAndroidToastMessage(string message)
{
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject unityActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
if (unityActivity != null)
{
AndroidJavaClass toastClass = new AndroidJavaClass("android.widget.Toast");
unityActivity.Call("runOnUiThread", new AndroidJavaRunnable(() =>
{
AndroidJavaObject toastObject = toastClass.CallStatic<AndroidJavaObject>("makeText", unityActivity,
message, 0);
toastObject.Call("show");
}));
}
}
}
| 33.796875 | 140 | 0.638927 | [
"MIT"
] | rajandeepsingh13/6DOF-Mobile-VR | Assets/Dodge/Scripts/PlayerScript.cs | 2,165 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Grappachu.Briscola.Model;
namespace Grappachu.Briscola.Players.zaninig.Model
{
class CardInfo
{
public Card Card { get; set; }
public decimal Weight { get; set; }
}
}
| 19.9375 | 50 | 0.705329 | [
"MIT"
] | grappachu/Briscola | src/Grappachu.Briscola.Players/zaninig/Model/CardInfo.cs | 321 | C# |
using CodingCat.Mq.Abstractions.Interfaces;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace CodingCat.Mq.Abstractions.Tests.Impls
{
public class SimpleSubscriber<T> : BaseProcessor<T>, ISubscriber
{
private object lockable { get; } = new object();
private Queue<T> inputQueue { get; set; }
public int ServedAmount { get; private set; } = 0;
public event EventHandler Subscribed;
public event EventHandler Processed;
public event EventHandler Disposing;
public event EventHandler Disposed;
public T LastInput { get; private set; }
#region Constructor(s)
public SimpleSubscriber(Queue<T> inputQueue) : base()
{
this.inputQueue = inputQueue;
}
#endregion Constructor(s)
protected override void Process(T input)
{
this.LastInput = input;
Console.WriteLine(this.LastInput.ToString());
}
public ISubscriber Subscribe()
{
Task.Run(() =>
{
while (this.inputQueue != null)
{
lock (this.lockable)
{
if (this.inputQueue == null) break;
if (this.inputQueue.Count > 0)
{
this.Process(this.inputQueue.Peek());
this.inputQueue.Dequeue();
this.ServedAmount += 1;
this.Processed?.Invoke(this, null);
}
}
Thread.Sleep(50);
}
});
this.Subscribed?.Invoke(this, null);
return this;
}
public void Dispose()
{
this.Disposing?.Invoke(this, null);
var notifier = new AutoResetEvent(false);
lock (this.lockable)
{
if (this.inputQueue.Count <= 0)
{
this.inputQueue = null;
notifier.Set();
}
else
{
this.inputQueue = new Queue<T>(this.inputQueue);
this.Processed += (sender, args) =>
{
if (this.inputQueue.Count <= 0)
{
this.inputQueue = null;
notifier.Set();
}
};
}
}
notifier.WaitOne();
this.Disposed?.Invoke(this, null);
}
}
} | 28.154639 | 68 | 0.450384 | [
"BSD-2-Clause"
] | CodingCatHongKong/dotnet-CodingCat.Mq.Abstractions | CodingCat.Mq.Abstractions/CodingCat.Mq.Abstractions.Tests/Impls/SimpleSubscriber.cs | 2,733 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.CognitoIdentity")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Cognito Identity. Amazon Cognito is a service that makes it easy to save user data, such as app preferences or game state, in the AWS Cloud without writing any backend code or managing any infrastructure. With Amazon Cognito, you can focus on creating great app experiences instead of having to worry about building and managing a backend solution to handle identity management, network state, storage, and sync.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon Cognito Identity. Amazon Cognito is a service that makes it easy to save user data, such as app preferences or game state, in the AWS Cloud without writing any backend code or managing any infrastructure. With Amazon Cognito, you can focus on creating great app experiences instead of having to worry about building and managing a backend solution to handle identity management, network state, storage, and sync.")]
#elif PCL
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - Amazon Cognito Identity. Amazon Cognito is a service that makes it easy to save user data, such as app preferences or game state, in the AWS Cloud without writing any backend code or managing any infrastructure. With Amazon Cognito, you can focus on creating great app experiences instead of having to worry about building and managing a backend solution to handle identity management, network state, storage, and sync.")]
#elif UNITY
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - Amazon Cognito Identity. Amazon Cognito is a service that makes it easy to save user data, such as app preferences or game state, in the AWS Cloud without writing any backend code or managing any infrastructure. With Amazon Cognito, you can focus on creating great app experiences instead of having to worry about building and managing a backend solution to handle identity management, network state, storage, and sync.")]
#elif NETSTANDARD13
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- Amazon Cognito Identity. Amazon Cognito is a service that makes it easy to save user data, such as app preferences or game state, in the AWS Cloud without writing any backend code or managing any infrastructure. With Amazon Cognito, you can focus on creating great app experiences instead of having to worry about building and managing a backend solution to handle identity management, network state, storage, and sync.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- Amazon Cognito Identity. Amazon Cognito is a service that makes it easy to save user data, such as app preferences or game state, in the AWS Cloud without writing any backend code or managing any infrastructure. With Amazon Cognito, you can focus on creating great app experiences instead of having to worry about building and managing a backend solution to handle identity management, network state, storage, and sync.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.3.101.32")]
#if WINDOWS_PHONE || UNITY
[assembly: System.CLSCompliant(false)]
# else
[assembly: System.CLSCompliant(true)]
#endif
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 80.084746 | 510 | 0.787725 | [
"Apache-2.0"
] | UpendoVentures/aws-sdk-net | sdk/src/Services/CognitoIdentity/Properties/AssemblyInfo.cs | 4,725 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using Humanizer;
using SqlKata.Compilers;
namespace SqlKata.Execution
{
public class QueryFactory : IDisposable
{
public IDbConnection Connection { get; set; }
public Compiler Compiler { get; set; }
public Action<SqlResult> Logger = result => { };
private bool disposedValue;
public int QueryTimeout { get; set; } = 30;
public QueryFactory() { }
public QueryFactory(IDbConnection connection, Compiler compiler, int timeout = 30)
{
Connection = connection;
Compiler = compiler;
QueryTimeout = timeout;
}
public Query Query()
{
var query = new XQuery(this.Connection, this.Compiler);
query.QueryFactory = this;
query.Logger = Logger;
return query;
}
public Query Query(string table)
{
return Query().From(table);
}
/// <summary>
/// Create an XQuery instance from a regular Query
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
public Query FromQuery(Query query)
{
var xQuery = new XQuery(this.Connection, this.Compiler);
xQuery.QueryFactory = this;
xQuery.Clauses = query.Clauses.Select(x => x.Clone()).ToList();
xQuery.SetParent(query.Parent);
xQuery.QueryAlias = query.QueryAlias;
xQuery.IsDistinct = query.IsDistinct;
xQuery.Method = query.Method;
xQuery.Includes = query.Includes;
xQuery.Variables = query.Variables;
xQuery.SetEngineScope(query.EngineScope);
xQuery.Logger = Logger;
return xQuery;
}
public IEnumerable<T> Get<T>(Query query, IDbTransaction transaction = null, int? timeout = null)
{
var compiled = CompileAndLog(query);
var result = this.Connection.Query<T>(
compiled.Sql,
compiled.NamedBindings,
transaction: transaction,
commandTimeout: timeout ?? this.QueryTimeout
).ToList();
result = handleIncludes<T>(query, result).ToList();
return result;
}
public async Task<IEnumerable<T>> GetAsync<T>(Query query, IDbTransaction transaction = null, int? timeout = null)
{
var compiled = CompileAndLog(query);
var result = (await this.Connection.QueryAsync<T>(
compiled.Sql,
compiled.NamedBindings,
transaction: transaction,
commandTimeout: timeout ?? this.QueryTimeout
)).ToList();
result = (await handleIncludesAsync(query, result)).ToList();
return result;
}
public IEnumerable<IDictionary<string, object>> GetDictionary(Query query, IDbTransaction transaction = null, int? timeout = null)
{
var compiled = CompileAndLog(query);
var result = this.Connection.Query(
compiled.Sql,
compiled.NamedBindings,
transaction: transaction,
commandTimeout: timeout ?? this.QueryTimeout
);
return result.Cast<IDictionary<string, object>>();
}
public async Task<IEnumerable<IDictionary<string, object>>> GetDictionaryAsync(Query query, IDbTransaction transaction = null, int? timeout = null)
{
var compiled = CompileAndLog(query);
var result = await this.Connection.QueryAsync(
compiled.Sql,
compiled.NamedBindings,
transaction: transaction,
commandTimeout: timeout ?? this.QueryTimeout
);
return result.Cast<IDictionary<string, object>>();
}
public IEnumerable<dynamic> Get(Query query, IDbTransaction transaction = null, int? timeout = null)
{
return Get<dynamic>(query, transaction, timeout);
}
public async Task<IEnumerable<dynamic>> GetAsync(Query query, IDbTransaction transaction = null, int? timeout = null)
{
return await GetAsync<dynamic>(query, transaction, timeout);
}
public T FirstOrDefault<T>(Query query, IDbTransaction transaction = null, int? timeout = null)
{
var list = Get<T>(query.Limit(1), transaction, timeout);
return list.ElementAtOrDefault(0);
}
public async Task<T> FirstOrDefaultAsync<T>(Query query, IDbTransaction transaction = null, int? timeout = null)
{
var list = await GetAsync<T>(query.Limit(1), transaction, timeout);
return list.ElementAtOrDefault(0);
}
public dynamic FirstOrDefault(Query query, IDbTransaction transaction = null, int? timeout = null)
{
return FirstOrDefault<dynamic>(query, transaction, timeout);
}
public async Task<dynamic> FirstOrDefaultAsync(Query query, IDbTransaction transaction = null, int? timeout = null)
{
return await FirstOrDefaultAsync<dynamic>(query, transaction, timeout);
}
public T First<T>(Query query, IDbTransaction transaction = null, int? timeout = null)
{
var item = FirstOrDefault<T>(query, transaction, timeout);
if (item == null)
{
throw new InvalidOperationException("The sequence contains no elements");
}
return item;
}
public async Task<T> FirstAsync<T>(Query query, IDbTransaction transaction = null, int? timeout = null)
{
var item = await FirstOrDefaultAsync<T>(query, transaction, timeout);
if (item == null)
{
throw new InvalidOperationException("The sequence contains no elements");
}
return item;
}
public dynamic First(Query query, IDbTransaction transaction = null, int? timeout = null)
{
return First<dynamic>(query, transaction, timeout);
}
public async Task<dynamic> FirstAsync(Query query, IDbTransaction transaction = null, int? timeout = null)
{
return await FirstAsync<dynamic>(query, transaction, timeout);
}
public int Execute(
Query query,
IDbTransaction transaction = null,
int? timeout = null
)
{
var compiled = CompileAndLog(query);
return this.Connection.Execute(
compiled.Sql,
compiled.NamedBindings,
transaction,
timeout ?? this.QueryTimeout
);
}
public async Task<int> ExecuteAsync(
Query query,
IDbTransaction transaction = null,
int? timeout = null
)
{
var compiled = CompileAndLog(query);
return await this.Connection.ExecuteAsync(
compiled.Sql,
compiled.NamedBindings,
transaction,
timeout ?? this.QueryTimeout
);
}
public T ExecuteScalar<T>(Query query, IDbTransaction transaction = null, int? timeout = null)
{
var compiled = CompileAndLog(query.Limit(1));
return this.Connection.ExecuteScalar<T>(
compiled.Sql,
compiled.NamedBindings,
transaction,
timeout ?? this.QueryTimeout
);
}
public async Task<T> ExecuteScalarAsync<T>(
Query query,
IDbTransaction transaction = null,
int? timeout = null
)
{
var compiled = CompileAndLog(query.Limit(1));
return await this.Connection.ExecuteScalarAsync<T>(
compiled.Sql,
compiled.NamedBindings,
transaction,
timeout ?? this.QueryTimeout
);
}
public SqlMapper.GridReader GetMultiple<T>(
Query[] queries,
IDbTransaction transaction = null,
int? timeout = null
)
{
var compiled = this.Compiler.Compile(queries);
return this.Connection.QueryMultiple(
compiled.Sql,
compiled.NamedBindings,
transaction,
timeout ?? this.QueryTimeout
);
}
public async Task<SqlMapper.GridReader> GetMultipleAsync<T>(
Query[] queries,
IDbTransaction transaction = null,
int? timeout = null)
{
var compiled = this.Compiler.Compile(queries);
return await this.Connection.QueryMultipleAsync(
compiled.Sql,
compiled.NamedBindings,
transaction,
timeout ?? this.QueryTimeout
);
}
public IEnumerable<IEnumerable<T>> Get<T>(
Query[] queries,
IDbTransaction transaction = null,
int? timeout = null
)
{
var multi = this.GetMultiple<T>(
queries,
transaction,
timeout
);
using (multi)
{
for (var i = 0; i < queries.Length; i++)
{
yield return multi.Read<T>();
}
}
}
public async Task<IEnumerable<IEnumerable<T>>> GetAsync<T>(
Query[] queries,
IDbTransaction transaction = null,
int? timeout = null
)
{
var multi = await this.GetMultipleAsync<T>(
queries,
transaction,
timeout
);
var list = new List<IEnumerable<T>>();
using (multi)
{
for (var i = 0; i < queries.Length; i++)
{
list.Add(multi.Read<T>());
}
}
return list;
}
public bool Exists(Query query, IDbTransaction transaction = null, int? timeout = null)
{
var clone = query.Clone()
.ClearComponent("select")
.SelectRaw("1 as [Exists]")
.Limit(1);
var rows = Get(clone, transaction, timeout);
return rows.Any();
}
public async Task<bool> ExistsAsync(Query query, IDbTransaction transaction = null, int? timeout = null)
{
var clone = query.Clone()
.ClearComponent("select")
.SelectRaw("1 as [Exists]")
.Limit(1);
var rows = await GetAsync(clone, transaction, timeout);
return rows.Any();
}
public T Aggregate<T>(
Query query,
string aggregateOperation,
string[] columns = null,
IDbTransaction transaction = null,
int? timeout = null
)
{
return this.ExecuteScalar<T>(query.AsAggregate(aggregateOperation, columns), transaction, timeout ?? this.QueryTimeout);
}
public async Task<T> AggregateAsync<T>(
Query query,
string aggregateOperation,
string[] columns = null,
IDbTransaction transaction = null,
int? timeout = null
)
{
return await this.ExecuteScalarAsync<T>(
query.AsAggregate(aggregateOperation, columns),
transaction,
timeout
);
}
public T Count<T>(Query query, string[] columns = null, IDbTransaction transaction = null, int? timeout = null)
{
return this.ExecuteScalar<T>(
query.AsCount(columns),
transaction,
timeout
);
}
public async Task<T> CountAsync<T>(Query query, string[] columns = null, IDbTransaction transaction = null, int? timeout = null)
{
return await this.ExecuteScalarAsync<T>(query.AsCount(columns), transaction, timeout);
}
public T Average<T>(Query query, string column, IDbTransaction transaction = null, int? timeout = null)
{
return this.Aggregate<T>(query, "avg", new[] { column });
}
public async Task<T> AverageAsync<T>(Query query, string column)
{
return await this.AggregateAsync<T>(query, "avg", new[] { column });
}
public T Sum<T>(Query query, string column)
{
return this.Aggregate<T>(query, "sum", new[] { column });
}
public async Task<T> SumAsync<T>(Query query, string column)
{
return await this.AggregateAsync<T>(query, "sum", new[] { column });
}
public T Min<T>(Query query, string column)
{
return this.Aggregate<T>(query, "min", new[] { column });
}
public async Task<T> MinAsync<T>(Query query, string column)
{
return await this.AggregateAsync<T>(query, "min", new[] { column });
}
public T Max<T>(Query query, string column)
{
return this.Aggregate<T>(query, "max", new[] { column });
}
public async Task<T> MaxAsync<T>(Query query, string column)
{
return await this.AggregateAsync<T>(query, "max", new[] { column });
}
public PaginationResult<T> Paginate<T>(Query query, int page, int perPage = 25, IDbTransaction transaction = null, int? timeout = null)
{
if (page < 1)
{
throw new ArgumentException("Page param should be greater than or equal to 1", nameof(page));
}
if (perPage < 1)
{
throw new ArgumentException("PerPage param should be greater than or equal to 1", nameof(perPage));
}
var count = Count<long>(query.Clone(), null, transaction, timeout);
IEnumerable<T> list;
if (count > 0)
{
list = Get<T>(query.Clone().ForPage(page, perPage), transaction, timeout);
}
else
{
list = Enumerable.Empty<T>();
}
return new PaginationResult<T>
{
Query = query,
Page = page,
PerPage = perPage,
Count = count,
List = list
};
}
public async Task<PaginationResult<T>> PaginateAsync<T>(Query query, int page, int perPage = 25, IDbTransaction transaction = null, int? timeout = null)
{
if (page < 1)
{
throw new ArgumentException("Page param should be greater than or equal to 1", nameof(page));
}
if (perPage < 1)
{
throw new ArgumentException("PerPage param should be greater than or equal to 1", nameof(perPage));
}
var count = await CountAsync<long>(query.Clone(), null, transaction, timeout);
IEnumerable<T> list;
if (count > 0)
{
list = await GetAsync<T>(query.Clone().ForPage(page, perPage), transaction, timeout);
}
else
{
list = Enumerable.Empty<T>();
}
return new PaginationResult<T>
{
Query = query,
Page = page,
PerPage = perPage,
Count = count,
List = list
};
}
public void Chunk<T>(
Query query,
int chunkSize,
Func<IEnumerable<T>, int, bool> func,
IDbTransaction transaction = null,
int? timeout = null)
{
var result = this.Paginate<T>(query, 1, chunkSize, transaction, timeout);
if (!func(result.List, 1))
{
return;
}
while (result.HasNext)
{
result = result.Next(transaction);
if (!func(result.List, result.Page))
{
return;
}
}
}
public async Task ChunkAsync<T>(
Query query,
int chunkSize,
Func<IEnumerable<T>, int, bool> func,
IDbTransaction transaction = null,
int? timeout = null
)
{
var result = await this.PaginateAsync<T>(query, 1, chunkSize, transaction);
if (!func(result.List, 1))
{
return;
}
while (result.HasNext)
{
result = result.Next(transaction);
if (!func(result.List, result.Page))
{
return;
}
}
}
public void Chunk<T>(Query query, int chunkSize, Action<IEnumerable<T>, int> action, IDbTransaction transaction = null, int? timeout = null)
{
var result = this.Paginate<T>(query, 1, chunkSize, transaction, timeout);
action(result.List, 1);
while (result.HasNext)
{
result = result.Next(transaction);
action(result.List, result.Page);
}
}
public async Task ChunkAsync<T>(
Query query,
int chunkSize,
Action<IEnumerable<T>, int> action,
IDbTransaction transaction = null,
int? timeout = null
)
{
var result = await this.PaginateAsync<T>(query, 1, chunkSize, transaction, timeout);
action(result.List, 1);
while (result.HasNext)
{
result = result.Next(transaction);
action(result.List, result.Page);
}
}
public IEnumerable<T> Select<T>(string sql, object param = null, IDbTransaction transaction = null, int? timeout = null)
{
return this.Connection.Query<T>(
sql,
param,
transaction: transaction,
commandTimeout: timeout ?? this.QueryTimeout
);
}
public async Task<IEnumerable<T>> SelectAsync<T>(string sql, object param = null, IDbTransaction transaction = null, int? timeout = null)
{
return await this.Connection.QueryAsync<T>(
sql,
param,
transaction: transaction,
commandTimeout: timeout ?? this.QueryTimeout
);
}
public IEnumerable<dynamic> Select(string sql, object param = null, IDbTransaction transaction = null, int? timeout = null)
{
return this.Select<dynamic>(sql, param, transaction, timeout);
}
public async Task<IEnumerable<dynamic>> SelectAsync(string sql, object param = null, IDbTransaction transaction = null, int? timeout = null)
{
return await this.SelectAsync<dynamic>(sql, param, transaction, timeout);
}
public int Statement(string sql, object param = null, IDbTransaction transaction = null, int? timeout = null)
{
return this.Connection.Execute(sql, param, transaction: transaction, commandTimeout: timeout ?? this.QueryTimeout);
}
public async Task<int> StatementAsync(string sql, object param = null, IDbTransaction transaction = null, int? timeout = null)
{
return await this.Connection.ExecuteAsync(sql, param, transaction: transaction, commandTimeout: timeout ?? this.QueryTimeout);
}
private static IEnumerable<T> handleIncludes<T>(Query query, IEnumerable<T> result)
{
if (!result.Any())
{
return result;
}
var canBeProcessed = query.Includes.Any() && result.ElementAt(0) is IDynamicMetaObjectProvider;
if (!canBeProcessed)
{
return result;
}
var dynamicResult = result
.Cast<IDictionary<string, object>>()
.Select(x => new Dictionary<string, object>(x, StringComparer.OrdinalIgnoreCase))
.ToList();
foreach (var include in query.Includes)
{
if (include.IsMany)
{
if (include.ForeignKey == null)
{
// try to guess the default key
// I will try to fetch the table name if provided and appending the Id as a convention
// Here am using Humanizer package to help getting the singular form of the table
var fromTable = query.GetOneComponent("from") as FromClause;
if (fromTable == null)
{
throw new InvalidOperationException($"Cannot guess the foreign key for the included relation '{include.Name}'");
}
var table = fromTable.Alias ?? fromTable.Table;
include.ForeignKey = table.Singularize(false) + "Id";
}
var localIds = dynamicResult.Where(x => x[include.LocalKey] != null)
.Select(x => x[include.LocalKey].ToString())
.ToList();
if (!localIds.Any())
{
continue;
}
var children = include
.Query
.WhereIn(include.ForeignKey, localIds)
.Get()
.Cast<IDictionary<string, object>>()
.Select(x => new Dictionary<string, object>(x, StringComparer.OrdinalIgnoreCase))
.GroupBy(x => x[include.ForeignKey].ToString())
.ToDictionary(x => x.Key, x => x.ToList());
foreach (var item in dynamicResult)
{
var localValue = item[include.LocalKey].ToString();
item[include.Name] = children.ContainsKey(localValue) ? children[localValue] : new List<Dictionary<string, object>>();
}
continue;
}
if (include.ForeignKey == null)
{
include.ForeignKey = include.Name + "Id";
}
var foreignIds = dynamicResult
.Where(x => x[include.ForeignKey] != null)
.Select(x => x[include.ForeignKey].ToString())
.ToList();
if (!foreignIds.Any())
{
continue;
}
var related = include
.Query
.WhereIn(include.LocalKey, foreignIds)
.Get()
.Cast<IDictionary<string, object>>()
.Select(x => new Dictionary<string, object>(x, StringComparer.OrdinalIgnoreCase))
.ToDictionary(x => x[include.LocalKey].ToString());
foreach (var item in dynamicResult)
{
var foreignValue = item[include.ForeignKey].ToString();
item[include.Name] = related.ContainsKey(foreignValue) ? related[foreignValue] : null;
}
}
return dynamicResult.Cast<T>();
}
private static async Task<IEnumerable<T>> handleIncludesAsync<T>(Query query, IEnumerable<T> result)
{
if (!result.Any())
{
return result;
}
var canBeProcessed = query.Includes.Any() && result.ElementAt(0) is IDynamicMetaObjectProvider;
if (!canBeProcessed)
{
return result;
}
var dynamicResult = result
.Cast<IDictionary<string, object>>()
.Select(x => new Dictionary<string, object>(x, StringComparer.OrdinalIgnoreCase))
.ToList();
foreach (var include in query.Includes)
{
if (include.IsMany)
{
if (include.ForeignKey == null)
{
// try to guess the default key
// I will try to fetch the table name if provided and appending the Id as a convention
// Here am using Humanizer package to help getting the singular form of the table
var fromTable = query.GetOneComponent("from") as FromClause;
if (fromTable == null)
{
throw new InvalidOperationException($"Cannot guess the foreign key for the included relation '{include.Name}'");
}
var table = fromTable.Alias ?? fromTable.Table;
include.ForeignKey = table.Singularize(false) + "Id";
}
var localIds = dynamicResult.Where(x => x[include.LocalKey] != null)
.Select(x => x[include.LocalKey].ToString())
.ToList();
if (!localIds.Any())
{
continue;
}
var children = (await include.Query.WhereIn(include.ForeignKey, localIds).GetAsync())
.Cast<IDictionary<string, object>>()
.Select(x => new Dictionary<string, object>(x, StringComparer.OrdinalIgnoreCase))
.GroupBy(x => x[include.ForeignKey].ToString())
.ToDictionary(x => x.Key, x => x.ToList());
foreach (var item in dynamicResult)
{
var localValue = item[include.LocalKey].ToString();
item[include.Name] = children.ContainsKey(localValue) ? children[localValue] : new List<Dictionary<string, object>>();
}
continue;
}
if (include.ForeignKey == null)
{
include.ForeignKey = include.Name + "Id";
}
var foreignIds = dynamicResult.Where(x => x[include.ForeignKey] != null)
.Select(x => x[include.ForeignKey].ToString())
.ToList();
if (!foreignIds.Any())
{
continue;
}
var related = (await include.Query.WhereIn(include.LocalKey, foreignIds).GetAsync())
.Cast<IDictionary<string, object>>()
.Select(x => new Dictionary<string, object>(x, StringComparer.OrdinalIgnoreCase))
.ToDictionary(x => x[include.LocalKey].ToString());
foreach (var item in dynamicResult)
{
var foreignValue = item[include.ForeignKey].ToString();
item[include.Name] = related.ContainsKey(foreignValue) ? related[foreignValue] : null;
}
}
return dynamicResult.Cast<T>();
}
/// <summary>
/// Compile and log query
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
internal SqlResult CompileAndLog(Query query)
{
var compiled = this.Compiler.Compile(query);
this.Logger(compiled);
return compiled;
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
Connection.Dispose();
}
// TODO: free unmanaged resources (unmanaged objects) and override finalizer
// TODO: set large fields to null
Connection = null;
Compiler = null;
disposedValue = true;
}
}
// // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
// ~QueryFactory()
// {
// // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
// Dispose(disposing: false);
// }
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
} | 33.343607 | 160 | 0.509227 | [
"MIT"
] | Magicianred/querybuilder | SqlKata.Execution/QueryFactory.cs | 29,209 | C# |
using RabbitMQ.Client;
namespace InstrumentedRabbitMqDotNetClient.Connection
{
internal class ChannelProvider : IChannelProvider
{
private readonly IModel _channel;
public ChannelProvider(RabbitMQConfiguration configuration, IConnectionFactory connectionFactory)
{
var connection = connectionFactory.CreateConnection();
_channel = connection.CreateModel();
_channel.ExchangeDeclare(exchange: configuration.Exchange, type: ExchangeType.Topic, true);
}
public IModel GetChannel() => _channel;
}
} | 32.555556 | 105 | 0.708191 | [
"MIT"
] | JoanComasFdz/dotnet-rabbitmq-client-instrumentation-app-insights | InstrumentedRabbitMqDotNetClient/Connection/ChannelProvider.cs | 588 | C# |
using System.ComponentModel;
using System.Runtime.Serialization;
namespace EncompassApi.Loans.Enums
{
/// <summary>
/// FreddieARMIndexType
/// </summary>
public enum FreddieARMIndexType
{
/// <summary>
/// LIBOROneYearWSJDaily
/// </summary>
LIBOROneYearWSJDaily = 0,
/// <summary>
/// SixMonthLIBOR_WSJDaily
/// </summary>
[EnumMember(Value = "SixMonthLIBOR_WSJDaily")]
SixMonthLIBORWSJDaily = 1,
/// <summary>
/// WeeklyFiveYearTreasurySecuritiesConstantMaturityFRBH15
/// </summary>
WeeklyFiveYearTreasurySecuritiesConstantMaturityFRBH15 = 2,
/// <summary>
/// WeeklyOneYearTreasurySecuritiesConstantMaturityFRBH15
/// </summary>
WeeklyOneYearTreasurySecuritiesConstantMaturityFRBH15 = 3,
/// <summary>
/// WeeklyThreeYearTreasurySecuritiesConstantMaturityFRBH15
/// </summary>
WeeklyThreeYearTreasurySecuritiesConstantMaturityFRBH15 = 4,
/// <summary>
/// 30-Day Average SOFR
/// </summary>
[Description("30-Day Average SOFR")]
[EnumMember(Value = "SOFR_30DayAvg")]
SOFR30DayAvg = 5
}
} | 31.615385 | 68 | 0.621249 | [
"MIT"
] | fairwayindependentmc/EncompassApi | src/EncompassApi/Loans/Enums/FreddieARMIndexType.cs | 1,235 | C# |
class StreetExtraordinaire : Cat
{
// public string Name { get; set; }
public double DecibelsOfMeows { get; set; }
public override string ToString()
{
return $"StreetExtraordinaire {Name} {DecibelsOfMeows}";
}
}
| 20.166667 | 64 | 0.644628 | [
"MIT"
] | ignatovg/Software-University | C#-Fundamentals/02_OOP_Basics/01_Defining_Classes/Defining_Classes_Exercises/CatLady/StreetExtraordinaire.cs | 244 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("WinApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("WinApi")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("bae19bd1-40fa-47ae-8bb0-efbdcaf4ef33")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 40.351351 | 106 | 0.760884 | [
"BSD-2-Clause"
] | JulianVo/SumpfkrautOnline-Khorinis | WinApi.changed/Properties/AssemblyInfo.cs | 1,511 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. 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.
*/
namespace TencentCloud.Cdb.V20170320.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DeleteAuditPolicyRequest : AbstractModel
{
/// <summary>
/// 审计策略 ID。
/// </summary>
[JsonProperty("PolicyId")]
public string PolicyId{ get; set; }
/// <summary>
/// 实例 ID。
/// </summary>
[JsonProperty("InstanceId")]
public string InstanceId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "PolicyId", this.PolicyId);
this.SetParamSimple(map, prefix + "InstanceId", this.InstanceId);
}
}
}
| 29.843137 | 83 | 0.637976 | [
"Apache-2.0"
] | ImEdisonJiang/tencentcloud-sdk-dotnet | TencentCloud/Cdb/V20170320/Models/DeleteAuditPolicyRequest.cs | 1,538 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace ModernSlavery.Core.Extensions
{
public static class Numeric
{
public static Random Random = new Random(VirtualDateTime.Now.Millisecond);
/// <summary>
/// Returns a randam value between two ranges (inclusive) but excludes certain values
/// </summary>
/// <param name="Min">The minimum value of the returned result</param>
/// <param name="Max">The maximum value of the returned result</param>
/// <param name="excludes">Values to exclude from results</param>
/// <returns>The random value between the min and max values (excluding specified results)</returns>
public static int Rand(int Min, int Max, params int[] excludes)
{
int result;
if (excludes == null || excludes.Length == 0)
{
result = Random.Next(Min, Max + 1);
return result;
}
//Get all values within the range
var range = Enumerable.Range(Min, Max - Min + 1).ToArray();
//Normalise all excludes and sort
excludes = new SortedSet<int>(excludes).ToArray();
//Throw wrror if all values are excluded
if (range.SequenceEqual(excludes))
throw new ArgumentOutOfRangeException(nameof(excludes), "All values cannot be excluded");
//Get a random value unit it is not in the cluded range
do
{
result = Random.Next(Min, Max + 1);
} while (excludes.Contains(result));
return result;
}
public static bool Between(this int num, int lower, int upper, bool inclusive = true)
{
return inclusive
? lower <= num && num <= upper
: lower < num && num < upper;
}
public static string FormatFileSize(double size, string formatString = null, bool roundDown = true)
{
if (roundDown)
{
if (size < 1024) return size.ToInt32().ToString(formatString) + " b";
if (size < 1048576) return (size / 1024).ToInt32().ToString(formatString) + " kb";
return (size / 10485.76 / 100).ToInt32().ToString(formatString) + " mb";
}
if (size < 1024) return Math.Round(size).ToString(formatString) + " b";
if (size < 1048576) return Math.Round(size / 1024).ToString(formatString) + " kb";
return (Math.Round(size / 10485.76) / 100).ToString(formatString) + " mb";
}
public static bool Contains(this int[] numbers, int value)
{
if (numbers == null || numbers.Length < 1) return false;
foreach (var i in numbers)
if (i == value)
return true;
return false;
}
}
} | 35.695122 | 108 | 0.556543 | [
"MIT"
] | UKHomeOffice/Modern-Slavery-Alpha | ModernSlavery.Core.Extensions/Numeric.cs | 2,929 | C# |
// ***********************************************************************
// <copyright file="WriteExpressionCommandExtensions.cs" company="ServiceStack, Inc.">
// Copyright (c) ServiceStack, Inc. All Rights Reserved.
// </copyright>
// <summary>Fork for YetAnotherForum.NET, Licensed under the Apache License, Version 2.0</summary>
// ***********************************************************************
namespace ServiceStack.OrmLite
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using ServiceStack.Text;
/// <summary>
/// Class WriteExpressionCommandExtensions.
/// </summary>
internal static class WriteExpressionCommandExtensions
{
/// <summary>
/// Updates the only.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="model">The model.</param>
/// <param name="onlyFields">The only fields.</param>
/// <param name="commandFilter">The command filter.</param>
/// <returns>System.Int32.</returns>
public static int UpdateOnly<T>(this IDbCommand dbCmd,
T model,
SqlExpression<T> onlyFields,
Action<IDbCommand> commandFilter = null)
{
OrmLiteUtils.AssertNotAnonType<T>();
UpdateOnlySql(dbCmd, model, onlyFields);
commandFilter?.Invoke(dbCmd);
return dbCmd.ExecNonQuery();
}
/// <summary>
/// Updates the only SQL.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="model">The model.</param>
/// <param name="onlyFields">The only fields.</param>
internal static void UpdateOnlySql<T>(this IDbCommand dbCmd, T model, SqlExpression<T> onlyFields)
{
OrmLiteUtils.AssertNotAnonType<T>();
OrmLiteConfig.UpdateFilter?.Invoke(dbCmd, model);
var fieldsToUpdate = onlyFields.UpdateFields.Count == 0
? onlyFields.GetAllFields()
: onlyFields.UpdateFields;
onlyFields.CopyParamsTo(dbCmd);
dbCmd.GetDialectProvider().PrepareUpdateRowStatement(dbCmd, model, fieldsToUpdate);
if (!onlyFields.WhereExpression.IsNullOrEmpty())
dbCmd.CommandText += " " + onlyFields.WhereExpression;
}
/// <summary>
/// Updates the only.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="obj">The object.</param>
/// <param name="onlyFields">The only fields.</param>
/// <param name="where">The where.</param>
/// <param name="commandFilter">The command filter.</param>
/// <returns>System.Int32.</returns>
/// <exception cref="System.ArgumentNullException">onlyFields</exception>
internal static int UpdateOnly<T>(this IDbCommand dbCmd, T obj,
Expression<Func<T, object>> onlyFields = null,
Expression<Func<T, bool>> where = null,
Action<IDbCommand> commandFilter = null)
{
OrmLiteUtils.AssertNotAnonType<T>();
if (onlyFields == null)
throw new ArgumentNullException(nameof(onlyFields));
var q = dbCmd.GetDialectProvider().SqlExpression<T>();
q.Update(onlyFields);
q.Where(where);
return dbCmd.UpdateOnly(obj, q, commandFilter);
}
/// <summary>
/// Updates the only.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="obj">The object.</param>
/// <param name="onlyFields">The only fields.</param>
/// <param name="where">The where.</param>
/// <param name="commandFilter">The command filter.</param>
/// <returns>System.Int32.</returns>
/// <exception cref="System.ArgumentNullException">onlyFields</exception>
internal static int UpdateOnly<T>(this IDbCommand dbCmd, T obj,
string[] onlyFields = null,
Expression<Func<T, bool>> where = null,
Action<IDbCommand> commandFilter = null)
{
OrmLiteUtils.AssertNotAnonType<T>();
if (onlyFields == null)
throw new ArgumentNullException(nameof(onlyFields));
var q = dbCmd.GetDialectProvider().SqlExpression<T>();
q.Update(onlyFields);
q.Where(where);
return dbCmd.UpdateOnly(obj, q, commandFilter);
}
/// <summary>
/// Updates the only.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="updateFields">The update fields.</param>
/// <param name="q">The q.</param>
/// <param name="commandFilter">The command filter.</param>
/// <returns>System.Int32.</returns>
internal static int UpdateOnly<T>(this IDbCommand dbCmd,
Expression<Func<T>> updateFields,
SqlExpression<T> q,
Action<IDbCommand> commandFilter = null)
{
OrmLiteUtils.AssertNotAnonType<T>();
var cmd = dbCmd.InitUpdateOnly(updateFields, q);
commandFilter?.Invoke(cmd);
return cmd.ExecNonQuery();
}
/// <summary>
/// Initializes the update only.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="updateFields">The update fields.</param>
/// <param name="q">The q.</param>
/// <returns>IDbCommand.</returns>
/// <exception cref="System.ArgumentNullException">updateFields</exception>
internal static IDbCommand InitUpdateOnly<T>(this IDbCommand dbCmd, Expression<Func<T>> updateFields, SqlExpression<T> q)
{
if (updateFields == null)
throw new ArgumentNullException(nameof(updateFields));
OrmLiteConfig.UpdateFilter?.Invoke(dbCmd, updateFields.EvalFactoryFn());
q.CopyParamsTo(dbCmd);
var updateFieldValues = updateFields.AssignedValues();
dbCmd.GetDialectProvider().PrepareUpdateRowStatement<T>(dbCmd, updateFieldValues, q.WhereExpression);
return dbCmd;
}
/// <summary>
/// Updates the only.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="updateFields">The update fields.</param>
/// <param name="whereExpression">The where expression.</param>
/// <param name="dbParams">The database parameters.</param>
/// <param name="commandFilter">The command filter.</param>
/// <returns>System.Int32.</returns>
internal static int UpdateOnly<T>(this IDbCommand dbCmd,
Expression<Func<T>> updateFields,
string whereExpression,
IEnumerable<IDbDataParameter> dbParams,
Action<IDbCommand> commandFilter = null)
{
OrmLiteUtils.AssertNotAnonType<T>();
var cmd = dbCmd.InitUpdateOnly(updateFields, whereExpression, dbParams);
commandFilter?.Invoke(cmd);
return cmd.ExecNonQuery();
}
/// <summary>
/// Initializes the update only.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="updateFields">The update fields.</param>
/// <param name="whereExpression">The where expression.</param>
/// <param name="sqlParams">The SQL parameters.</param>
/// <returns>IDbCommand.</returns>
/// <exception cref="System.ArgumentNullException">updateFields</exception>
internal static IDbCommand InitUpdateOnly<T>(this IDbCommand dbCmd, Expression<Func<T>> updateFields, string whereExpression, IEnumerable<IDbDataParameter> sqlParams)
{
if (updateFields == null)
throw new ArgumentNullException(nameof(updateFields));
OrmLiteConfig.UpdateFilter?.Invoke(dbCmd, updateFields.EvalFactoryFn());
dbCmd.SetParameters(sqlParams);
var updateFieldValues = updateFields.AssignedValues();
dbCmd.GetDialectProvider().PrepareUpdateRowStatement<T>(dbCmd, updateFieldValues, whereExpression);
return dbCmd;
}
/// <summary>
/// Updates the add.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="updateFields">The update fields.</param>
/// <param name="q">The q.</param>
/// <param name="commandFilter">The command filter.</param>
/// <returns>System.Int32.</returns>
public static int UpdateAdd<T>(this IDbCommand dbCmd,
Expression<Func<T>> updateFields,
SqlExpression<T> q,
Action<IDbCommand> commandFilter)
{
var cmd = dbCmd.InitUpdateAdd(updateFields, q);
commandFilter?.Invoke(cmd);
return cmd.ExecNonQuery();
}
/// <summary>
/// Initializes the update add.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="updateFields">The update fields.</param>
/// <param name="q">The q.</param>
/// <returns>IDbCommand.</returns>
/// <exception cref="System.ArgumentNullException">updateFields</exception>
internal static IDbCommand InitUpdateAdd<T>(this IDbCommand dbCmd, Expression<Func<T>> updateFields, SqlExpression<T> q)
{
if (updateFields == null)
throw new ArgumentNullException(nameof(updateFields));
OrmLiteConfig.UpdateFilter?.Invoke(dbCmd, updateFields.EvalFactoryFn());
q.CopyParamsTo(dbCmd);
var updateFieldValues = updateFields.AssignedValues();
dbCmd.GetDialectProvider().PrepareUpdateRowAddStatement<T>(dbCmd, updateFieldValues, q.WhereExpression);
return dbCmd;
}
/// <summary>
/// Updates the only.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="updateFields">The update fields.</param>
/// <param name="where">The where.</param>
/// <param name="commandFilter">The command filter.</param>
/// <returns>System.Int32.</returns>
/// <exception cref="System.ArgumentNullException">updateFields</exception>
public static int UpdateOnly<T>(this IDbCommand dbCmd,
Dictionary<string, object> updateFields,
Expression<Func<T, bool>> where,
Action<IDbCommand> commandFilter = null)
{
OrmLiteUtils.AssertNotAnonType<T>();
if (updateFields == null)
throw new ArgumentNullException(nameof(updateFields));
OrmLiteConfig.UpdateFilter?.Invoke(dbCmd, updateFields.ToFilterType<T>());
var q = dbCmd.GetDialectProvider().SqlExpression<T>();
q.Where(where);
q.PrepareUpdateStatement(dbCmd, updateFields);
return dbCmd.UpdateAndVerify<T>(commandFilter, updateFields.ContainsKey(ModelDefinition.RowVersionName));
}
/// <summary>
/// Gets the update only where expression.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dialectProvider">The dialect provider.</param>
/// <param name="updateFields">The update fields.</param>
/// <param name="args">The arguments.</param>
/// <returns>System.String.</returns>
/// <exception cref="System.NotSupportedException">'{typeof(T).Name}' does not have a primary key</exception>
internal static string GetUpdateOnlyWhereExpression<T>(this IOrmLiteDialectProvider dialectProvider,
Dictionary<string, object> updateFields, out object[] args)
{
var modelDef = typeof(T).GetModelDefinition();
var pkField = modelDef.PrimaryKey;
if (pkField == null)
throw new NotSupportedException($"'{typeof(T).Name}' does not have a primary key");
var idValue = updateFields.TryRemove(pkField.Name, out var nameValue)
? nameValue
: pkField.Alias != null && updateFields.TryRemove(pkField.Alias, out var aliasValue)
? aliasValue
: null;
if (idValue == null)
{
var caseInsensitiveMap =
new Dictionary<string, object>(updateFields, StringComparer.InvariantCultureIgnoreCase);
idValue = caseInsensitiveMap.TryRemove(pkField.Name, out nameValue)
? nameValue
: pkField.Alias != null && caseInsensitiveMap.TryRemove(pkField.Alias, out aliasValue)
? aliasValue
: new NotSupportedException(
$"UpdateOnly<{typeof(T).Name}> requires a '{pkField.Name}' Primary Key Value");
}
if (modelDef.RowVersion == null || !updateFields.TryGetValue(ModelDefinition.RowVersionName, out var rowVersion))
{
args = new[] { idValue };
return "(" + pkField.FieldName + " = {0})";
}
args = new[] { idValue, rowVersion };
return "(" + dialectProvider.GetQuotedColumnName(pkField.FieldName) + " = {0} AND " + dialectProvider.GetRowVersionColumn(modelDef.RowVersion) + " = {1})";
}
/// <summary>
/// Updates the only.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="updateFields">The update fields.</param>
/// <param name="commandFilter">The command filter.</param>
/// <returns>System.Int32.</returns>
public static int UpdateOnly<T>(this IDbCommand dbCmd,
Dictionary<string, object> updateFields,
Action<IDbCommand> commandFilter = null)
{
var whereExpr = dbCmd.GetDialectProvider().GetUpdateOnlyWhereExpression<T>(updateFields, out var exprArgs);
dbCmd.PrepareUpdateOnly<T>(updateFields, whereExpr, exprArgs);
return dbCmd.UpdateAndVerify<T>(commandFilter, updateFields.ContainsKey(ModelDefinition.RowVersionName));
}
/// <summary>
/// Updates the only.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="updateFields">The update fields.</param>
/// <param name="whereExpression">The where expression.</param>
/// <param name="whereParams">The where parameters.</param>
/// <param name="commandFilter">The command filter.</param>
/// <returns>System.Int32.</returns>
public static int UpdateOnly<T>(this IDbCommand dbCmd,
Dictionary<string, object> updateFields,
string whereExpression,
object[] whereParams,
Action<IDbCommand> commandFilter = null)
{
dbCmd.PrepareUpdateOnly<T>(updateFields, whereExpression, whereParams);
return dbCmd.UpdateAndVerify<T>(commandFilter, updateFields.ContainsKey(ModelDefinition.RowVersionName));
}
/// <summary>
/// Prepares the update only.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="updateFields">The update fields.</param>
/// <param name="whereExpression">The where expression.</param>
/// <param name="whereParams">The where parameters.</param>
/// <exception cref="System.ArgumentNullException">updateFields</exception>
internal static void PrepareUpdateOnly<T>(this IDbCommand dbCmd, Dictionary<string, object> updateFields, string whereExpression, object[] whereParams)
{
if (updateFields == null)
throw new ArgumentNullException(nameof(updateFields));
OrmLiteConfig.UpdateFilter?.Invoke(dbCmd, updateFields.ToFilterType<T>());
var q = dbCmd.GetDialectProvider().SqlExpression<T>();
q.Where(whereExpression, whereParams);
q.PrepareUpdateStatement(dbCmd, updateFields);
}
/// <summary>
/// Updates the non defaults.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="item">The item.</param>
/// <param name="where">The where.</param>
/// <returns>System.Int32.</returns>
public static int UpdateNonDefaults<T>(this IDbCommand dbCmd, T item, Expression<Func<T, bool>> where)
{
OrmLiteConfig.UpdateFilter?.Invoke(dbCmd, item);
var q = dbCmd.GetDialectProvider().SqlExpression<T>();
q.Where(@where);
q.PrepareUpdateStatement(dbCmd, item, excludeDefaults: true);
return dbCmd.ExecNonQuery();
}
/// <summary>
/// Updates the specified item.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="item">The item.</param>
/// <param name="expression">The expression.</param>
/// <param name="commandFilter">The command filter.</param>
/// <returns>System.Int32.</returns>
public static int Update<T>(this IDbCommand dbCmd, T item, Expression<Func<T, bool>> expression, Action<IDbCommand> commandFilter = null)
{
OrmLiteConfig.UpdateFilter?.Invoke(dbCmd, item);
var q = dbCmd.GetDialectProvider().SqlExpression<T>();
q.Where(expression);
q.PrepareUpdateStatement(dbCmd, item);
commandFilter?.Invoke(dbCmd);
return dbCmd.ExecNonQuery();
}
/// <summary>
/// Updates the specified update only.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="updateOnly">The update only.</param>
/// <param name="where">The where.</param>
/// <param name="commandFilter">The command filter.</param>
/// <returns>System.Int32.</returns>
public static int Update<T>(this IDbCommand dbCmd, object updateOnly, Expression<Func<T, bool>> where = null, Action<IDbCommand> commandFilter = null)
{
OrmLiteUtils.AssertNotAnonType<T>();
OrmLiteConfig.UpdateFilter?.Invoke(dbCmd, updateOnly.ToFilterType<T>());
var q = dbCmd.GetDialectProvider().SqlExpression<T>();
var whereSql = q.Where(where).WhereExpression;
q.CopyParamsTo(dbCmd);
var hadRowVersion = dbCmd.PrepareUpdateAnonSql<T>(dbCmd.GetDialectProvider(), updateOnly, whereSql);
return dbCmd.UpdateAndVerify<T>(commandFilter, hadRowVersion);
}
/// <summary>
/// Prepares the update anon SQL.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="dialectProvider">The dialect provider.</param>
/// <param name="updateOnly">The update only.</param>
/// <param name="whereSql">The where SQL.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
internal static bool PrepareUpdateAnonSql<T>(this IDbCommand dbCmd, IOrmLiteDialectProvider dialectProvider, object updateOnly, string whereSql)
{
var sql = StringBuilderCache.Allocate();
var modelDef = typeof(T).GetModelDefinition();
var fields = modelDef.FieldDefinitionsArray;
var fieldDefs = new List<FieldDefinition>();
if (updateOnly is IDictionary d)
{
foreach (DictionaryEntry entry in d)
{
var fieldDef = modelDef.GetFieldDefinition((string)entry.Key);
if (fieldDef == null || fieldDef.ShouldSkipUpdate())
continue;
fieldDefs.Add(fieldDef);
}
}
else
{
foreach (var setField in updateOnly.GetType().GetPublicProperties())
{
var fieldDef = fields.FirstOrDefault(x =>
string.Equals(x.Name, setField.Name, StringComparison.OrdinalIgnoreCase));
if (fieldDef == null || fieldDef.ShouldSkipUpdate())
continue;
fieldDefs.Add(fieldDef);
}
}
var hadRowVersion = false;
foreach (var fieldDef in fieldDefs)
{
var value = fieldDef.GetValue(updateOnly);
if (fieldDef.IsPrimaryKey || fieldDef.AutoIncrement || fieldDef.IsRowVersion)
{
if (fieldDef.IsRowVersion)
hadRowVersion = true;
whereSql += string.IsNullOrEmpty(whereSql) ? "WHERE " : " AND ";
whereSql += $"{dialectProvider.GetQuotedColumnName(fieldDef.FieldName)} = {dialectProvider.AddQueryParam(dbCmd, value, fieldDef).ParameterName}";
continue;
}
if (sql.Length > 0)
sql.Append(", ");
sql
.Append(dialectProvider.GetQuotedColumnName(fieldDef.FieldName))
.Append("=")
.Append(dialectProvider.GetUpdateParam(dbCmd, value, fieldDef));
}
dbCmd.CommandText = $"UPDATE {dialectProvider.GetQuotedTableName(modelDef)} " +
$"SET {StringBuilderCache.ReturnAndFree(sql)} {whereSql}";
return hadRowVersion;
}
/// <summary>
/// Inserts the only.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="obj">The object.</param>
/// <param name="onlyFields">The only fields.</param>
/// <param name="selectIdentity">if set to <c>true</c> [select identity].</param>
/// <returns>System.Int64.</returns>
public static long InsertOnly<T>(this IDbCommand dbCmd, T obj, string[] onlyFields, bool selectIdentity)
{
OrmLiteConfig.InsertFilter?.Invoke(dbCmd, obj);
var dialectProvider = dbCmd.GetDialectProvider();
var sql = dialectProvider.ToInsertRowStatement(dbCmd, obj, onlyFields);
dialectProvider.SetParameterValues<T>(dbCmd, obj);
if (selectIdentity)
return dbCmd.ExecLongScalar(sql + dialectProvider.GetLastInsertIdSqlSuffix<T>());
return dbCmd.ExecuteSql(sql);
}
/// <summary>
/// Inserts the only.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="insertFields">The insert fields.</param>
/// <param name="selectIdentity">if set to <c>true</c> [select identity].</param>
/// <returns>System.Int64.</returns>
public static long InsertOnly<T>(this IDbCommand dbCmd, Expression<Func<T>> insertFields, bool selectIdentity)
{
dbCmd.InitInsertOnly(insertFields);
if (selectIdentity)
return dbCmd.ExecLongScalar(dbCmd.CommandText + dbCmd.GetDialectProvider().GetLastInsertIdSqlSuffix<T>());
return dbCmd.ExecuteNonQuery();
}
/// <summary>
/// Initializes the insert only.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="insertFields">The insert fields.</param>
/// <returns>IDbCommand.</returns>
/// <exception cref="System.ArgumentNullException">insertFields</exception>
internal static IDbCommand InitInsertOnly<T>(this IDbCommand dbCmd, Expression<Func<T>> insertFields)
{
if (insertFields == null)
throw new ArgumentNullException(nameof(insertFields));
OrmLiteConfig.InsertFilter?.Invoke(dbCmd, insertFields.EvalFactoryFn());
var fieldValuesMap = insertFields.AssignedValues();
dbCmd.GetDialectProvider().PrepareInsertRowStatement<T>(dbCmd, fieldValuesMap);
return dbCmd;
}
/// <summary>
/// Deletes the specified where.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="where">The where.</param>
/// <param name="commandFilter">The command filter.</param>
/// <returns>System.Int32.</returns>
public static int Delete<T>(this IDbCommand dbCmd, Expression<Func<T, bool>> where, Action<IDbCommand> commandFilter = null)
{
var ev = dbCmd.GetDialectProvider().SqlExpression<T>();
ev.Where(where);
return dbCmd.Delete(ev, commandFilter);
}
/// <summary>
/// Deletes the specified where.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="where">The where.</param>
/// <param name="commandFilter">The command filter.</param>
/// <returns>System.Int32.</returns>
public static int Delete<T>(this IDbCommand dbCmd, SqlExpression<T> where, Action<IDbCommand> commandFilter = null)
{
var sql = where.ToDeleteRowStatement();
return dbCmd.ExecuteSql(sql, where.Params, commandFilter);
}
/// <summary>
/// Deletes the where.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dbCmd">The database command.</param>
/// <param name="whereFilter">The where filter.</param>
/// <param name="whereParams">The where parameters.</param>
/// <returns>System.Int32.</returns>
public static int DeleteWhere<T>(this IDbCommand dbCmd, string whereFilter, object[] whereParams)
{
var q = dbCmd.GetDialectProvider().SqlExpression<T>();
q.Where(whereFilter, whereParams);
var sql = q.ToDeleteRowStatement();
return dbCmd.ExecuteSql(sql, q.Params);
}
}
}
| 44.580542 | 175 | 0.572159 | [
"Apache-2.0"
] | YAFNET/YAFNET | yafsrc/ServiceStack/ServiceStack.OrmLite/Expressions/WriteExpressionCommandExtensions.cs | 27,954 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Test3x.Domain.Entities;
using ShardingCore.VirtualRoutes.Months;
namespace ShardingCore.Test3x.Shardings
{
public class LogMonthLongvirtualRoute:AbstractSimpleShardingMonthKeyLongVirtualTableRoute<LogMonthLong>
{
protected override bool EnableHintRoute => true;
public override bool? EnableRouteParseCompileCache => true;
public override bool AutoCreateTableByTime()
{
return true;
}
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
public override void Configure(EntityMetadataTableBuilder<LogMonthLong> builder)
{
builder.ShardingProperty(o => o.LogTime);
}
}
}
| 27.545455 | 107 | 0.70187 | [
"Apache-2.0"
] | ChangYinHan/sharding-core | test/ShardingCore.Test3x/Shardings/LogMonthLongvirtualRoute.cs | 911 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using DlibFaceLandmarkDetector;
using OpenCVForUnity;
using OpenCVForUnity.RectangleTrack;
#if UNITY_5_3 || UNITY_5_3_OR_NEWER
using UnityEngine.SceneManagement;
#endif
namespace FaceMaskExample
{
/// <summary>
/// VideoCapture FaceMask Example
/// </summary>
[RequireComponent (typeof(TrackedMeshOverlay))]
public class VideoCaptureFaceMaskExample : MonoBehaviour
{
[HeaderAttribute ("FaceMaskData")]
/// <summary>
/// The face mask data list.
/// </summary>
public List<FaceMaskData> faceMaskDatas;
[HeaderAttribute ("Option")]
/// <summary>
/// Determines if use dlib face detector.
/// </summary>
public bool useDlibFaceDetecter = true;
/// <summary>
/// The use dlib face detecter toggle.
/// </summary>
public Toggle useDlibFaceDetecterToggle;
/// <summary>
/// Determines if enables noise filter.
/// </summary>
public bool enableNoiseFilter = true;
/// <summary>
/// The enable noise filter toggle.
/// </summary>
public Toggle enableNoiseFilterToggle;
/// <summary>
/// Determines if enables color correction.
/// </summary>
public bool enableColorCorrection = true;
/// <summary>
/// The enable color correction toggle.
/// </summary>
public Toggle enableColorCorrectionToggle;
/// <summary>
/// Determines if filters non frontal faces.
/// </summary>
public bool filterNonFrontalFaces = false;
/// <summary>
/// The filter non frontal faces toggle.
/// </summary>
public Toggle filterNonFrontalFacesToggle;
/// <summary>
/// The frontal face rate lower limit.
/// </summary>
[Range (0.0f, 1.0f)]
public float frontalFaceRateLowerLimit;
/// <summary>
/// Determines if displays face rects.
/// </summary>
public bool displayFaceRects = false;
/// <summary>
/// The toggle for switching face rects display state
/// </summary>
public Toggle displayFaceRectsToggle;
/// <summary>
/// Determines if displays debug face points.
/// </summary>
public bool displayDebugFacePoints = false;
/// <summary>
/// The toggle for switching debug face points display state.
/// </summary>
public Toggle displayDebugFacePointsToggle;
/// <summary>
/// The width of the frame.
/// </summary>
double frameWidth = 320;
/// <summary>
/// The height of the frame.
/// </summary>
double frameHeight = 240;
/// <summary>
/// The capture.
/// </summary>
VideoCapture capture;
/// <summary>
/// The rgb mat.
/// </summary>
Mat rgbMat;
/// <summary>
/// The gray mat.
/// </summary>
Mat grayMat;
/// <summary>
/// The texture.
/// </summary>
Texture2D texture;
/// <summary>
/// The cascade.
/// </summary>
CascadeClassifier cascade;
/// <summary>
/// The detection based tracker.
/// </summary>
RectangleTracker rectangleTracker;
/// <summary>
/// The face landmark detector.
/// </summary>
FaceLandmarkDetector faceLandmarkDetector;
/// <summary>
/// The mean points filter dictionary.
/// </summary>
Dictionary<int, LowPassPointsFilter> lowPassFilterDict;
/// <summary>
/// The optical flow points filter dictionary.
/// </summary>
Dictionary<int, OFPointsFilter> opticalFlowFilterDict;
/// <summary>
/// The face mask color corrector.
/// </summary>
FaceMaskColorCorrector faceMaskColorCorrector;
/// <summary>
/// The frontal face checker.
/// </summary>
FrontalFaceChecker frontalFaceChecker;
/// <summary>
/// The mesh overlay.
/// </summary>
TrackedMeshOverlay meshOverlay;
/// <summary>
/// The Shader.PropertyToID for "_Fade".
/// </summary>
int shader_FadeID;
/// <summary>
/// The Shader.PropertyToID for "_ColorCorrection".
/// </summary>
int shader_ColorCorrectionID;
/// <summary>
/// The Shader.PropertyToID for "_LUTTex".
/// </summary>
int shader_LUTTexID;
/// <summary>
/// The face mask texture.
/// </summary>
Texture2D faceMaskTexture;
/// <summary>
/// The face mask mat.
/// </summary>
Mat faceMaskMat;
/// <summary>
/// The index number of face mask data.
/// </summary>
int faceMaskDataIndex = 0;
/// <summary>
/// The detected face rect in mask mat.
/// </summary>
UnityEngine.Rect faceRectInMask;
/// <summary>
/// The detected face landmark points in mask mat.
/// </summary>
List<Vector2> faceLandmarkPointsInMask;
/// <summary>
/// The haarcascade_frontalface_alt_xml_filepath.
/// </summary>
string haarcascade_frontalface_alt_xml_filepath;
/// <summary>
/// The sp_human_face_68_dat_filepath.
/// </summary>
string sp_human_face_68_dat_filepath;
/// <summary>
/// The couple_avi_filepath.
/// </summary>
string couple_avi_filepath;
#if UNITY_WEBGL && !UNITY_EDITOR
Stack<IEnumerator> coroutines = new Stack<IEnumerator> ();
#endif
// Use this for initialization
void Start ()
{
capture = new VideoCapture ();
#if UNITY_WEBGL && !UNITY_EDITOR
var getFilePath_Coroutine = GetFilePath ();
coroutines.Push (getFilePath_Coroutine);
StartCoroutine (getFilePath_Coroutine);
#else
haarcascade_frontalface_alt_xml_filepath = OpenCVForUnity.Utils.getFilePath ("haarcascade_frontalface_alt.xml");
sp_human_face_68_dat_filepath = DlibFaceLandmarkDetector.Utils.getFilePath ("sp_human_face_68.dat");
couple_avi_filepath = OpenCVForUnity.Utils.getFilePath ("dance.avi");
Run ();
#endif
}
#if UNITY_WEBGL && !UNITY_EDITOR
private IEnumerator GetFilePath ()
{
var getFilePathAsync_0_Coroutine = OpenCVForUnity.Utils.getFilePathAsync ("haarcascade_frontalface_alt.xml", (result) => {
haarcascade_frontalface_alt_xml_filepath = result;
});
coroutines.Push (getFilePathAsync_0_Coroutine);
yield return StartCoroutine (getFilePathAsync_0_Coroutine);
var getFilePathAsync_1_Coroutine = DlibFaceLandmarkDetector.Utils.getFilePathAsync ("sp_human_face_68.dat", (result) => {
sp_human_face_68_dat_filepath = result;
});
coroutines.Push (getFilePathAsync_1_Coroutine);
yield return StartCoroutine (getFilePathAsync_1_Coroutine);
var getFilePathAsync_2_Coroutine = OpenCVForUnity.Utils.getFilePathAsync ("dance.avi", (result) => {
couple_avi_filepath = result;
});
coroutines.Push (getFilePathAsync_2_Coroutine);
yield return StartCoroutine (getFilePathAsync_2_Coroutine);
coroutines.Clear ();
Run ();
}
#endif
private void Run ()
{
meshOverlay = this.GetComponent<TrackedMeshOverlay> ();
shader_FadeID = Shader.PropertyToID("_Fade");
shader_ColorCorrectionID = Shader.PropertyToID("_ColorCorrection");
shader_LUTTexID = Shader.PropertyToID("_LUTTex");
rectangleTracker = new RectangleTracker ();
frontalFaceChecker = new FrontalFaceChecker((float)frameWidth, (float)frameHeight);
faceLandmarkDetector = new FaceLandmarkDetector (sp_human_face_68_dat_filepath);
lowPassFilterDict = new Dictionary<int, LowPassPointsFilter> ();
opticalFlowFilterDict = new Dictionary<int, OFPointsFilter> ();
faceMaskColorCorrector = new FaceMaskColorCorrector ();
rgbMat = new Mat ();
capture.open (couple_avi_filepath);
if (capture.isOpened ()) {
Debug.Log ("capture.isOpened() true");
} else {
Debug.Log ("capture.isOpened() false");
}
Debug.Log ("CAP_PROP_FORMAT: " + capture.get (Videoio.CAP_PROP_FORMAT));
Debug.Log ("CV_CAP_PROP_PREVIEW_FORMAT: " + capture.get (Videoio.CV_CAP_PROP_PREVIEW_FORMAT));
Debug.Log ("CAP_PROP_POS_MSEC: " + capture.get (Videoio.CAP_PROP_POS_MSEC));
Debug.Log ("CAP_PROP_POS_FRAMES: " + capture.get (Videoio.CAP_PROP_POS_FRAMES));
Debug.Log ("CAP_PROP_POS_AVI_RATIO: " + capture.get (Videoio.CAP_PROP_POS_AVI_RATIO));
Debug.Log ("CAP_PROP_FRAME_COUNT: " + capture.get (Videoio.CAP_PROP_FRAME_COUNT));
Debug.Log ("CAP_PROP_FPS: " + capture.get (Videoio.CAP_PROP_FPS));
Debug.Log ("CAP_PROP_FRAME_WIDTH: " + capture.get (Videoio.CAP_PROP_FRAME_WIDTH));
Debug.Log ("CAP_PROP_FRAME_HEIGHT: " + capture.get (Videoio.CAP_PROP_FRAME_HEIGHT));
texture = new Texture2D ((int)(frameWidth), (int)(frameHeight), TextureFormat.RGB24, false);
gameObject.transform.localScale = new Vector3 ((float)frameWidth, (float)frameHeight, 1);
float widthScale = (float)Screen.width / (float)frameWidth;
float heightScale = (float)Screen.height / (float)frameHeight;
if (widthScale < heightScale) {
Camera.main.orthographicSize = ((float)frameWidth * (float)Screen.height / (float)Screen.width) / 2;
} else {
Camera.main.orthographicSize = (float)frameHeight / 2;
}
gameObject.GetComponent<Renderer> ().material.mainTexture = texture;
meshOverlay.UpdateOverlayTransform (gameObject.transform);
grayMat = new Mat ((int)frameHeight, (int)frameWidth, CvType.CV_8UC1);
cascade = new CascadeClassifier (haarcascade_frontalface_alt_xml_filepath);
// if (cascade.empty ()) {
// Debug.LogError ("cascade file is not loaded.Please copy from “FaceTrackerExample/StreamingAssets/” to “Assets/StreamingAssets/” folder. ");
// }
displayFaceRectsToggle.isOn = displayFaceRects;
useDlibFaceDetecterToggle.isOn = useDlibFaceDetecter;
enableNoiseFilterToggle.isOn = enableNoiseFilter;
enableColorCorrectionToggle.isOn = enableColorCorrection;
filterNonFrontalFacesToggle.isOn = filterNonFrontalFaces;
displayDebugFacePointsToggle.isOn = displayDebugFacePoints;
OnChangeFaceMaskButtonClick ();
}
// Update is called once per frame
void Update ()
{
// loop play.
if (capture.get (Videoio.CAP_PROP_POS_FRAMES) >= capture.get (Videoio.CAP_PROP_FRAME_COUNT))
capture.set (Videoio.CAP_PROP_POS_FRAMES, 0);
if (capture.grab ()) {
capture.retrieve (rgbMat, 0);
Imgproc.cvtColor (rgbMat, rgbMat, Imgproc.COLOR_BGR2RGB);
//Debug.Log ("Mat toString " + rgbMat.ToString ());
// detect faces.
List<OpenCVForUnity.Rect> detectResult = new List<OpenCVForUnity.Rect> ();
if (useDlibFaceDetecter) {
OpenCVForUnityUtils.SetImage (faceLandmarkDetector, rgbMat);
List<UnityEngine.Rect> result = faceLandmarkDetector.Detect ();
foreach (var unityRect in result) {
detectResult.Add (new OpenCVForUnity.Rect ((int)unityRect.x, (int)unityRect.y, (int)unityRect.width, (int)unityRect.height));
}
} else {
// convert image to greyscale.
Imgproc.cvtColor (rgbMat, grayMat, Imgproc.COLOR_RGB2GRAY);
using (Mat equalizeHistMat = new Mat ())
using (MatOfRect faces = new MatOfRect ()) {
Imgproc.equalizeHist (grayMat, equalizeHistMat);
cascade.detectMultiScale (equalizeHistMat, faces, 1.1f, 2, 0 | Objdetect.CASCADE_SCALE_IMAGE, new OpenCVForUnity.Size (equalizeHistMat.cols () * 0.15, equalizeHistMat.cols () * 0.15), new Size ());
detectResult = faces.toList ();
// adjust to Dilb's result.
foreach (OpenCVForUnity.Rect r in detectResult) {
r.y += (int)(r.height * 0.1f);
}
}
}
// face tracking.
rectangleTracker.UpdateTrackedObjects (detectResult);
List<TrackedRect> trackedRects = new List<TrackedRect> ();
rectangleTracker.GetObjects (trackedRects, true);
// create noise filter.
foreach (var openCVRect in trackedRects) {
if (openCVRect.state == TrackedState.NEW) {
if (!lowPassFilterDict.ContainsKey(openCVRect.id))
lowPassFilterDict.Add (openCVRect.id, new LowPassPointsFilter((int)faceLandmarkDetector.GetShapePredictorNumParts()));
if (!opticalFlowFilterDict.ContainsKey(openCVRect.id))
opticalFlowFilterDict.Add (openCVRect.id, new OFPointsFilter((int)faceLandmarkDetector.GetShapePredictorNumParts()));
}else if (openCVRect.state == TrackedState.DELETED){
if (lowPassFilterDict.ContainsKey (openCVRect.id)) {
lowPassFilterDict [openCVRect.id].Dispose ();
lowPassFilterDict.Remove (openCVRect.id);
}
if (opticalFlowFilterDict.ContainsKey (openCVRect.id)) {
opticalFlowFilterDict [openCVRect.id].Dispose ();
opticalFlowFilterDict.Remove (openCVRect.id);
}
}
}
// create LUT texture.
foreach (var openCVRect in trackedRects) {
if (openCVRect.state == TrackedState.NEW) {
faceMaskColorCorrector.CreateLUTTex (openCVRect.id);
}else if (openCVRect.state == TrackedState.DELETED) {
faceMaskColorCorrector.DeleteLUTTex (openCVRect.id);
}
}
// detect face landmark points.
OpenCVForUnityUtils.SetImage (faceLandmarkDetector, rgbMat);
List<List<Vector2>> landmarkPoints = new List<List<Vector2>> ();
for (int i = 0; i < trackedRects.Count; i++) {
TrackedRect tr = trackedRects [i];
UnityEngine.Rect rect = new UnityEngine.Rect (tr.x, tr.y, tr.width, tr.height);
List<Vector2> points = faceLandmarkDetector.DetectLandmark (rect);
// apply noise filter.
if (enableNoiseFilter) {
if (tr.state > TrackedState.NEW && tr.state < TrackedState.DELETED) {
opticalFlowFilterDict [tr.id].Process (rgbMat, points, points);
lowPassFilterDict [tr.id].Process (rgbMat, points, points);
}
}
landmarkPoints.Add (points);
}
// face masking.
if (faceMaskTexture != null && landmarkPoints.Count >= 1) { // Apply face masking between detected faces and a face mask image.
float maskImageWidth = faceMaskTexture.width;
float maskImageHeight = faceMaskTexture.height;
TrackedRect tr;
for (int i = 0; i < trackedRects.Count; i++) {
tr = trackedRects [i];
if (tr.state == TrackedState.NEW) {
meshOverlay.CreateObject (tr.id, faceMaskTexture);
}
if (tr.state < TrackedState.DELETED) {
MaskFace (meshOverlay, tr, landmarkPoints [i], faceLandmarkPointsInMask, maskImageWidth, maskImageHeight);
if (enableColorCorrection) {
CorrectFaceMaskColor (tr.id, faceMaskMat, rgbMat, faceLandmarkPointsInMask, landmarkPoints [i]);
}
} else if (tr.state == TrackedState.DELETED) {
meshOverlay.DeleteObject (tr.id);
}
}
} else if (landmarkPoints.Count >= 1) { // Apply face masking between detected faces.
float maskImageWidth = texture.width;
float maskImageHeight = texture.height;
TrackedRect tr;
for (int i = 0; i < trackedRects.Count; i++) {
tr = trackedRects [i];
if (tr.state == TrackedState.NEW) {
meshOverlay.CreateObject (tr.id, texture);
}
if (tr.state < TrackedState.DELETED) {
MaskFace (meshOverlay, tr, landmarkPoints [i], landmarkPoints [0], maskImageWidth, maskImageHeight);
if (enableColorCorrection) {
CorrectFaceMaskColor (tr.id, rgbMat, rgbMat, landmarkPoints [0], landmarkPoints [i]);
}
} else if (tr.state == TrackedState.DELETED) {
meshOverlay.DeleteObject (tr.id);
}
}
}
// draw face rects.
if (displayFaceRects) {
for (int i = 0; i < detectResult.Count; i++) {
UnityEngine.Rect rect = new UnityEngine.Rect (detectResult [i].x, detectResult [i].y, detectResult [i].width, detectResult [i].height);
OpenCVForUnityUtils.DrawFaceRect (rgbMat, rect, new Scalar (255, 0, 0, 255), 2);
}
for (int i = 0; i < trackedRects.Count; i++) {
UnityEngine.Rect rect = new UnityEngine.Rect (trackedRects [i].x, trackedRects [i].y, trackedRects [i].width, trackedRects [i].height);
OpenCVForUnityUtils.DrawFaceRect (rgbMat, rect, new Scalar (255, 255, 0, 255), 2);
//Imgproc.putText (rgbaMat, " " + frontalFaceChecker.GetFrontalFaceAngles (landmarkPoints [i]), new Point (rect.xMin, rect.yMin - 10), Core.FONT_HERSHEY_SIMPLEX, 0.5, new Scalar (255, 255, 255, 255), 2, Imgproc.LINE_AA, false);
//Imgproc.putText (rgbaMat, " " + frontalFaceChecker.GetFrontalFaceRate (landmarkPoints [i]), new Point (rect.xMin, rect.yMin - 10), Core.FONT_HERSHEY_SIMPLEX, 0.5, new Scalar (255, 255, 255, 255), 2, Imgproc.LINE_AA, false);
}
}
// draw face points.
if (displayDebugFacePoints) {
for (int i = 0; i < landmarkPoints.Count; i++) {
OpenCVForUnityUtils.DrawFaceLandmark (rgbMat, landmarkPoints [i], new Scalar (0, 255, 0, 255), 2);
}
}
// display face mask image.
if (faceMaskTexture != null && faceMaskMat != null) {
if (displayFaceRects) {
OpenCVForUnityUtils.DrawFaceRect (faceMaskMat, faceRectInMask, new Scalar (255, 0, 0, 255), 2);
}
if (displayDebugFacePoints) {
OpenCVForUnityUtils.DrawFaceLandmark (faceMaskMat, faceLandmarkPointsInMask, new Scalar (0, 255, 0, 255), 2);
}
float scale = (rgbMat.width () / 4f) / faceMaskMat.width ();
float tx = rgbMat.width () - faceMaskMat.width () * scale;
float ty = 0.0f;
Mat trans = new Mat (2, 3, CvType.CV_32F);//1.0, 0.0, tx, 0.0, 1.0, ty);
trans.put (0, 0, scale);
trans.put (0, 1, 0.0f);
trans.put (0, 2, tx);
trans.put (1, 0, 0.0f);
trans.put (1, 1, scale);
trans.put (1, 2, ty);
Imgproc.warpAffine (faceMaskMat, rgbMat, trans, rgbMat.size (), Imgproc.INTER_LINEAR, Core.BORDER_TRANSPARENT, new Scalar (0));
if (displayFaceRects || displayDebugFacePointsToggle)
OpenCVForUnity.Utils.texture2DToMat (faceMaskTexture, faceMaskMat);
}
// Imgproc.putText (rgbMat, "W:" + rgbMat.width () + " H:" + rgbMat.height () + " SO:" + Screen.orientation, new Point (5, rgbMat.rows () - 10), Core.FONT_HERSHEY_SIMPLEX, 0.5, new Scalar (255, 255, 255), 1, Imgproc.LINE_AA, false);
OpenCVForUnity.Utils.fastMatToTexture2D (rgbMat, texture);
}
}
private void MaskFace (TrackedMeshOverlay meshOverlay, TrackedRect tr, List<Vector2> landmarkPoints, List<Vector2> landmarkPointsInMaskImage, float maskImageWidth = 0, float maskImageHeight = 0)
{
float imageWidth = meshOverlay.width;
float imageHeight = meshOverlay.height;
if (maskImageWidth == 0)
maskImageWidth = imageWidth;
if (maskImageHeight == 0)
maskImageHeight = imageHeight;
TrackedMesh tm = meshOverlay.GetObjectById (tr.id);
Vector3[] vertices = tm.meshFilter.mesh.vertices;
if (vertices.Length == landmarkPoints.Count) {
for (int j = 0; j < vertices.Length; j++) {
vertices [j].x = landmarkPoints[j].x / imageWidth - 0.5f;
vertices [j].y = 0.5f - landmarkPoints[j].y / imageHeight;
}
}
Vector2[] uv = tm.meshFilter.mesh.uv;
if (uv.Length == landmarkPointsInMaskImage.Count) {
for (int jj = 0; jj < uv.Length; jj++) {
uv [jj].x = landmarkPointsInMaskImage[jj].x / maskImageWidth;
uv [jj].y = (maskImageHeight - landmarkPointsInMaskImage[jj].y) / maskImageHeight;
}
}
meshOverlay.UpdateObject (tr.id, vertices, null, uv);
if (tr.numFramesNotDetected > 3) {
tm.sharedMaterial.SetFloat (shader_FadeID, 1f);
}else if (tr.numFramesNotDetected > 0 && tr.numFramesNotDetected <= 3) {
tm.sharedMaterial.SetFloat (shader_FadeID, 0.3f + (0.7f/4f) * tr.numFramesNotDetected);
} else {
tm.sharedMaterial.SetFloat (shader_FadeID, 0.3f);
}
if (enableColorCorrection) {
tm.sharedMaterial.SetFloat (shader_ColorCorrectionID, 1f);
} else {
tm.sharedMaterial.SetFloat (shader_ColorCorrectionID, 0f);
}
// filter non frontal faces.
if (filterNonFrontalFaces && frontalFaceChecker.GetFrontalFaceRate (landmarkPoints) < frontalFaceRateLowerLimit) {
tm.sharedMaterial.SetFloat (shader_FadeID, 1f);
}
}
private void CorrectFaceMaskColor (int id, Mat src, Mat dst, List<Vector2> src_landmarkPoints, List<Vector2> dst_landmarkPoints)
{
Texture2D LUTTex = faceMaskColorCorrector.UpdateLUTTex(id, src, dst, src_landmarkPoints, dst_landmarkPoints);
TrackedMesh tm = meshOverlay.GetObjectById (id);
tm.sharedMaterial.SetTexture (shader_LUTTexID, LUTTex);
}
/// <summary>
/// Raises the disable event.
/// </summary>
void OnDestroy ()
{
capture.release ();
if (rgbMat != null)
rgbMat.Dispose ();
if (grayMat != null)
grayMat.Dispose ();
if (rectangleTracker != null)
rectangleTracker.Dispose ();
if (faceLandmarkDetector != null)
faceLandmarkDetector.Dispose ();
foreach (var key in lowPassFilterDict.Keys) {
lowPassFilterDict [key].Dispose ();
}
lowPassFilterDict.Clear ();
foreach (var key in opticalFlowFilterDict.Keys) {
opticalFlowFilterDict [key].Dispose ();
}
opticalFlowFilterDict.Clear ();
if (faceMaskColorCorrector != null)
faceMaskColorCorrector.Dispose ();
if (frontalFaceChecker != null)
frontalFaceChecker.Dispose ();
#if UNITY_WEBGL && !UNITY_EDITOR
foreach (var coroutine in coroutines) {
StopCoroutine (coroutine);
((IDisposable)coroutine).Dispose ();
}
#endif
}
/// <summary>
/// Raises the back button click event.
/// </summary>
public void OnBackButtonClick ()
{
#if UNITY_5_3 || UNITY_5_3_OR_NEWER
SceneManager.LoadScene ("FaceMaskExample");
#else
Application.LoadLevel ("FaceMaskExample");
#endif
}
/// <summary>
/// Raises the use Dlib face detector toggle value changed event.
/// </summary>
public void OnUseDlibFaceDetecterToggleValueChanged ()
{
if (useDlibFaceDetecterToggle.isOn) {
useDlibFaceDetecter = true;
} else {
useDlibFaceDetecter = false;
}
}
/// <summary>
/// Raises the enable noise filter toggle value changed event.
/// </summary>
public void OnEnableNoiseFilterToggleValueChanged ()
{
if (enableNoiseFilterToggle.isOn) {
enableNoiseFilter = true;
foreach (var key in lowPassFilterDict.Keys) {
lowPassFilterDict [key].Reset ();
}
foreach (var key in opticalFlowFilterDict.Keys) {
opticalFlowFilterDict [key].Reset ();
}
} else {
enableNoiseFilter = false;
}
}
/// <summary>
/// Raises the enable color correction toggle value changed event.
/// </summary>
public void OnEnableColorCorrectionToggleValueChanged ()
{
if (enableColorCorrectionToggle.isOn) {
enableColorCorrection = true;
} else {
enableColorCorrection = false;
}
}
/// <summary>
/// Raises the filter non frontal faces toggle value changed event.
/// </summary>
public void OnFilterNonFrontalFacesToggleValueChanged ()
{
if (filterNonFrontalFacesToggle.isOn) {
filterNonFrontalFaces = true;
} else {
filterNonFrontalFaces = false;
}
}
/// <summary>
/// Raises the display face rects toggle value changed event.
/// </summary>
public void OnDisplayFaceRectsToggleValueChanged ()
{
if (displayFaceRectsToggle.isOn) {
displayFaceRects = true;
} else {
displayFaceRects = false;
}
}
/// <summary>
/// Raises the display debug face points toggle value changed event.
/// </summary>
public void OnDisplayDebugFacePointsToggleValueChanged ()
{
if (displayDebugFacePointsToggle.isOn) {
displayDebugFacePoints = true;
} else {
displayDebugFacePoints = false;
}
}
/// <summary>
/// Raises the change face mask button click event.
/// </summary>
public void OnChangeFaceMaskButtonClick ()
{
RemoveFaceMask ();
if (faceMaskDatas.Count == 0)
return;
FaceMaskData maskData = faceMaskDatas[faceMaskDataIndex];
faceMaskDataIndex = (faceMaskDataIndex < faceMaskDatas.Count - 1) ? faceMaskDataIndex + 1 : 0;
if (maskData == null) {
Debug.LogError ("maskData == null");
return;
}
if (maskData.image == null) {
Debug.LogError ("image == null");
return;
}
if (maskData.landmarkPoints.Count != 68) {
Debug.LogError ("landmarkPoints.Count != 68");
return;
}
faceMaskTexture = maskData.image;
faceMaskMat = new Mat (faceMaskTexture.height, faceMaskTexture.width, CvType.CV_8UC3);
OpenCVForUnity.Utils.texture2DToMat (faceMaskTexture, faceMaskMat);
if(maskData.isDynamicMode){
faceRectInMask = DetectFace (faceMaskMat);
faceLandmarkPointsInMask = DetectFaceLandmarkPoints (faceMaskMat, faceRectInMask);
maskData.faceRect = faceRectInMask;
maskData.landmarkPoints = faceLandmarkPointsInMask;
}else{
faceRectInMask = maskData.faceRect;
faceLandmarkPointsInMask = maskData.landmarkPoints;
}
if (faceRectInMask.width == 0 && faceRectInMask.height == 0){
RemoveFaceMask ();
Debug.LogError ("A face could not be detected from the input image.");
}
enableColorCorrectionToggle.isOn = maskData.enableColorCorrection;
/*
DumpFaceRect (faceRectInMask);
DumpLandMarkPoints (faceLandmarkPointsInMask);
*/
/*
if (maskData.name == "Panda") {
UnityEngine.Rect faceRect;
List<Vector2> landmarkPoints;
CreatePandaMaskData (out faceRect, out landmarkPoints);
SetFaceMaskData (maskData, faceRect, landmarkPoints);
}else if (maskData.name == "Anime") {
UnityEngine.Rect faceRect;
List<Vector2> landmarkPoints;
CreateAnimeMaskData (out faceRect, out landmarkPoints);
SetFaceMaskData (maskData, faceRect, landmarkPoints);
}
*/
}
/// <summary>
/// Raises the remove face mask button click event.
/// </summary>
public void OnRemoveFaceMaskButtonClick ()
{
RemoveFaceMask ();
}
private void RemoveFaceMask ()
{
faceMaskTexture = null;
if (faceMaskMat != null) {
faceMaskMat.Dispose ();
faceMaskMat = null;
}
rectangleTracker.Reset ();
meshOverlay.Reset ();
}
private UnityEngine.Rect DetectFace (Mat mat)
{
if (useDlibFaceDetecter) {
OpenCVForUnityUtils.SetImage (faceLandmarkDetector, mat);
List<UnityEngine.Rect> result = faceLandmarkDetector.Detect ();
if (result.Count >= 1)
return result [0];
} else {
using (Mat grayMat = new Mat ())
using (Mat equalizeHistMat = new Mat ())
using (MatOfRect faces = new MatOfRect ()) {
// convert image to greyscale.
Imgproc.cvtColor (mat, grayMat, Imgproc.COLOR_RGB2GRAY);
Imgproc.equalizeHist (grayMat, equalizeHistMat);
cascade.detectMultiScale (equalizeHistMat, faces, 1.1f, 2, 0 | Objdetect.CASCADE_SCALE_IMAGE, new OpenCVForUnity.Size (equalizeHistMat.cols () * 0.15, equalizeHistMat.cols () * 0.15), new Size ());
List<OpenCVForUnity.Rect> faceList = faces.toList ();
if (faceList.Count >= 1) {
UnityEngine.Rect r = new UnityEngine.Rect (faceList [0].x, faceList [0].y, faceList [0].width, faceList [0].height);
// adjust to Dilb's result.
r.y += (int)(r.height * 0.1f);
return r;
}
}
}
return new UnityEngine.Rect ();
}
private List<Vector2> DetectFaceLandmarkPoints (Mat mat, UnityEngine.Rect rect)
{
OpenCVForUnityUtils.SetImage (faceLandmarkDetector, mat);
List<Vector2> points = faceLandmarkDetector.DetectLandmark (rect);
return points;
}
/*
private void DumpFaceRect (UnityEngine.Rect faceRect)
{
Debug.Log ("== DumpFaceRect ==");
Debug.Log ("new Rect(" + faceRect.x + ", " + faceRect.y + ", " + faceRect.width + ", " + faceRect.height + ");");
Debug.Log ("==================");
}
private void DumpLandMarkPoints (List<Vector2> landmarkPoints)
{
Debug.Log ("== DumpLandMarkPoints ==");
string str = "";
for (int i = 0; i < landmarkPoints.Count; i++) {
str = str + "new Vector2(" + landmarkPoints[i].x + ", " + landmarkPoints[i].y + ")";
if (i < landmarkPoints.Count - 1) {
str = str + "," + "\n";
}
}
Debug.Log (str);
Debug.Log ("==================");
}
private void SetFaceMaskData (FaceMaskData data, UnityEngine.Rect faceRect, List<Vector2> landmarkPoints)
{
data.faceRect = faceRect;
data.landmarkPoints = landmarkPoints;
}
private void CreatePandaMaskData (out UnityEngine.Rect faceRect, out List<Vector2> landmarkPoints)
{
faceRect = new UnityEngine.Rect (17, 64, 261, 205);
landmarkPoints = new List<Vector2> () {
new Vector2 (31, 136),
new Vector2 (23, 169),
new Vector2 (26, 195),
new Vector2 (35, 216),
new Vector2 (53, 236),
new Vector2 (71, 251),
new Vector2 (96, 257),
new Vector2 (132, 259),
new Vector2 (143, 263),
//9
new Vector2 (165, 258),
new Vector2 (198, 255),
new Vector2 (222, 242),
new Vector2 (235, 231),
new Vector2 (248, 215),
new Vector2 (260, 195),
new Vector2 (272, 171),
new Vector2 (264, 135),
//17
new Vector2 (45, 115),
new Vector2 (70, 94),
new Vector2 (97, 89),
new Vector2 (116, 90),
new Vector2 (135, 105),
new Vector2 (157, 104),
new Vector2 (176, 90),
new Vector2 (198, 86),
new Vector2 (223, 90),
new Vector2 (248, 110),
//27
new Vector2 (148, 134),
new Vector2 (147, 152),
new Vector2 (145, 174),
new Vector2 (144, 192),
new Vector2 (117, 205),
new Vector2 (128, 213),
new Vector2 (143, 216),
new Vector2 (160, 216),
new Vector2 (174, 206),
//36
new Vector2 (96, 138),
new Vector2 (101, 131),
new Vector2 (111, 132),
new Vector2 (114, 140),
new Vector2 (109, 146),
new Vector2 (100, 146),
new Vector2 (180, 138),
new Vector2 (186, 130),
new Vector2 (195, 131),
new Vector2 (199, 137),
new Vector2 (195, 143),
new Vector2 (185, 143),
//48
new Vector2 (109, 235),
new Vector2 (118, 231),
new Vector2 (129, 228),
new Vector2 (143, 225),
new Vector2 (156, 227),
new Vector2 (174, 232),
new Vector2 (181, 234),
new Vector2 (173, 241),
new Vector2 (156, 245),
new Vector2 (143, 245),
new Vector2 (130, 244),
new Vector2 (117, 239),
new Vector2 (114, 235),
new Vector2 (130, 232),
new Vector2 (142, 232),
new Vector2 (157, 233),
new Vector2 (175, 236),
new Vector2 (155, 237),
new Vector2 (143, 238),
new Vector2 (130, 237)
};
}
private void CreateAnimeMaskData (out UnityEngine.Rect faceRect, out List<Vector2> landmarkPoints)
{
faceRect = new UnityEngine.Rect (56, 85, 190, 196);
landmarkPoints = new List<Vector2> () {
new Vector2(62, 179),
new Vector2(72, 209),
new Vector2(75, 223),
new Vector2(81, 236),
new Vector2(90, 244),
new Vector2(101, 251),
new Vector2(116, 258),
new Vector2(129, 262),
new Vector2(142, 268),
new Vector2(160, 265),
new Vector2(184, 260),
new Vector2(202, 253),
new Vector2(210, 247),
new Vector2(217, 239),
new Vector2(222, 229),
new Vector2(225, 222),
new Vector2(243, 191),
//17
new Vector2(68, 136),
new Vector2(86, 128),
new Vector2(104, 126),
new Vector2(122, 131),
new Vector2(134, 141),
new Vector2(177, 143),
new Vector2(191, 135),
new Vector2(209, 132),
new Vector2(227, 136),
new Vector2(239, 143),
//27
new Vector2(153, 163),
new Vector2(150, 190),
new Vector2(149, 201),
new Vector2(148, 212),
new Vector2(138, 217),
new Vector2(141, 219),
new Vector2(149, 221),
new Vector2(152, 220),
new Vector2(155, 217),
//36
new Vector2(70, 182),
new Vector2(85, 165),
new Vector2(114, 168),
new Vector2(122, 192),
new Vector2(113, 211),
new Vector2(82, 209),
new Vector2(177, 196),
new Vector2(189, 174),
new Vector2(220, 175),
new Vector2(234, 192),
new Vector2(215, 220),
new Vector2(184, 217),
//48
new Vector2(132, 249),
new Vector2(134, 249),
new Vector2(139, 250),
new Vector2(144, 251),
new Vector2(148, 251),
new Vector2(153, 250),
new Vector2(155, 251),
new Vector2(154, 253),
new Vector2(149, 257),
new Vector2(144, 257),
new Vector2(138, 256),
new Vector2(133, 252),
new Vector2(133, 250),
new Vector2(139, 252),
new Vector2(144, 254),
new Vector2(148, 253),
new Vector2(153, 251),
new Vector2(148, 254),
new Vector2(144, 254),
new Vector2(139, 253)
};
}
*/
}
} | 39.269781 | 251 | 0.517138 | [
"MIT"
] | PacktPublishing/Complete-Virtual-Reality-and-Augmented-Reality-Development-with-Unity | Chapter16/Assets/FaceMaskExample/VideoCaptureFaceMaskExample/VideoCaptureFaceMaskExample.cs | 41,204 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("LanboostPathFindingTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LanboostPathFindingTest")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("f5819022-fe06-47a6-98df-6a1f761e3e7e")]
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 30.761905 | 56 | 0.763158 | [
"MIT"
] | Lanboost/LanboostPathfindingSharp | LanboostPathFindingTest/Properties/AssemblyInfo.cs | 647 | C# |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Rest.Trusthub.V1.CustomerProfiles;
namespace Twilio.Tests.Rest.Trusthub.V1.CustomerProfiles
{
[TestFixture]
public class CustomerProfilesEvaluationsTest : TwilioTest
{
[Test]
public void TestCreateRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Post,
Twilio.Rest.Domain.Trusthub,
"/v1/CustomerProfiles/BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Evaluations",
""
);
request.AddPostParam("PolicySid", Serialize("RNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"));
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
CustomerProfilesEvaluationsResource.Create("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "RNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestCreateResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.Created,
"{\"sid\": \"ELaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"policy_sid\": \"RNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"customer_profile_sid\": \"BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"status\": \"noncompliant\",\"date_created\": \"2020-04-28T18:14:01Z\",\"url\": \"https://trusthub.twilio.com/v1/CustomerProfiles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations/ELaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"results\": [{\"friendly_name\": \"Business\",\"object_type\": \"business\",\"passed\": false,\"failure_reason\": \"A Business End-User is missing. Please add one to the regulatory bundle.\",\"error_code\": 22214,\"valid\": [],\"invalid\": [{\"friendly_name\": \"Business Name\",\"object_field\": \"business_name\",\"failure_reason\": \"The Business Name is missing. Please enter in a Business Name on the Business information.\",\"error_code\": 22215},{\"friendly_name\": \"Business Registration Number\",\"object_field\": \"business_registration_number\",\"failure_reason\": \"The Business Registration Number is missing. Please enter in a Business Registration Number on the Business information.\",\"error_code\": 22215},{\"friendly_name\": \"First Name\",\"object_field\": \"first_name\",\"failure_reason\": \"The First Name is missing. Please enter in a First Name on the Business information.\",\"error_code\": 22215},{\"friendly_name\": \"Last Name\",\"object_field\": \"last_name\",\"failure_reason\": \"The Last Name is missing. Please enter in a Last Name on the Business information.\",\"error_code\": 22215}],\"requirement_friendly_name\": \"Business\",\"requirement_name\": \"business_info\"},{\"friendly_name\": \"Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative\",\"object_type\": \"commercial_registrar_excerpt\",\"passed\": false,\"failure_reason\": \"An Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [{\"friendly_name\": \"Business Name\",\"object_field\": \"business_name\",\"failure_reason\": \"The Business Name is missing. Or, it does not match the Business Name you entered within Business information. Please enter in the Business Name shown on the Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative or make sure both Business Name fields use the same exact inputs.\",\"error_code\": 22217}],\"requirement_friendly_name\": \"Business Name\",\"requirement_name\": \"business_name_info\"},{\"friendly_name\": \"Excerpt from the commercial register showing French address\",\"object_type\": \"commercial_registrar_excerpt\",\"passed\": false,\"failure_reason\": \"An Excerpt from the commercial register showing French address is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [{\"friendly_name\": \"Address sid(s)\",\"object_field\": \"address_sids\",\"failure_reason\": \"The Address is missing. Please enter in the address shown on the Excerpt from the commercial register showing French address.\",\"error_code\": 22219}],\"requirement_friendly_name\": \"Business Address (Proof of Address)\",\"requirement_name\": \"business_address_proof_info\"},{\"friendly_name\": \"Excerpt from the commercial register (Extrait K-bis)\",\"object_type\": \"commercial_registrar_excerpt\",\"passed\": false,\"failure_reason\": \"An Excerpt from the commercial register (Extrait K-bis) is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [{\"friendly_name\": \"Document Number\",\"object_field\": \"document_number\",\"failure_reason\": \"The Document Number is missing. Please enter in the Document Number shown on the Excerpt from the commercial register (Extrait K-bis).\",\"error_code\": 22217}],\"requirement_friendly_name\": \"Business Registration Number\",\"requirement_name\": \"business_reg_no_info\"},{\"friendly_name\": \"Government-issued ID\",\"object_type\": \"government_issued_document\",\"passed\": false,\"failure_reason\": \"A Government-issued ID is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [{\"friendly_name\": \"First Name\",\"object_field\": \"first_name\",\"failure_reason\": \"The First Name is missing. Or, it does not match the First Name you entered within Business information. Please enter in the First Name shown on the Government-issued ID or make sure both First Name fields use the same exact inputs.\",\"error_code\": 22217},{\"friendly_name\": \"Last Name\",\"object_field\": \"last_name\",\"failure_reason\": \"The Last Name is missing. Or, it does not match the Last Name you entered within Business information. Please enter in the Last Name shown on the Government-issued ID or make sure both Last Name fields use the same exact inputs.\",\"error_code\": 22217}],\"requirement_friendly_name\": \"Name of Authorized Representative\",\"requirement_name\": \"name_of_auth_rep_info\"},{\"friendly_name\": \"Executed Copy of Power of Attorney\",\"object_type\": \"power_of_attorney\",\"passed\": false,\"failure_reason\": \"An Executed Copy of Power of Attorney is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [],\"requirement_friendly_name\": \"Power of Attorney\",\"requirement_name\": \"power_of_attorney_info\"},{\"friendly_name\": \"Government-issued ID\",\"object_type\": \"government_issued_document\",\"passed\": false,\"failure_reason\": \"A Government-issued ID is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [{\"friendly_name\": \"First Name\",\"object_field\": \"first_name\",\"failure_reason\": \"The First Name is missing on the Governnment-Issued ID.\",\"error_code\": 22217},{\"friendly_name\": \"Last Name\",\"object_field\": \"last_name\",\"failure_reason\": \"The Last Name is missing on the Government-issued ID\",\"error_code\": 22217}],\"requirement_friendly_name\": \"Name of Person granted the Power of Attorney\",\"requirement_name\": \"name_in_power_of_attorney_info\"}]}"
));
var response = CustomerProfilesEvaluationsResource.Create("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "RNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestReadRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Get,
Twilio.Rest.Domain.Trusthub,
"/v1/CustomerProfiles/BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Evaluations",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
CustomerProfilesEvaluationsResource.Read("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestReadEmptyResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"results\": [],\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://trusthub.twilio.com/v1/CustomerProfiles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://trusthub.twilio.com/v1/CustomerProfiles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"results\"}}"
));
var response = CustomerProfilesEvaluationsResource.Read("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestReadFullResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"results\": [{\"sid\": \"ELaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"policy_sid\": \"RNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"customer_profile_sid\": \"BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"status\": \"noncompliant\",\"date_created\": \"2020-04-28T18:14:01Z\",\"url\": \"https://trusthub.twilio.com/v1/CustomerProfiles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations/ELaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"results\": [{\"friendly_name\": \"Business\",\"object_type\": \"business\",\"passed\": false,\"failure_reason\": \"A Business End-User is missing. Please add one to the regulatory bundle.\",\"error_code\": 22214,\"valid\": [],\"invalid\": [{\"friendly_name\": \"Business Name\",\"object_field\": \"business_name\",\"failure_reason\": \"The Business Name is missing. Please enter in a Business Name on the Business information.\",\"error_code\": 22215},{\"friendly_name\": \"Business Registration Number\",\"object_field\": \"business_registration_number\",\"failure_reason\": \"The Business Registration Number is missing. Please enter in a Business Registration Number on the Business information.\",\"error_code\": 22215},{\"friendly_name\": \"First Name\",\"object_field\": \"first_name\",\"failure_reason\": \"The First Name is missing. Please enter in a First Name on the Business information.\",\"error_code\": 22215},{\"friendly_name\": \"Last Name\",\"object_field\": \"last_name\",\"failure_reason\": \"The Last Name is missing. Please enter in a Last Name on the Business information.\",\"error_code\": 22215}],\"requirement_friendly_name\": \"Business\",\"requirement_name\": \"business_info\"},{\"friendly_name\": \"Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative\",\"object_type\": \"commercial_registrar_excerpt\",\"passed\": false,\"failure_reason\": \"An Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [{\"friendly_name\": \"Business Name\",\"object_field\": \"business_name\",\"failure_reason\": \"The Business Name is missing. Or, it does not match the Business Name you entered within Business information. Please enter in the Business Name shown on the Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative or make sure both Business Name fields use the same exact inputs.\",\"error_code\": 22217}],\"requirement_friendly_name\": \"Business Name\",\"requirement_name\": \"business_name_info\"},{\"friendly_name\": \"Excerpt from the commercial register showing French address\",\"object_type\": \"commercial_registrar_excerpt\",\"passed\": false,\"failure_reason\": \"An Excerpt from the commercial register showing French address is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [{\"friendly_name\": \"Address sid(s)\",\"object_field\": \"address_sids\",\"failure_reason\": \"The Address is missing. Please enter in the address shown on the Excerpt from the commercial register showing French address.\",\"error_code\": 22219}],\"requirement_friendly_name\": \"Business Address (Proof of Address)\",\"requirement_name\": \"business_address_proof_info\"},{\"friendly_name\": \"Excerpt from the commercial register (Extrait K-bis)\",\"object_type\": \"commercial_registrar_excerpt\",\"passed\": false,\"failure_reason\": \"An Excerpt from the commercial register (Extrait K-bis) is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [{\"friendly_name\": \"Document Number\",\"object_field\": \"document_number\",\"failure_reason\": \"The Document Number is missing. Please enter in the Document Number shown on the Excerpt from the commercial register (Extrait K-bis).\",\"error_code\": 22217}],\"requirement_friendly_name\": \"Business Registration Number\",\"requirement_name\": \"business_reg_no_info\"},{\"friendly_name\": \"Government-issued ID\",\"object_type\": \"government_issued_document\",\"passed\": false,\"failure_reason\": \"A Government-issued ID is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [{\"friendly_name\": \"First Name\",\"object_field\": \"first_name\",\"failure_reason\": \"The First Name is missing. Or, it does not match the First Name you entered within Business information. Please enter in the First Name shown on the Government-issued ID or make sure both First Name fields use the same exact inputs.\",\"error_code\": 22217},{\"friendly_name\": \"Last Name\",\"object_field\": \"last_name\",\"failure_reason\": \"The Last Name is missing. Or, it does not match the Last Name you entered within Business information. Please enter in the Last Name shown on the Government-issued ID or make sure both Last Name fields use the same exact inputs.\",\"error_code\": 22217}],\"requirement_friendly_name\": \"Name of Authorized Representative\",\"requirement_name\": \"name_of_auth_rep_info\"},{\"friendly_name\": \"Executed Copy of Power of Attorney\",\"object_type\": \"power_of_attorney\",\"passed\": false,\"failure_reason\": \"An Executed Copy of Power of Attorney is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [],\"requirement_friendly_name\": \"Power of Attorney\",\"requirement_name\": \"power_of_attorney_info\"},{\"friendly_name\": \"Government-issued ID\",\"object_type\": \"government_issued_document\",\"passed\": false,\"failure_reason\": \"A Government-issued ID is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [{\"friendly_name\": \"First Name\",\"object_field\": \"first_name\",\"failure_reason\": \"The First Name is missing on the Governnment-Issued ID.\",\"error_code\": 22217},{\"friendly_name\": \"Last Name\",\"object_field\": \"last_name\",\"failure_reason\": \"The Last Name is missing on the Government-issued ID\",\"error_code\": 22217}],\"requirement_friendly_name\": \"Name of Person granted the Power of Attorney\",\"requirement_name\": \"name_in_power_of_attorney_info\"}]}],\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://trusthub.twilio.com/v1/CustomerProfiles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://trusthub.twilio.com/v1/CustomerProfiles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"results\"}}"
));
var response = CustomerProfilesEvaluationsResource.Read("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestFetchRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Get,
Twilio.Rest.Domain.Trusthub,
"/v1/CustomerProfiles/BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Evaluations/ELXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
CustomerProfilesEvaluationsResource.Fetch("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ELXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestFetchResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"sid\": \"ELaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"policy_sid\": \"RNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"customer_profile_sid\": \"BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"status\": \"noncompliant\",\"date_created\": \"2020-04-28T18:14:01Z\",\"url\": \"https://trusthub.twilio.com/v1/CustomerProfiles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations/ELaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"results\": [{\"friendly_name\": \"Business\",\"object_type\": \"business\",\"passed\": false,\"failure_reason\": \"A Business End-User is missing. Please add one to the regulatory bundle.\",\"error_code\": 22214,\"valid\": [],\"invalid\": [{\"friendly_name\": \"Business Name\",\"object_field\": \"business_name\",\"failure_reason\": \"The Business Name is missing. Please enter in a Business Name on the Business information.\",\"error_code\": 22215},{\"friendly_name\": \"Business Registration Number\",\"object_field\": \"business_registration_number\",\"failure_reason\": \"The Business Registration Number is missing. Please enter in a Business Registration Number on the Business information.\",\"error_code\": 22215},{\"friendly_name\": \"First Name\",\"object_field\": \"first_name\",\"failure_reason\": \"The First Name is missing. Please enter in a First Name on the Business information.\",\"error_code\": 22215},{\"friendly_name\": \"Last Name\",\"object_field\": \"last_name\",\"failure_reason\": \"The Last Name is missing. Please enter in a Last Name on the Business information.\",\"error_code\": 22215}],\"requirement_friendly_name\": \"Business\",\"requirement_name\": \"business_info\"},{\"friendly_name\": \"Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative\",\"object_type\": \"commercial_registrar_excerpt\",\"passed\": false,\"failure_reason\": \"An Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [{\"friendly_name\": \"Business Name\",\"object_field\": \"business_name\",\"failure_reason\": \"The Business Name is missing. Or, it does not match the Business Name you entered within Business information. Please enter in the Business Name shown on the Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative or make sure both Business Name fields use the same exact inputs.\",\"error_code\": 22217}],\"requirement_friendly_name\": \"Business Name\",\"requirement_name\": \"business_name_info\"},{\"friendly_name\": \"Excerpt from the commercial register showing French address\",\"object_type\": \"commercial_registrar_excerpt\",\"passed\": false,\"failure_reason\": \"An Excerpt from the commercial register showing French address is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [{\"friendly_name\": \"Address sid(s)\",\"object_field\": \"address_sids\",\"failure_reason\": \"The Address is missing. Please enter in the address shown on the Excerpt from the commercial register showing French address.\",\"error_code\": 22219}],\"requirement_friendly_name\": \"Business Address (Proof of Address)\",\"requirement_name\": \"business_address_proof_info\"},{\"friendly_name\": \"Excerpt from the commercial register (Extrait K-bis)\",\"object_type\": \"commercial_registrar_excerpt\",\"passed\": false,\"failure_reason\": \"An Excerpt from the commercial register (Extrait K-bis) is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [{\"friendly_name\": \"Document Number\",\"object_field\": \"document_number\",\"failure_reason\": \"The Document Number is missing. Please enter in the Document Number shown on the Excerpt from the commercial register (Extrait K-bis).\",\"error_code\": 22217}],\"requirement_friendly_name\": \"Business Registration Number\",\"requirement_name\": \"business_reg_no_info\"},{\"friendly_name\": \"Government-issued ID\",\"object_type\": \"government_issued_document\",\"passed\": false,\"failure_reason\": \"A Government-issued ID is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [{\"friendly_name\": \"First Name\",\"object_field\": \"first_name\",\"failure_reason\": \"The First Name is missing. Or, it does not match the First Name you entered within Business information. Please enter in the First Name shown on the Government-issued ID or make sure both First Name fields use the same exact inputs.\",\"error_code\": 22217},{\"friendly_name\": \"Last Name\",\"object_field\": \"last_name\",\"failure_reason\": \"The Last Name is missing. Or, it does not match the Last Name you entered within Business information. Please enter in the Last Name shown on the Government-issued ID or make sure both Last Name fields use the same exact inputs.\",\"error_code\": 22217}],\"requirement_friendly_name\": \"Name of Authorized Representative\",\"requirement_name\": \"name_of_auth_rep_info\"},{\"friendly_name\": \"Executed Copy of Power of Attorney\",\"object_type\": \"power_of_attorney\",\"passed\": false,\"failure_reason\": \"An Executed Copy of Power of Attorney is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [],\"requirement_friendly_name\": \"Power of Attorney\",\"requirement_name\": \"power_of_attorney_info\"},{\"friendly_name\": \"Government-issued ID\",\"object_type\": \"government_issued_document\",\"passed\": false,\"failure_reason\": \"A Government-issued ID is missing. Please add one to the regulatory bundle.\",\"error_code\": 22216,\"valid\": [],\"invalid\": [{\"friendly_name\": \"First Name\",\"object_field\": \"first_name\",\"failure_reason\": \"The First Name is missing on the Governnment-Issued ID.\",\"error_code\": 22217},{\"friendly_name\": \"Last Name\",\"object_field\": \"last_name\",\"failure_reason\": \"The Last Name is missing on the Government-issued ID\",\"error_code\": 22217}],\"requirement_friendly_name\": \"Name of Person granted the Power of Attorney\",\"requirement_name\": \"name_in_power_of_attorney_info\"}]}"
));
var response = CustomerProfilesEvaluationsResource.Fetch("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ELXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
}
} | 171.662162 | 6,647 | 0.696686 | [
"MIT"
] | BrimmingDev/twilio-csharp | test/Twilio.Test/Rest/Trusthub/V1/CustomerProfiles/CustomerProfilesEvaluationsResourceTest.cs | 25,406 | C# |
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public class XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaDelegateBridgeBaseWrapWrapWrapWrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Type type = typeof(XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaDelegateBridgeBaseWrapWrapWrap);
Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0);
Utils.EndObjectRegister(type, L, translator, null, null,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0);
Utils.RegisterFunc(L, Utils.CLS_IDX, "__Register", _m___Register_xlua_st_);
Utils.EndClassRegister(type, L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CreateInstance(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
if(LuaAPI.lua_gettop(L) == 1)
{
XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaDelegateBridgeBaseWrapWrapWrap gen_ret = new XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaDelegateBridgeBaseWrapWrapWrap();
translator.Push(L, gen_ret);
return 1;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaDelegateBridgeBaseWrapWrapWrap constructor!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m___Register_xlua_st_(RealStatePtr L)
{
try {
{
System.IntPtr _L = LuaAPI.lua_touserdata(L, 1);
XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaDelegateBridgeBaseWrapWrapWrap.__Register( _L );
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
}
}
| 25.918182 | 191 | 0.596282 | [
"MIT"
] | zxsean/DCET | Unity/Assets/Model/XLua/Gen/XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaDelegateBridgeBaseWrapWrapWrapWrap.cs | 2,853 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Ch01._06
{
public interface IExamApplication
{
public Subject Subject { get; }
public Professor Admin { get; }
public Student Candidate { get; }
}
}
| 18.857143 | 41 | 0.655303 | [
"MIT"
] | hhko/Books | 3.Lectures/FP/DefensiveProgramming/DefensiveProgramming/Ch03/_06/IExamApplication.cs | 266 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using Silky.Core.Configuration;
using Silky.Core.Extensions;
namespace Silky.Core
{
public class AppDomainTypeFinder : ITypeFinder
{
private bool _ignoreReflectionErrors = true;
protected ISilkyFileProvider _fileProvider;
public AppDomainTypeFinder(ISilkyFileProvider fileProvider = null)
{
_fileProvider = fileProvider ?? CommonSilkyHelpers.DefaultFileProvider;
}
#region Utilities
private void AddAssembliesInAppDomain(List<string> addedAssemblyNames, List<Assembly> assemblies)
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (!Matches(assembly.FullName))
continue;
if (addedAssemblyNames.Contains(assembly.FullName))
continue;
if (assembly.IsDynamic)
continue;
assemblies.Add(assembly);
addedAssemblyNames.Add(assembly.FullName);
}
}
protected virtual void AddConfiguredAssemblies(List<string> addedAssemblyNames, List<Assembly> assemblies)
{
foreach (var assemblyName in AssemblyNames)
{
var assembly = Assembly.Load(assemblyName);
if (addedAssemblyNames.Contains(assembly.FullName))
continue;
assemblies.Add(assembly);
addedAssemblyNames.Add(assembly.FullName);
}
}
protected virtual bool Matches(string assemblyFullName)
{
return !Matches(assemblyFullName, AssemblySkipLoadingPattern)
&& Matches(assemblyFullName, AssemblyRestrictToLoadingPattern);
}
protected virtual bool Matches(string assemblyFullName, string pattern)
{
return Regex.IsMatch(assemblyFullName, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
protected virtual void LoadMatchingAssemblies(string directoryPath)
{
var loadedAssemblyNames = new List<string>();
foreach (var a in GetAssemblies())
{
loadedAssemblyNames.Add(a.FullName);
}
if (!_fileProvider.DirectoryExists(directoryPath))
{
return;
}
foreach (var dllPath in _fileProvider.GetFiles(directoryPath, "*.dll"))
{
try
{
var an = AssemblyName.GetAssemblyName(dllPath);
if (Matches(an.FullName) && !loadedAssemblyNames.Contains(an.FullName))
{
App.Load(an);
}
//old loading stuff
//Assembly a = Assembly.ReflectionOnlyLoadFrom(dllPath);
//if (Matches(a.FullName) && !loadedAssemblyNames.Contains(a.FullName))
//{
// App.Load(a.FullName);
//}
}
catch (BadImageFormatException ex)
{
Trace.TraceError(ex.ToString());
}
}
}
protected virtual bool DoesTypeImplementOpenGeneric(Type type, Type openGeneric)
{
try
{
var genericTypeDefinition = openGeneric.GetGenericTypeDefinition();
foreach (var implementedInterface in type.FindInterfaces((objType, objCriteria) => true, null))
{
if (!implementedInterface.IsGenericType)
continue;
if (genericTypeDefinition.IsAssignableFrom(implementedInterface.GetGenericTypeDefinition()))
return true;
}
return false;
}
catch
{
return false;
}
}
protected virtual IEnumerable<Type> FindClassesOfType(Type assignTypeFrom, IEnumerable<Assembly> assemblies,
bool onlyConcreteClasses = true)
{
var result = new List<Type>();
try
{
foreach (var a in assemblies)
{
Type[] types = null;
try
{
types = a.GetTypes();
}
catch
{
//Entity Framework 6 doesn't allow getting types (throws an exception)
if (!_ignoreReflectionErrors)
{
throw;
}
}
if (types == null)
continue;
foreach (var t in types)
{
if (!assignTypeFrom.IsAssignableFrom(t) && (!assignTypeFrom.IsGenericTypeDefinition ||
!DoesTypeImplementOpenGeneric(t, assignTypeFrom)))
continue;
if (t.IsInterface)
continue;
if (onlyConcreteClasses)
{
if (t.IsClass && !t.IsAbstract)
{
result.Add(t);
}
}
else
{
result.Add(t);
}
}
}
}
catch (ReflectionTypeLoadException ex)
{
var msg = string.Empty;
foreach (var e in ex.LoaderExceptions)
msg += e.Message + Environment.NewLine;
var fail = new Exception(msg, ex);
Debug.WriteLine(fail.Message, fail);
throw fail;
}
return result;
}
#endregion
#region Methods
public IEnumerable<Type> FindClassesOfType<T>(bool onlyConcreteClasses = true)
{
return FindClassesOfType(typeof(T), onlyConcreteClasses);
}
public IEnumerable<Type> FindClassesOfType(Type assignTypeFrom, bool onlyConcreteClasses = true)
{
return FindClassesOfType(assignTypeFrom, GetAssemblies(), onlyConcreteClasses);
}
public virtual IList<Assembly> GetAssemblies()
{
var addedAssemblyNames = new List<string>();
var assemblies = new List<Assembly>();
if (LoadAppDomainAssemblies)
AddAssembliesInAppDomain(addedAssemblyNames, assemblies);
AddConfiguredAssemblies(addedAssemblyNames, assemblies);
AddAppServiceAssemblies(addedAssemblyNames, assemblies);
return assemblies;
}
protected virtual void AddAppServiceAssemblies(List<string> addedAssemblyNames, List<Assembly> assemblies)
{
var appSettingsOptions = EngineContext.Current.GetOptions<AppSettingsOptions>();
foreach (var appService in appSettingsOptions.Services)
{
LoadServiceAssemblies(appService.AppServiceDirectory, appService.AppServicePattern,
addedAssemblyNames, assemblies);
LoadServiceAssemblies(appService.AppServiceInterfaceDirectory,
appService.AppServiceInterfacePattern,
addedAssemblyNames, assemblies);
}
}
protected virtual void LoadServiceAssemblies(string directoryPath, string pattern,
List<string> loadedAssemblyNames, List<Assembly> assemblies)
{
if (directoryPath.IsNullOrWhiteSpace() || pattern.IsNullOrEmpty())
{
return;
}
if (!_fileProvider.DirectoryExists(directoryPath))
{
return;
}
foreach (var dllPath in _fileProvider.GetFiles(directoryPath, "*.dll", false))
{
try
{
if (Matches(dllPath) && Matches(dllPath, pattern))
{
var dllFullPath = Path.GetFullPath(dllPath);
var an = AssemblyName.GetAssemblyName(dllFullPath);
if (loadedAssemblyNames.Contains(an.FullName))
continue;
var assembly = Assembly.LoadFile(dllFullPath);
assemblies.Add(assembly);
loadedAssemblyNames.Add(assembly.FullName);
}
}
catch (BadImageFormatException ex)
{
Trace.TraceError(ex.ToString());
}
}
}
#endregion
#region Properties
public virtual AppDomain App => AppDomain.CurrentDomain;
public bool LoadAppDomainAssemblies { get; set; } = true;
public IList<string> AssemblyNames { get; set; } = new List<string>();
public string AssemblySkipLoadingPattern { get; set; } =
"^System|^mscorlib|^Microsoft|^AjaxControlToolkit|^Antlr3|^Autofac|^AutoMapper|^Castle|^ComponentArt|^CppCodeProvider|^DotNetOpenAuth|^EntityFramework|^EPPlus|^FluentValidation|^ImageResizer|^itextsharp|^log4net|^MaxMind|^MbUnit|^MiniProfiler|^Mono.Math|^MvcContrib|^Newtonsoft|^NHibernate|^nunit|^Org.Mentalis|^PerlRegex|^QuickGraph|^Recaptcha|^Remotion|^RestSharp|^Rhino|^Telerik|^Iesi|^TestDriven|^TestFu|^UserAgentStringLibrary|^VJSharpCodeProvider|^WebActivator|^WebDev|^WebGrease|^netstandard|^xunit";
public string AssemblyRestrictToLoadingPattern { get; set; } = ".*";
#endregion
}
} | 35.982143 | 519 | 0.526352 | [
"MIT"
] | microserviceframe/silky | framework/src/Silky.Core/AppDomainTypeFinder.cs | 10,077 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cs_game.Db.Models
{
public class Save : BaseDataObject
{
[ForeignKey("Player")]
public int PlayerId { get; set; }
public string Name { get; set; }
public virtual Player Player { get; set; }
public virtual Exit Exit { get; set; }
public List<Monster> Monsters { get; set; }
public Save(string name)
{
this.Name = name;
}
public void DeleteSave(Save save)
{
var factory = new DbContextFactory();
var context = factory.CreateDbContext(null);
save = context.Saves.First(s => s.Id == save.Id);
Player player = context.Players.First(p => p.Id == save.Id);
Exit exit = context.Exits.First(e => e.Id == save.Id);
List<Monster> monsters = context.Monsters.Where(m => m.SaveId == save.Id).ToList();
List<Weapon> weapons = context.Weapons.Where(w => w.PlayerId ==player.Id).ToList();
List<Item> items = context.Items.Where(i => i.PlayerId == player.Id).ToList();
context.Saves.Remove(save);
context.Items.RemoveRange(items);
context.Weapons.RemoveRange(weapons);
context.Monsters.RemoveRange(monsters);
context.Exits.Remove(exit);
context.Players.Remove(player);
context.SaveChanges();
}
}
}
| 34.021739 | 95 | 0.594888 | [
"MIT"
] | adrienvaucard/cs-game | cs-game.Db/Models/Save.cs | 1,567 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Trakx.Coinbase.Custody.Client.Interfaces;
using Trakx.Coinbase.Custody.Client.Models;
using Trakx.Common.Interfaces.Transaction;
using Trakx.IndiceManager.Server.Models;
using WrappingTransactionModel = Trakx.IndiceManager.Server.Models.WrappingTransactionModel;
namespace Trakx.IndiceManager.Server.Managers
{
/// <inheritdoc />
public class WrappingService : IWrappingService
{
private readonly ICoinbaseClient _coinbaseClient;
private readonly ILogger<WrappingService> _logger;
/// <inheritdoc />
public WrappingService(ICoinbaseClient coinbaseClient,
ILogger<WrappingService> logger)
{
_coinbaseClient = coinbaseClient;
_logger = logger;
}
#region Implementation of IWrappingService
/// <inheritdoc />
public async Task<string> RetrieveAddressFromSymbol(string symbol)
{
throw new System.NotImplementedException();
}
/// <inheritdoc />
public async Task<string> TryToFindTransaction(WrappingTransactionModel transaction)
{
throw new System.NotImplementedException();
}
/// <inheritdoc />
public async Task<string> InitiateWrapping(string transactionHash)
{
throw new System.NotImplementedException();
}
/// <inheritdoc />
public async Task<List<IWrappingTransaction>> GetTransactionByUser(string user)
{
throw new System.NotImplementedException();
}
/// <inheritdoc />
public async IAsyncEnumerable<AccountBalanceModel> GetTrakxBalances(
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
IAsyncEnumerable<Wallet> wallets;
try
{
wallets = _coinbaseClient.GetWallets(cancellationToken: cancellationToken);
}
catch (Exception e)
{
_logger.LogError(e, "Failed to retrieve wallets from Coinbase Custody");
yield break;
}
await foreach (var wallet in wallets.WithCancellation(cancellationToken))
{
yield return new AccountBalanceModel(wallet.CurrencySymbol,
wallet.Balance,
wallet.UnscaledBalance,
wallet.Name,
wallet.ColdAddress,
wallet.UpdatedAt);
}
}
#endregion
}
}
| 32.626506 | 92 | 0.6274 | [
"MIT"
] | fakecoinbase/trakxslashtrakx-tools | src/Trakx.IndiceManager.Server/Managers/WrappingService.cs | 2,710 | C# |
namespace WebGYM.ViewModels
{
public class MemberRequest
{
public string MemberName { get; set; }
}
public class MemberResponse
{
public string MemberNo { get; set; }
public string MemberName { get; set; }
}
public class MemberNoRequest
{
public string MemberNo { get; set; }
}
} | 20.411765 | 46 | 0.599424 | [
"MIT"
] | Gajendrajangid/CrudusingAngular7 | WebGYM/WebGYM.ViewModels/MemberRequest.cs | 349 | C# |
/*
* Copyright (C) 2019 - 2021, Fyfe Software Inc. and the SanteSuite Contributors (See NOTICE.md)
*
* 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.
*
* User: fyfej
* Date: 2021-2-9
*/
using SanteDB.Core.Model;
using SanteDB.Core.Model.Acts;
using SanteDB.Core.Model.Collection;
using SanteDB.Core.Model.Constants;
using SanteDB.Core.Model.DataTypes;
using SanteDB.Core.Model.Query;
using SanteDB.Core.Model.Roles;
using SanteDB.Core.Security;
using SanteDB.Core.Services;
using SanteDB.DisconnectedClient;
using SanteDB.DisconnectedClient.Caching;
using SanteDB.DisconnectedClient.Security;
using SanteDB.DisconnectedClient.Services;
using SanteDB.DisconnectedClient.Services.Attributes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SanteDB.DisconnectedClient.Services.ServiceHandlers
{
/// <summary>
/// IMSI Service handler for acts
/// </summary>
public partial class HdsiService
{
public Guid? ActParticipationKeys { get; private set; }
/// <summary>
/// Creates an act.
/// </summary>
/// <param name="actToInsert">The act to be inserted.</param>
/// <returns>Returns the inserted act.</returns>
[RestOperation(Method = "POST", UriPath = "/Act", FaultProvider = nameof(HdsiFault))]
[Demand(PermissionPolicyIdentifiers.WriteClinicalData)]
[return: RestMessage(RestMessageFormat.SimpleJson)]
public Act CreateAct([RestMessage(RestMessageFormat.SimpleJson)]Act actToInsert)
{
IActRepositoryService actService = ApplicationContext.Current.GetService<IActRepositoryService>();
return actService.Insert(actToInsert);
}
/// <summary>
/// Gets a list of acts.
/// </summary>
/// <returns>Returns a list of acts.</returns>
[RestOperation(Method = "GET", UriPath = "/Act", FaultProvider = nameof(HdsiFault))]
[Demand(PermissionPolicyIdentifiers.QueryClinicalData)]
[return: RestMessage(RestMessageFormat.SimpleJson)]
public IdentifiedData GetAct()
{
return this.GetAct<Act>();
}
/// <summary>
/// Gets a list of acts.
/// </summary>
/// <returns>Returns a list of acts.</returns>
[RestOperation(Method = "GET", UriPath = "/SubstanceAdministration", FaultProvider = nameof(HdsiFault))]
[Demand(PermissionPolicyIdentifiers.QueryClinicalData)]
[return: RestMessage(RestMessageFormat.SimpleJson)]
public IdentifiedData GetSubstanceAdministration()
{
return this.GetAct<SubstanceAdministration>();
}
/// <summary>
/// Gets a list of acts.
/// </summary>
/// <returns>Returns a list of acts.</returns>
[RestOperation(Method = "GET", UriPath = "/QuantityObservation", FaultProvider = nameof(HdsiFault))]
[Demand(PermissionPolicyIdentifiers.QueryClinicalData)]
[return: RestMessage(RestMessageFormat.SimpleJson)]
public IdentifiedData GetQuantityObservation()
{
return this.GetAct<QuantityObservation>();
}
/// <summary>
/// Gets a list of acts.
/// </summary>
/// <returns>Returns a list of acts.</returns>
[RestOperation(Method = "GET", UriPath = "/TextObservation", FaultProvider = nameof(HdsiFault))]
[Demand(PermissionPolicyIdentifiers.QueryClinicalData)]
[return: RestMessage(RestMessageFormat.SimpleJson)]
public IdentifiedData GetTextObservation()
{
return this.GetAct<TextObservation>();
}
/// <summary>
/// Gets a list of acts.
/// </summary>
/// <returns>Returns a list of acts.</returns>
[RestOperation(Method = "GET", UriPath = "/CodedObservation", FaultProvider = nameof(HdsiFault))]
[Demand(PermissionPolicyIdentifiers.QueryClinicalData)]
[return: RestMessage(RestMessageFormat.SimpleJson)]
public IdentifiedData GetCodedObservation()
{
return this.GetAct<CodedObservation>();
}
/// <summary>
/// Gets a list of acts.
/// </summary>
/// <returns>Returns a list of acts.</returns>
[RestOperation(Method = "GET", UriPath = "/PatientEncounter", FaultProvider = nameof(HdsiFault))]
[Demand(PermissionPolicyIdentifiers.QueryClinicalData)]
[return: RestMessage(RestMessageFormat.SimpleJson)]
public IdentifiedData GetPatientEncounter()
{
return this.GetAct<PatientEncounter>();
}
/// <summary>
/// Get specified service
/// </summary>
private IdentifiedData GetAct<TAct>() where TAct : IdentifiedData
{
var actRepositoryService = ApplicationContext.Current.GetService<IRepositoryService<TAct>>();
var search = NameValueCollection.ParseQueryString(MiniHdsiServer.CurrentContext.Request.Url.Query);
if (search.ContainsKey("_id"))
{
// Force load from DB
ApplicationContext.Current.GetService<IDataCachingService>().Remove(Guid.Parse(search["_id"].FirstOrDefault()));
var act = actRepositoryService.Get(Guid.Parse(search["_id"].FirstOrDefault()), Guid.Empty);
return act;
}
else
{
var queryId = search.ContainsKey("_state") ? Guid.Parse(search["_state"][0]) : Guid.NewGuid();
int totalResults = 0,
offset = search.ContainsKey("_offset") ? Int32.Parse(search["_offset"][0]) : 0,
count = search.ContainsKey("_count") ? Int32.Parse(search["_count"][0]) : 100;
IEnumerable<TAct> results = null;
if (search.ContainsKey("_onlineOnly") && search["_onlineOnly"][0] == "true")
{
var integrationService = ApplicationContext.Current.GetService<IClinicalIntegrationService>();
var bundle = integrationService.Find<Act>(QueryExpressionParser.BuildLinqExpression<Act>(search, null, false), offset, count);
totalResults = bundle.TotalResults;
bundle.Reconstitute();
bundle.Item.OfType<Act>().ToList().ForEach(o => o.Tags.Add(new ActTag("onlineResult", "true")));
results = bundle.Item.OfType<TAct>();
}
else if (actRepositoryService is IPersistableQueryRepositoryService)
{
if (actRepositoryService is IFastQueryRepositoryService)
results = (actRepositoryService as IFastQueryRepositoryService).Find<TAct>(QueryExpressionParser.BuildLinqExpression<TAct>(search, null, false), offset, count, out totalResults, queryId);
else
results = (actRepositoryService as IPersistableQueryRepositoryService).Find<TAct>(QueryExpressionParser.BuildLinqExpression<TAct>(search, null, false), offset, count, out totalResults, queryId);
}
else
{
results = actRepositoryService.Find(QueryExpressionParser.BuildLinqExpression<TAct>(search, null, false), offset, count, out totalResults);
}
//results.ToList().ForEach(a => a.Relationships.OrderBy(r => r.TargetAct.CreationTime));
this.m_tracer.TraceVerbose("Returning ACT bundle {0}..{1} / {2}", offset, offset + count, totalResults);
//
return new Bundle
{
Key = queryId,
Count = results.Count(),
Item = results.OfType<IdentifiedData>().ToList(),
Offset = offset,
TotalResults = totalResults
};
}
}
/// <summary>
/// Deletes the act
/// </summary>
[RestOperation(Method = "DELETE", UriPath = "/Act", FaultProvider = nameof(HdsiFault))]
[Demand(PermissionPolicyIdentifiers.DeleteClinicalData)]
[return: RestMessage(RestMessageFormat.SimpleJson)]
public Act DeleteAct()
{
var actRepositoryService = ApplicationContext.Current.GetService<IActRepositoryService>();
var search = NameValueCollection.ParseQueryString(MiniHdsiServer.CurrentContext.Request.Url.Query);
if (search.ContainsKey("_id"))
{
// Force load from DB
var keyid = Guid.Parse(search["_id"].FirstOrDefault());
ApplicationContext.Current.GetService<IDataCachingService>().Remove(keyid);
var act = actRepositoryService.Get<Act>(Guid.Parse(search["_id"].FirstOrDefault()), Guid.Empty);
if (act == null) throw new KeyNotFoundException();
return actRepositoryService.Obsolete<Act>(keyid);
}
else
throw new ArgumentNullException("_id");
}
/// <summary>
/// Updates an act.
/// </summary>
/// <param name="act">The act to update.</param>
/// <returns>Returns the updated act.</returns>
[RestOperation(Method = "PUT", UriPath = "/Act", FaultProvider = nameof(HdsiFault))]
[Demand(PermissionPolicyIdentifiers.WriteClinicalData)]
[return: RestMessage(RestMessageFormat.SimpleJson)]
public Act UpdateAct([RestMessage(RestMessageFormat.SimpleJson)] Act act)
{
var query = NameValueCollection.ParseQueryString(MiniHdsiServer.CurrentContext.Request.Url.Query);
Guid actKey = Guid.Empty;
if (query.ContainsKey("_id") && Guid.TryParse(query["_id"][0], out actKey))
{
if (act.Key == actKey)
{
var actRepositoryService = ApplicationContext.Current.GetService<IActRepositoryService>();
return actRepositoryService.Save(act);
}
else
{
throw new FileNotFoundException("Act not found");
}
}
else
{
throw new FileNotFoundException("Act not found");
}
}
}
}
| 42.675781 | 218 | 0.612357 | [
"Apache-2.0"
] | santedb/santedb-dc-core | SanteDB.DisconnectedClient.Core/Services/ServiceHandlers/ImsiService.Acts.cs | 10,927 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.GenbiL.Parser.Valuable
{
public interface IValuable
{
string Display { get; }
string GetValue(DataRow data);
}
public enum ValuableType
{
Value = 0,
Column = 1
}
}
| 17.863636 | 39 | 0.615776 | [
"Apache-2.0"
] | CoolsJoris/NBi | NBi.genbiL/Parser/Valuable/IValuable.cs | 395 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
namespace Microsoft.Extensions.Logging.Test.Console
{
public class ConsoleSink
{
public List<ConsoleContext> Writes { get; set; } = new List<ConsoleContext>();
public void Write(ConsoleContext context)
{
Writes.Add(context);
}
}
}
| 25.611111 | 86 | 0.67462 | [
"MIT"
] | 2m0nd/runtime | src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/Console/ConsoleSink.cs | 461 | C# |
//
// Encog(tm) Core v3.1 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2012 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 System.Collections.Generic;
using System.Linq;
using System.Text;
using Encog.App.Analyst.Missing;
using Encog.App.Analyst.Script.Prop;
using Encog.Util.Arrayutil;
namespace Encog.App.Analyst.Script.Normalize
{
/// <summary>
/// This class holds information about the fields that the Encog Analyst will
/// normalize.
/// </summary>
///
public class AnalystNormalize
{
/// <summary>
/// The normalized fields. These fields define the order and format
/// that data will be presented to the ML method.
/// </summary>
///
private readonly IList<AnalystField> _normalizedFields;
/// <summary>
/// The parent script.
/// </summary>
private readonly AnalystScript _script;
/// <summary>
/// Construct the object.
/// </summary>
public AnalystNormalize(AnalystScript script)
{
_normalizedFields = new List<AnalystField>();
_script = script;
}
/// <value>the normalizedFields</value>
public IList<AnalystField> NormalizedFields
{
get { return _normalizedFields; }
}
/// <summary>
/// The missing values handler.
/// </summary>
public IHandleMissingValues MissingValues
{
get
{
String type = _script.Properties.GetPropertyString(
ScriptProperties.NormalizeMissingValues);
if (type.Equals("DiscardMissing"))
{
return new DiscardMissing();
}
else if (type.Equals("MeanAndModeMissing"))
{
return new MeanAndModeMissing();
}
else if (type.Equals("NegateMissing"))
{
return new NegateMissing();
}
else
{
return new DiscardMissing();
}
}
set
{
_script.Properties.SetProperty(
ScriptProperties.NormalizeMissingValues, value.GetType().Name);
}
}
/// <returns>Calculate the input columns.</returns>
public int CalculateInputColumns()
{
return _normalizedFields.Where(field => field.Input).Sum(field => field.ColumnsNeeded);
}
/// <summary>
/// Calculate the output columns.
/// </summary>
///
/// <returns>The output columns.</returns>
public int CalculateOutputColumns()
{
return _normalizedFields.Where(field => field.Output).Sum(field => field.ColumnsNeeded);
}
/// <returns>Count the active fields.</returns>
public int CountActiveFields()
{
int result = 0;
foreach (AnalystField field in _normalizedFields)
{
if (field.Action != NormalizationAction.Ignore)
{
result++;
}
}
return result;
}
/// <summary>
/// Init the normalized fields.
/// </summary>
///
/// <param name="script">The script.</param>
public void Init(AnalystScript script)
{
if (_normalizedFields == null)
{
return;
}
foreach (AnalystField norm in _normalizedFields)
{
DataField f = script.FindDataField(norm.Name);
if (f == null)
{
throw new AnalystError("Normalize specifies unknown field: "
+ norm.Name);
}
if (norm.Action == NormalizationAction.Normalize)
{
norm.ActualHigh = f.Max;
norm.ActualLow = f.Min;
}
if ((norm.Action == NormalizationAction.Equilateral)
|| (norm.Action == NormalizationAction.OneOf)
|| (norm.Action == NormalizationAction.SingleField))
{
int index = 0;
foreach (AnalystClassItem item in f.ClassMembers)
{
norm.Classes.Add(new ClassItem(item.Name, index++));
}
}
}
}
/// <summary>
///
/// </summary>
///
public override sealed String ToString()
{
var result = new StringBuilder("[");
result.Append(GetType().Name);
result.Append(": ");
if (_normalizedFields != null)
{
result.Append(_normalizedFields.ToString());
}
result.Append("]");
return result.ToString();
}
}
}
| 29.719388 | 100 | 0.515365 | [
"BSD-3-Clause"
] | mpcoombes/MaterialPredictor | encog-core-cs/App/Analyst/Script/Normalize/AnalystNormalize.cs | 5,825 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Web;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
namespace TygaSoft.Converter
{
public class ExcelHelper
{
public static void Export(string filePath, DataTable dt)
{
using (SpreadsheetDocument document = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook))
{
Export(filePath, dt);
}
}
public static void Export(Stream stream, DataTable dt)
{
using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook))
{
Export(document, dt);
}
}
private static void Export(SpreadsheetDocument document, DataTable dt)
{
var workbookpart = document.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
var sheets = document.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
var sheet = new Sheet()
{
Id = document.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Sheet1"
};
sheets.Append(sheet);
DtToExcel(worksheetPart, dt);
document.Close();
}
public static DataTable Import(string filePath)
{
using (SpreadsheetDocument document = SpreadsheetDocument.Open(filePath, false))
{
return ExcelToDt(document);
}
}
public static DataTable Import(Stream stream)
{
using (SpreadsheetDocument document = SpreadsheetDocument.Open(stream, false))
{
return ExcelToDt(document);
}
}
private static void DtToExcel(WorksheetPart worksheetPart, DataTable dt)
{
var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
var dcc = dt.Columns;
var drc = dt.Rows;
uint rowIndex = 1;
var headRow = new Row() { RowIndex = rowIndex };
var headCells = new List<Cell>();
foreach (DataColumn item in dcc)
{
headCells.Add(new Cell() { CellValue = new CellValue(item.ColumnName), DataType = CellValues.String });
}
headRow.Append(headCells);
sheetData.Append(headRow);
foreach (DataRow dr in drc)
{
rowIndex++;
var row = new Row() { RowIndex = rowIndex };
var cells = new List<Cell>();
for (var i = 0; i < headRow.Count(); i++)
{
cells.Add(new Cell() { CellValue = new CellValue(dr[i].ToString()), DataType = CellValues.String });
}
row.Append(cells);
sheetData.Append(row);
}
worksheetPart.Worksheet.Save();
}
private static DataTable ExcelToDt(SpreadsheetDocument document)
{
DataTable dt = new DataTable();
var sheet = document.WorkbookPart.Workbook.GetFirstChild<Sheets>().GetFirstChild<Sheet>();
if (sheet == null) return null;
var worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheet.Id.Value);
var rows = worksheetPart.Worksheet.GetFirstChild<SheetData>().Elements<Row>();
if (rows == null || rows.Count() == 0) return null;
var headNames = new List<string>();
var headValues = new List<string>();
GetHeaderCell(document, rows.First().Elements<Cell>(), ref headNames, ref headValues);
if (headValues.Count == 0) return null;
foreach (var item in headValues)
{
dt.Columns.Add(new DataColumn(item.Trim('*'), typeof(System.String)));
}
rows.First().Remove();
if (rows.Count() > 10000) throw new ArgumentException("数据量太大,请分批上传,一次上传不超过5000条为最佳!");
var tasks = new List<Task>();
foreach (var row in rows)
{
var items = GetCellValues(document, row.Elements<Cell>(), headNames);
if (items.Count > 0)
{
DataRow dr = dt.NewRow();
for (var i = 0; i < headValues.Count; i++)
{
dr[i] = items[i];
}
dt.Rows.Add(dr);
}
}
return dt;
}
private static void GetHeaderCell(SpreadsheetDocument document, IEnumerable<Cell> cells, ref List<string> headNames, ref List<string> headValues)
{
foreach (var cell in cells)
{
if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
{
var shareStringPart = document.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
var items = shareStringPart.SharedStringTable.Elements<SharedStringItem>().ToArray();
headValues.Add(items[int.Parse(cell.CellValue.Text)].InnerText.Trim(new char[] { '\'' }).Trim());
headNames.Add(GetCellChar(cell.CellReference.Value));
}
else
{
if (cell.CellValue != null)
{
headValues.Add(cell.CellValue.Text.Trim(new char[] { '\'' }));
headNames.Add(GetCellChar(cell.CellReference.Value));
}
}
}
}
private static List<string> GetCellValues(SpreadsheetDocument document, IEnumerable<Cell> cells, List<string> headNames)
{
var list = new List<string>();
foreach (var item in headNames)
{
var cell = cells.FirstOrDefault(c => c.CellReference.Value.StartsWith(item));
if (cell == null) list.Add("");
else
{
if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
{
var shareStringPart = document.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
var items = shareStringPart.SharedStringTable.Elements<SharedStringItem>().ToArray();
list.Add(items[int.Parse(cell.CellValue.Text)].InnerText.Trim());
}
else
{
if (cell.CellValue != null) list.Add(cell.CellValue.Text.Trim());
else list.Add("");
}
}
}
return list;
}
private int InsertSharedStringItem(string text, SharedStringTablePart shareStringPart)
{
// If the part does not contain a SharedStringTable, create one.
if (shareStringPart.SharedStringTable == null)
{
shareStringPart.SharedStringTable = new SharedStringTable();
}
int i = 0;
// Iterate through all the items in the SharedStringTable. If the text already exists, return its index.
foreach (SharedStringItem item in shareStringPart.SharedStringTable.Elements<SharedStringItem>())
{
if (item.InnerText == text)
{
return i;
}
i++;
}
// The text does not exist in the part. Create the SharedStringItem and return its index.
shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new DocumentFormat.OpenXml.Spreadsheet.Text(text)));
shareStringPart.SharedStringTable.Save();
return i;
}
private Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart)
{
Worksheet worksheet = worksheetPart.Worksheet;
SheetData sheetData = worksheet.GetFirstChild<SheetData>();
string cellReference = columnName + rowIndex;
// If the worksheet does not contain a row with the specified row index, insert one.
Row row;
if (sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).Count() != 0)
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
}
else
{
row = new Row() { RowIndex = rowIndex };
sheetData.Append(row);
}
// If there is not a cell with the specified column name, insert one.
if (row.Elements<Cell>().Where(c => c.CellReference.Value == columnName + rowIndex).Count() > 0)
{
return row.Elements<Cell>().Where(c => c.CellReference.Value == cellReference).First();
}
else
{
// Cells must be in sequential order according to CellReference. Determine where to insert the new cell.
Cell refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
if (cell.CellReference.Value.Length == cellReference.Length)
{
if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
{
refCell = cell;
break;
}
}
}
Cell newCell = new Cell() { CellReference = cellReference };
row.InsertBefore(newCell, refCell);
worksheet.Save();
return newCell;
}
}
private Char GetColumnName(int index)
{
var az = new List<Char>(Enumerable.Range('A', 'Z' - 'A' + 1).Select(i => (Char)i).ToArray());
return az[index];
}
private uint GetRowIndex(string cellName)
{
Match match = Regex.Match(cellName, @"\d+");
return uint.Parse(match.Value);
}
private static string GetCellChar(string cellRef)
{
return Regex.Replace(cellRef, @"\d+", "");
}
}
}
| 38.719424 | 153 | 0.530286 | [
"MIT"
] | 64075898/Asset | src/TygaSoft/Converter/ExcelHelper.cs | 10,814 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Xunit;
namespace System.IO.MemoryMappedFiles.Tests
{
/// <summary>
/// Tests for MemoryMappedFile.CreateFromFile.
/// </summary>
public class MemoryMappedFileTests_CreateFromFile : MemoryMappedFilesTestBase
{
/// <summary>
/// Tests invalid arguments to the CreateFromFile path parameter.
/// </summary>
[Fact]
public void InvalidArguments_Path()
{
// null is an invalid path
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName()));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read));
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile fileStream parameter.
/// </summary>
[Fact]
public void InvalidArguments_FileStream()
{
// null is an invalid stream
AssertExtensions.Throws<ArgumentNullException>("fileStream", () => MemoryMappedFile.CreateFromFile(null, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile mode parameter.
/// </summary>
[Fact]
public void InvalidArguments_Mode()
{
// FileMode out of range
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42));
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null));
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096));
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096, MemoryMappedFileAccess.ReadWrite));
// FileMode.Append never allowed
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append));
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null));
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096));
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096, MemoryMappedFileAccess.ReadWrite));
// FileMode.CreateNew/Create/OpenOrCreate can't be used with default capacity, as the file will be empty
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Create));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.OpenOrCreate));
// FileMode.Truncate can't be used with default capacity, as resulting file will be empty
using (TempFile file = new TempFile(GetTestFilePath()))
{
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Truncate));
}
}
[Fact]
public void InvalidArguments_Mode_Truncate()
{
// FileMode.Truncate never allowed
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate));
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null));
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null, 4096));
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null, 4096, MemoryMappedFileAccess.ReadWrite));
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile access parameter.
/// </summary>
[Fact]
public void InvalidArguments_Access()
{
// Out of range access values with a path
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42)));
// Write-only access is not allowed on maps (only on views)
AssertExtensions.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write));
// Test the same things, but with a FileStream instead of a path
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Out of range values with a stream
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2), HandleInheritability.None, true));
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42), HandleInheritability.None, true));
// Write-only access is not allowed
AssertExtensions.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write, HandleInheritability.None, true));
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream. The combinations should all be valid.
/// </summary>
[Theory]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.CopyOnWrite)]
public void FileAccessAndMapAccessCombinations_Valid(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true))
{
ValidateMemoryMappedFile(mmf, Capacity, mmfAccess);
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream on Windows. The combinations should all be invalid, resulting in exception.
/// </summary>
[PlatformSpecific(TestPlatforms.Windows)] // On Windows, permission errors come from CreateFromFile
[Theory]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute)] // this and the next are explicitly left off of the Unix test due to differences in Unix permissions
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute)]
public void FileAccessAndMapAccessCombinations_Invalid_Windows(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
// On Windows, creating the file mapping does the permissions checks, so the exception comes from CreateFromFile.
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
{
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true));
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream on Unix. The combinations should all be invalid, resulting in exception.
/// </summary>
[PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, permission errors come from CreateView*
[Theory]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)]
public void FileAccessAndMapAccessCombinations_Invalid_Unix(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
// On Unix we don't actually create the OS map until the view is created; this results in the permissions
// error being thrown from CreateView* instead of from CreateFromFile.
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true))
{
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor());
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile mapName parameter.
/// </summary>
[Fact]
public void InvalidArguments_MapName()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// Empty string is an invalid map name
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read));
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, string.Empty, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
}
}
/// <summary>
/// Test to verify that map names are left unsupported on Unix.
/// </summary>
[PlatformSpecific(TestPlatforms.AnyUnix)] // Check map names are unsupported on Unix
[Theory]
[MemberData(nameof(CreateValidMapNames))]
public void MapNamesNotSupported_Unix(string mapName)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
{
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite));
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(fs, mapName, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile capacity parameter.
/// </summary>
[Fact]
public void InvalidArguments_Capacity()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// Out of range values for capacity
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1));
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1, MemoryMappedFileAccess.Read));
// Positive capacity required when creating a map from an empty file
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 0, MemoryMappedFileAccess.Read));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read));
// With Read, the capacity can't be larger than the backing file's size.
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read));
// Now with a FileStream...
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// The subsequent tests are only valid we if we start with an empty FileStream, which we should have.
// This also verifies the previous failed tests didn't change the length of the file.
Assert.Equal(0, fs.Length);
// Out of range values for capacity
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(fs, null, -1, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Default (0) capacity with an empty file
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, null, 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Larger capacity than the underlying file, but read-only such that we can't expand the file
fs.SetLength(4096);
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, null, 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Capacity can't be less than the file size (for such cases a view can be created with the smaller size)
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(fs, null, 1, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
// Capacity can't be less than the file size
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read));
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile inheritability parameter.
/// </summary>
[Theory]
[InlineData((HandleInheritability)(-1))]
[InlineData((HandleInheritability)(42))]
public void InvalidArguments_Inheritability(HandleInheritability inheritability)
{
// Out of range values for inheritability
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("inheritability", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite, inheritability, true));
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the Open and OpenOrCreate modes,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath),
new FileMode[] { FileMode.Open, FileMode.OpenOrCreate },
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })]
public void ValidArgumentCombinationsWithPath_ModesOpenOrCreate(
FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
{
// Test each of the four path-based CreateFromFile overloads
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
// Finally, re-test the last overload, this time with an empty file to start
using (TempFile file = new TempFile(GetTestFilePath()))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the CreateNew mode,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath),
new FileMode[] { FileMode.CreateNew },
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })]
public void ValidArgumentCombinationsWithPath_ModeCreateNew(
FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
{
// For FileMode.CreateNew, the file will be created new and thus be empty, so we can only use the overloads
// that take a capacity, since the default capacity doesn't work with an empty file.
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity, access))
{
ValidateMemoryMappedFile(mmf, capacity, access);
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the Create mode,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidNameCapacityCombinationsWithPath),
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 })]
public void ValidArgumentCombinationsWithPath_ModeCreate(string mapName, long capacity)
{
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Create, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Create, mapName, capacity, MemoryMappedFileAccess.ReadWrite))
{
ValidateMemoryMappedFile(mmf, capacity, MemoryMappedFileAccess.ReadWrite);
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Create, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
}
/// <summary>
/// Provides input data to the ValidArgumentCombinationsWithPath tests, yielding the full matrix
/// of combinations of input values provided, except for those that are known to be unsupported
/// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders
/// listed in the MemberData attribute (e.g. actual system page size instead of -1).
/// </summary>
/// <param name="modes">The modes to yield.</param>
/// <param name="mapNames">
/// The names to yield.
/// non-null may be excluded based on platform.
/// "CreateUniqueMapName()" will be translated to an invocation of that method.
/// </param>
/// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param>
/// <param name="accesses">
/// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it.
/// </param>
public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithPath(
FileMode[] modes, string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses)
{
foreach (object[] namesCaps in MemberData_ValidNameCapacityCombinationsWithPath(mapNames, capacities))
{
foreach (FileMode mode in modes)
{
foreach (MemoryMappedFileAccess access in accesses)
{
if ((mode == FileMode.Create || mode == FileMode.CreateNew || mode == FileMode.Truncate) &&
!IsWritable(access))
{
continue;
}
yield return new object[] { mode, namesCaps[0], namesCaps[1], access };
}
}
}
}
public static IEnumerable<object[]> MemberData_ValidNameCapacityCombinationsWithPath(
string[] mapNames, long[] capacities)
{
foreach (string tmpMapName in mapNames)
{
if (tmpMapName != null && !MapNamesSupported)
{
continue;
}
foreach (long tmpCapacity in capacities)
{
long capacity = tmpCapacity == -1 ? s_pageSize.Value : tmpCapacity;
string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName;
yield return new object[] { mapName, capacity, };
}
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile that accepts a FileStream.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithStream),
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite },
new HandleInheritability[] { HandleInheritability.None, HandleInheritability.Inheritable },
new bool[] { false, true })]
public void ValidArgumentCombinationsWithStream(
string mapName, long capacity, MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen)
{
// Create a file of the right size, then create the map for it.
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen))
{
ValidateMemoryMappedFile(mmf, capacity, access, inheritability);
}
// Start with an empty file and let the map grow it to the right size. This requires write access.
if (IsWritable(access))
{
using (FileStream fs = File.Create(GetTestFilePath()))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen))
{
ValidateMemoryMappedFile(mmf, capacity, access, inheritability);
}
}
}
/// <summary>
/// Provides input data to the ValidArgumentCombinationsWithStream tests, yielding the full matrix
/// of combinations of input values provided, except for those that are known to be unsupported
/// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders
/// listed in the MemberData attribute (e.g. actual system page size instead of -1).
/// </summary>
/// <param name="mapNames">
/// The names to yield.
/// non-null may be excluded based on platform.
/// "CreateUniqueMapName()" will be translated to an invocation of that method.
/// </param>
/// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param>
/// <param name="accesses">
/// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it.
/// </param>
/// <param name="inheritabilities">The inheritabilities to yield.</param>
/// <param name="inheritabilities">The leaveOpen values to yield.</param>
public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithStream(
string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses, HandleInheritability[] inheritabilities, bool[] leaveOpens)
{
foreach (string tmpMapName in mapNames)
{
if (tmpMapName != null && !MapNamesSupported)
{
continue;
}
foreach (long tmpCapacity in capacities)
{
long capacity = tmpCapacity == -1 ?
s_pageSize.Value :
tmpCapacity;
foreach (MemoryMappedFileAccess access in accesses)
{
foreach (HandleInheritability inheritability in inheritabilities)
{
foreach (bool leaveOpen in leaveOpens)
{
string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName;
yield return new object[] { mapName, capacity, access, inheritability, leaveOpen };
}
}
}
}
}
}
/// <summary>
/// Test that a map using the default capacity (0) grows to the size of the underlying file.
/// </summary>
[Fact]
public void DefaultCapacityIsFileLength()
{
const int DesiredCapacity = 8192;
const int DefaultCapacity = 0;
// With path
using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, DefaultCapacity))
{
ValidateMemoryMappedFile(mmf, DesiredCapacity);
}
// With stream
using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, DefaultCapacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
{
ValidateMemoryMappedFile(mmf, DesiredCapacity);
}
}
/// <summary>
/// Test that appropriate exceptions are thrown creating a map with a non-existent file and a mode
/// that requires the file to exist.
/// </summary>
[Fact]
public void FileDoesNotExist_OpenFileMode()
{
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath()));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null, 4096));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null, 4096, MemoryMappedFileAccess.ReadWrite));
}
/// <summary>
/// Test that appropriate exceptions are thrown creating a map with an existing file and a mode
/// that requires the file to not exist.
/// </summary>
[Fact]
public void FileAlreadyExists()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// FileMode.CreateNew invalid when the file already exists
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName()));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a read-write file that's currently in use.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent
public void FileInUse_CreateFromFile_FailsWithExistingReadWriteFile()
{
// Already opened with a FileStream
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent
public void FileInUse_CreateFromFile_FailsWithExistingReadWriteMap()
{
// Already opened with another read-write map
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use.
/// </summary>
[Fact]
public void FileInUse_CreateFromFile_FailsWithExistingNoShareFile()
{
// Already opened with a FileStream
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (FileStream fs = File.Open(file.Path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test to validate we can create multiple concurrent read-only maps from the same file path.
/// </summary>
[Fact]
public void FileInUse_CreateFromFile_SucceedsWithReadOnly()
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read))
{
Assert.Equal(acc1.Capacity, acc2.Capacity);
}
}
/// <summary>
/// Test the exceptional behavior of *Execute access levels.
/// </summary>
[PlatformSpecific(TestPlatforms.Windows)] // Unix model for executable differs from Windows
[Theory]
[InlineData(MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute)]
public void FileNotOpenedForExecute(MemoryMappedFileAccess access)
{
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
{
// The FileStream created by the map doesn't have GENERIC_EXECUTE set
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 4096, access));
// The FileStream opened explicitly doesn't have GENERIC_EXECUTE set
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, 4096, access, HandleInheritability.None, true));
}
}
}
/// <summary>
/// On Unix, modifying a file that is ReadOnly will fail under normal permissions.
/// If the test is being run under the superuser, however, modification of a ReadOnly
/// file is allowed.
/// </summary>
private void WriteToReadOnlyFile(MemoryMappedFileAccess access, bool succeeds)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
{
FileAttributes original = File.GetAttributes(file.Path);
File.SetAttributes(file.Path, FileAttributes.ReadOnly);
try
{
if (succeeds)
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access))
ValidateMemoryMappedFile(mmf, Capacity, MemoryMappedFileAccess.Read);
else
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access));
}
finally
{
File.SetAttributes(file.Path, original);
}
}
}
[Theory]
[InlineData(MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWrite)]
public void WriteToReadOnlyFile_ReadWrite(MemoryMappedFileAccess access)
{
WriteToReadOnlyFile(access, access == MemoryMappedFileAccess.Read ||
(!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && geteuid() == 0));
}
[Fact]
public void WriteToReadOnlyFile_CopyOnWrite()
{
WriteToReadOnlyFile(MemoryMappedFileAccess.CopyOnWrite, (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && geteuid() == 0));
}
/// <summary>
/// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open
/// or closing it on disposal.
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public void LeaveOpenRespected_Basic(bool leaveOpen)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Handle should still be open
SafeFileHandle handle = fs.SafeFileHandle;
Assert.False(handle.IsClosed);
// Create and close the map
MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen).Dispose();
// The handle should now be open iff leaveOpen
Assert.NotEqual(leaveOpen, handle.IsClosed);
}
}
/// <summary>
/// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open
/// or closing it on disposal.
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public void LeaveOpenRespected_OutstandingViews(bool leaveOpen)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Handle should still be open
SafeFileHandle handle = fs.SafeFileHandle;
Assert.False(handle.IsClosed);
// Create the map, create each of the views, then close the map
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen))
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, Capacity))
using (MemoryMappedViewStream s = mmf.CreateViewStream(0, Capacity))
{
// Explicitly close the map. The handle should now be open iff leaveOpen.
mmf.Dispose();
Assert.NotEqual(leaveOpen, handle.IsClosed);
// But the views should still be usable.
ValidateMemoryMappedViewAccessor(acc, Capacity, MemoryMappedFileAccess.ReadWrite);
ValidateMemoryMappedViewStream(s, Capacity, MemoryMappedFileAccess.ReadWrite);
}
}
}
/// <summary>
/// Test to validate we can create multiple maps from the same FileStream.
/// </summary>
[Fact]
public void MultipleMapsForTheSameFileStream()
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open))
using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor())
using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor())
{
// The capacity of the two maps should be equal
Assert.Equal(acc1.Capacity, acc2.Capacity);
var rand = new Random();
for (int i = 1; i <= 10; i++)
{
// Write a value to one map, then read it from the other,
// ping-ponging between the two.
int pos = rand.Next((int)acc1.Capacity - 1);
MemoryMappedViewAccessor reader = acc1, writer = acc2;
if (i % 2 == 0)
{
reader = acc2;
writer = acc1;
}
writer.Write(pos, (byte)i);
writer.Flush();
Assert.Equal(i, reader.ReadByte(pos));
}
}
}
/// <summary>
/// Test to verify that the map's size increases the underlying file size if the map's capacity is larger.
/// </summary>
[Fact]
public void FileSizeExpandsToCapacity()
{
const int InitialCapacity = 256;
using (TempFile file = new TempFile(GetTestFilePath(), InitialCapacity))
{
// Create a map with a larger capacity, and verify the file has expanded.
MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, InitialCapacity * 2).Dispose();
using (FileStream fs = File.OpenRead(file.Path))
{
Assert.Equal(InitialCapacity * 2, fs.Length);
}
// Do the same thing again but with a FileStream.
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
MemoryMappedFile.CreateFromFile(fs, null, InitialCapacity * 4, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose();
Assert.Equal(InitialCapacity * 4, fs.Length);
}
}
}
/// <summary>
/// Test the exceptional behavior when attempting to create a map so large it's not supported.
/// </summary>
[PlatformSpecific(~TestPlatforms.OSX)] // Because of the file-based backing, OS X pops up a warning dialog about being out-of-space (even though we clean up immediately)
[Fact]
public void TooLargeCapacity()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.CreateNew))
{
try
{
long length = long.MaxValue;
MemoryMappedFile.CreateFromFile(fs, null, length, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose();
Assert.Equal(length, fs.Length); // if it didn't fail to create the file, the length should be what was requested.
}
catch (IOException)
{
// Expected exception for too large a capacity
}
}
}
/// <summary>
/// Test to verify map names are handled appropriately, causing a conflict when they're active but
/// reusable in a sequential manner.
/// </summary>
[PlatformSpecific(TestPlatforms.Windows)] // Tests reusability of map names on Windows
[Theory]
[MemberData(nameof(CreateValidMapNames))]
public void ReusingNames_Windows(string name)
{
const int Capacity = 4096;
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity))
{
ValidateMemoryMappedFile(mmf, Capacity);
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity));
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity))
{
ValidateMemoryMappedFile(mmf, Capacity);
}
}
}
}
| 55.485649 | 215 | 0.633153 | [
"MIT"
] | ARhj/corefx | src/System.IO.MemoryMappedFiles/tests/MemoryMappedFile.CreateFromFile.Tests.cs | 48,328 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WpfApp1.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WpfApp1.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Value.
/// </summary>
internal static string Key {
get {
return ResourceManager.GetString("Key", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to .
/// </summary>
internal static string TextFile1 {
get {
return ResourceManager.GetString("TextFile1", resourceCulture);
}
}
}
}
| 40.47561 | 173 | 0.589937 | [
"MIT"
] | GuOrg/Gu.Roslyn.Asserts | TestApps/WpfApp1/Properties/Resources.Designer.cs | 3,321 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
/*
Copyright 2017 Enkhbold Nyamsuren (http://www.bcogs.net , http://www.bcogs.info/)
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.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SeriousRPG.Editor.ActionNS;
using SeriousRPG.Editor.ConditionNS;
using SeriousRPG.Model.RuleNS;
using SeriousRPG.Model.GameNS;
using SeriousRPG.Model;
namespace SeriousRPG.Editor.RuleNS {
public partial class RuleForm : Form {
public RuleForm() {
InitializeComponent();
UpdateRuleDGV();
}
private void UpdateRuleDGV() {
this.ruleGridView.Rows.Clear();
IEnumerable<IdNamePair> rules = Game.GetInstance().GetRuleList<IRule>();
foreach (IdNamePair ruleObj in rules) {
int id = ruleObj.Id;
string description = ruleObj.Name;
this.ruleGridView.Rows.Add(id, description);
}
}
private void addRuleBtn_Click(object sender, EventArgs e) {
new AddRuleForm().ShowDialog();
UpdateRuleDGV();
}
private void editRuleBtn_Click(object sender, EventArgs e) {
// [TODO]
}
private void removeRuleBtn_Click(object sender, EventArgs e) {
// [TODO]
}
private void manageConditionsBtn_Click(object sender, EventArgs e) {
new ConditionForm().ShowDialog();
}
private void manageActionsBtn_Click(object sender, EventArgs e) {
new ActionForm().ShowDialog();
}
private void quickTriggerRuleBtn_Click(object sender, EventArgs e) {
new QuickTriggerRuleForm().ShowDialog();
UpdateRuleDGV();
}
}
}
| 29.2 | 84 | 0.661387 | [
"Apache-2.0"
] | E-Nyamsuren/SeriousRPG-Proof-of-Concept | SeriousRPG/Editor/RuleNS/RuleForm.cs | 2,338 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using Sdl.Web.Common;
using Sdl.Web.Common.Logging;
using SDL.DXA.AlpacaForms.DBHandler.Models;
using SDL.DXA.Modules.Forms;
using SDL.DXA.Modules.Forms.Models;
namespace SDL.DXA.AlpacaForms.DBHandler
{
/// <summary>
/// Simple DB repository for forms.
/// </summary>
public class DBFormsRepository
{
private string connectionString;
const string GET_NEXT_FORM_ID = "SELECT NEXT VALUE FOR FORM_ID_SEQUENCE";
const string INSERT_FORM_DATA_SQL = "INSERT INTO SUBMITTED_FORM(ID, FORM_ID, SUBMIT_DATE) VALUES(@Id,@FormId,@SubmitDate);";
const string INSERT_FORM_FIELD_SQL = "INSERT INTO SUBMITTED_FORM_FIELD(ID, NAME, VALUE) VALUES(@Id,@Name,@Value)";
const string SELECT_ALL_FORMS = "SELECT FORM_ID, COUNT(FORM_ID) AS SUBMITTED_COUNT FROM SUBMITTED_FORM GROUP BY FORM_ID";
const string SELECT_SUBMITTED_FORMS = "SELECT ID, SUBMIT_DATE FROM SUBMITTED_FORM WHERE FORM_ID=@FormId ORDER BY ID";
const string SELECT_SUBMITTED_FORM_FIELDS = "SELECT NAME,VALUE FROM SUBMITTED_FORM_FIELD WHERE ID=@Id";
/// <summary>
/// Constructor
/// </summary>
/// <param name="connectionString"></param>
public DBFormsRepository(string connectionString)
{
this.connectionString = connectionString;
}
/// <summary>
/// Store submitted form
/// </summary>
/// <param name="form"></param>
/// <param name="formData"></param>
public void StoreSubmittedForm(Form form, FormCollection formData)
{
using ( SqlConnection sqlConnection = new SqlConnection(connectionString) )
{
try
{
sqlConnection.Open();
var getFormSequenceIdSQL = new SqlCommand(GET_NEXT_FORM_ID, sqlConnection);
SqlDataReader reader = getFormSequenceIdSQL.ExecuteReader();
using (reader)
{
if (reader.Read())
{
int formSequenceId = reader.GetInt32(0);
reader.Close();
var insertFormSQL = new SqlCommand(INSERT_FORM_DATA_SQL, sqlConnection);
insertFormSQL.Parameters.Add("@Id", SqlDbType.Int).Value = formSequenceId;
insertFormSQL.Parameters.Add("@FormId", SqlDbType.NVarChar).Value = form.FormId;
insertFormSQL.Parameters.Add("@SubmitDate", SqlDbType.Date).Value = DateTime.Now;
insertFormSQL.ExecuteNonQuery();
foreach (var formFieldName in formData.Keys.Cast<string>())
{
var insertFormFieldSQL = new SqlCommand(INSERT_FORM_FIELD_SQL, sqlConnection);
insertFormFieldSQL.Parameters.Add("@Id", SqlDbType.Int).Value = formSequenceId;
insertFormFieldSQL.Parameters.Add("@Name", SqlDbType.NVarChar).Value = formFieldName;
insertFormFieldSQL.Parameters.Add("@Value", SqlDbType.NVarChar).Value = formData[formFieldName];
insertFormFieldSQL.ExecuteNonQuery();
}
}
}
}
catch (Exception e)
{
throw new DxaException("Could not store submitted form.", e);
}
}
}
/// <summary>
/// Get all defined forms that have submitted form data
/// </summary>
/// <returns></returns>
public IList<DBForm> GetAllForms()
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
try
{
sqlConnection.Open();
var getAllFormsSQL = new SqlCommand(SELECT_ALL_FORMS, sqlConnection);
SqlDataReader reader = getAllFormsSQL.ExecuteReader();
IList<DBForm> allForms = new List<DBForm>();
while (reader.Read())
{
string formId = reader.GetString(0);
int count = reader.GetInt32(1);
Form form = FormRepository.GetForm(formId);
if (form != null)
{
DBForm dbForm = new DBForm(form);
dbForm.Count = count;
allForms.Add(dbForm);
}
}
return allForms;
}
catch (Exception e)
{
throw new DxaException("Could not get all forms.", e);
}
}
}
/// <summary>
/// Get a specific form and its submitted data
/// </summary>
/// <param name="formId"></param>
/// <returns></returns>
public DBForm GetForm(string formId)
{
Form form = FormRepository.GetForm(formId);
if (form == null)
{
Log.Warn("No form found in the Broker DB with ID: " + formId);
return null;
}
DBForm dbForm = new DBForm(form);
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
try
{
sqlConnection.Open();
var getSubmittedFormsSQL = new SqlCommand(SELECT_SUBMITTED_FORMS, sqlConnection);
getSubmittedFormsSQL.Parameters.Add("@FormId", SqlDbType.NVarChar).Value = form.FormId;
SqlDataReader reader = getSubmittedFormsSQL.ExecuteReader();
IList<SubmittedForm> submittedForms = new List<SubmittedForm>();
dbForm.SubmittedForms = submittedForms;
while (reader.Read())
{
int id = reader.GetInt32(0);
DateTime date = reader.GetDateTime(1);
SubmittedForm submittedForm = new SubmittedForm { SequenceId = id, SubmitDate = date};
submittedForms.Add(submittedForm);
}
dbForm.Count = submittedForms.Count;
return dbForm;
}
catch (Exception e)
{
throw new DxaException("Could not get all forms.", e);
}
}
}
/// <summary>
/// Get a specific submitted form with form fields
/// </summary>
/// <param name="sequenceId"></param>
/// <returns></returns>
public SubmittedForm GetSubmittedForm(int sequenceId)
{
SubmittedForm form = new SubmittedForm();
form.SequenceId = sequenceId;
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
try
{
sqlConnection.Open();
var getSubmittedFormSQL = new SqlCommand(SELECT_SUBMITTED_FORM_FIELDS, sqlConnection);
getSubmittedFormSQL.Parameters.Add("@Id", SqlDbType.Int).Value = sequenceId;
SqlDataReader reader = getSubmittedFormSQL.ExecuteReader();
form.FormData = new FormCollection();
while (reader.Read())
{
string name = reader.GetString(0);
string value = reader.GetString(1);
Log.Info("Form " + name + " = " + value);
form.FormData.Add(name, value);
}
return form;
}
catch (Exception e)
{
throw new DxaException("Could not get all forms.", e);
}
}
}
}
} | 41.899497 | 132 | 0.511274 | [
"Apache-2.0"
] | NiclasCedermalm/dxa-alpaca-forms | dotnet/SDL.DXA.AlpacaForms.DBHandler/DBFormsRepository.cs | 8,340 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.