text stringlengths 13 6.01M |
|---|
namespace CustomerBarcodeGenerator;
internal static class BarcodeUtils
{
public static IEnumerable<Bar> Generate(string data)
{
return GenerateBarcodeCharacters(data).SelectMany(t => ConvertToBars(t));
}
private static IEnumerable<BarcodeCharacter> GenerateBarcodeCharacters(string data)
{
yield return BarcodeCharacter.Start;
int sum = 19;
foreach (var bc in PadLast(data.SelectMany(ConvertToBarcodeCharacters).Take(20), 20, BarcodeCharacter.CC4))
{
sum += (int)bc;
yield return bc;
}
yield return BarcodeCharacter.Num0 + 18 - (sum - 1) % 19;
yield return BarcodeCharacter.Stop;
}
private static IEnumerable<BarcodeCharacter> ConvertToBarcodeCharacters(char character)
{
if (character is >= '0' and <= '9')
{
yield return BarcodeCharacter.Num0 + character - '0';
}
else if (character is '-')
{
yield return BarcodeCharacter.Hyphen;
}
else if (character is >= 'A' and <= 'Z')
{
yield return BarcodeCharacter.CC1 + (character - 'A') / 10;
yield return BarcodeCharacter.Num0 + (character - 'A') % 10;
}
}
private static IEnumerable<Bar> ConvertToBars(BarcodeCharacter bc)
{
switch (bc)
{
case BarcodeCharacter.Num0:
yield return Bar.Long;
yield return Bar.Timing;
yield return Bar.Timing;
break;
case BarcodeCharacter.Num1:
yield return Bar.Long;
yield return Bar.Long;
yield return Bar.Timing;
break;
case BarcodeCharacter.Num2:
yield return Bar.Long;
yield return Bar.Down;
yield return Bar.Up;
break;
case BarcodeCharacter.Num3:
yield return Bar.Down;
yield return Bar.Long;
yield return Bar.Up;
break;
case BarcodeCharacter.Num4:
yield return Bar.Long;
yield return Bar.Up;
yield return Bar.Down;
break;
case BarcodeCharacter.Num5:
yield return Bar.Long;
yield return Bar.Timing;
yield return Bar.Long;
break;
case BarcodeCharacter.Num6:
yield return Bar.Down;
yield return Bar.Up;
yield return Bar.Long;
break;
case BarcodeCharacter.Num7:
yield return Bar.Up;
yield return Bar.Long;
yield return Bar.Down;
break;
case BarcodeCharacter.Num8:
yield return Bar.Up;
yield return Bar.Down;
yield return Bar.Long;
break;
case BarcodeCharacter.Num9:
yield return Bar.Timing;
yield return Bar.Long;
yield return Bar.Long;
break;
case BarcodeCharacter.Hyphen:
yield return Bar.Timing;
yield return Bar.Long;
yield return Bar.Timing;
break;
case BarcodeCharacter.CC1:
yield return Bar.Down;
yield return Bar.Up;
yield return Bar.Timing;
break;
case BarcodeCharacter.CC2:
yield return Bar.Down;
yield return Bar.Timing;
yield return Bar.Up;
break;
case BarcodeCharacter.CC3:
yield return Bar.Up;
yield return Bar.Down;
yield return Bar.Timing;
break;
case BarcodeCharacter.CC4:
yield return Bar.Timing;
yield return Bar.Down;
yield return Bar.Up;
break;
case BarcodeCharacter.CC5:
yield return Bar.Up;
yield return Bar.Timing;
yield return Bar.Down;
break;
case BarcodeCharacter.CC6:
yield return Bar.Timing;
yield return Bar.Up;
yield return Bar.Down;
break;
case BarcodeCharacter.CC7:
yield return Bar.Timing;
yield return Bar.Timing;
yield return Bar.Long;
break;
case BarcodeCharacter.CC8:
yield return Bar.Long;
yield return Bar.Long;
yield return Bar.Long;
break;
case BarcodeCharacter.Start:
yield return Bar.Long;
yield return Bar.Down;
break;
case BarcodeCharacter.Stop:
yield return Bar.Down;
yield return Bar.Long;
break;
default:
break;
}
}
private static IEnumerable<T> PadLast<T>(IEnumerable<T> src, int totalCount, T paddingValue)
{
int count = 0;
foreach (var item in src)
{
count++;
yield return item;
}
for (int i = count; i < totalCount; i++)
{
yield return paddingValue;
}
}
private enum BarcodeCharacter
{
Num0,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
Hyphen,
CC1,
CC2,
CC3,
CC4,
CC5,
CC6,
CC7,
CC8,
Start,
Stop,
}
public enum Bar
{
Long = 1,
Up = 2,
Down = 3,
Timing = 4,
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _02.BankAccounts
{
class Company : Customer
{
private string name;
private string type;
public string Name
{
get { return this.name; }
set { this.name = value; }
}
public string Type
{
get { return this.type; }
set { this.type = value; }
}
public Company()
{
}
public Company(string name, string type)
{
this.name = name;
this.type = type;
}
}
}
|
using NStack;
using System;
namespace Terminal.Gui {
/// <summary>
/// Specifies the border style for a <see cref="View"/> and to be used by the <see cref="Border"/> class.
/// </summary>
public enum BorderStyle {
/// <summary>
/// No border is drawn.
/// </summary>
None,
/// <summary>
/// The border is drawn with a single line limits.
/// </summary>
Single,
/// <summary>
/// The border is drawn with a double line limits.
/// </summary>
Double,
/// <summary>
/// The border is drawn with a single line and rounded corners limits.
/// </summary>
Rounded
}
/// <summary>
/// Describes the thickness of a frame around a rectangle. Four <see cref="int"/> values describe
/// the <see cref="Left"/>, <see cref="Top"/>, <see cref="Right"/>, and <see cref="Bottom"/> sides
/// of the rectangle, respectively.
/// </summary>
public struct Thickness {
/// <summary>
/// Gets or sets the width, in integers, of the left side of the bounding rectangle.
/// </summary>
public int Left;
/// <summary>
/// Gets or sets the width, in integers, of the upper side of the bounding rectangle.
/// </summary>
public int Top;
/// <summary>
/// Gets or sets the width, in integers, of the right side of the bounding rectangle.
/// </summary>
public int Right;
/// <summary>
/// Gets or sets the width, in integers, of the lower side of the bounding rectangle.
/// </summary>
public int Bottom;
/// <summary>
/// Initializes a new instance of the <see cref="Thickness"/> structure that has the
/// specified uniform length on each side.
/// </summary>
/// <param name="length"></param>
public Thickness (int length)
{
if (length < 0) {
throw new ArgumentException ("Invalid value for this property.");
}
Left = Top = Right = Bottom = length;
}
/// <summary>
/// Initializes a new instance of the <see cref="Thickness"/> structure that has specific
/// lengths (supplied as a <see cref="int"/>) applied to each side of the rectangle.
/// </summary>
/// <param name="left"></param>
/// <param name="top"></param>
/// <param name="right"></param>
/// <param name="bottom"></param>
public Thickness (int left, int top, int right, int bottom)
{
if (left < 0 || top < 0 || right < 0 || bottom < 0) {
throw new ArgumentException ("Invalid value for this property.");
}
Left = left;
Top = top;
Right = right;
Bottom = bottom;
}
/// <summary>Returns the fully qualified type name of this instance.</summary>
/// <returns>The fully qualified type name.</returns>
public override string ToString ()
{
return $"(Left={Left},Top={Top},Right={Right},Bottom={Bottom})";
}
}
/// <summary>
/// Draws a border, background, or both around another element.
/// </summary>
public class Border {
private int marginFrame => DrawMarginFrame ? 1 : 0;
/// <summary>
/// A sealed <see cref="Toplevel"/> derived class to implement <see cref="Border"/> feature.
/// This is only a wrapper to get borders on a toplevel and is recommended using another
/// derived, like <see cref="Window"/> where is possible to have borders with or without
/// border line or spacing around.
/// </summary>
public sealed class ToplevelContainer : Toplevel {
/// <inheritdoc/>
public override Border Border {
get => base.Border;
set {
if (base.Border != null && base.Border.Child != null && value.Child == null) {
value.Child = base.Border.Child;
}
base.Border = value;
if (value == null) {
return;
}
Rect frame;
if (Border.Child != null && (Border.Child.Width is Dim || Border.Child.Height is Dim)) {
frame = Rect.Empty;
} else {
frame = Frame;
}
AdjustContentView (frame);
Border.BorderChanged += Border_BorderChanged;
}
}
void Border_BorderChanged (Border border)
{
Rect frame;
if (Border.Child != null && (Border.Child.Width is Dim || Border.Child.Height is Dim)) {
frame = Rect.Empty;
} else {
frame = Frame;
}
AdjustContentView (frame);
}
/// <summary>
/// Initializes with default null values.
/// </summary>
public ToplevelContainer () : this (null, string.Empty) { }
/// <summary>
/// Initializes a <see cref="ToplevelContainer"/> with a <see cref="LayoutStyle.Computed"/>
/// </summary>
/// <param name="border">The border.</param>
/// <param name="title">The title.</param>
public ToplevelContainer (Border border, string title = null)
{
Initialize (Rect.Empty, border, title ?? string.Empty);
}
/// <summary>
/// Initializes a <see cref="ToplevelContainer"/> with a <see cref="LayoutStyle.Absolute"/>
/// </summary>
/// <param name="frame">The frame.</param>
/// <param name="border">The border.</param>
/// <param name="title">The title.</param>
public ToplevelContainer (Rect frame, Border border, string title = null) : base (frame)
{
Initialize (frame, border, title ?? string.Empty);
}
private void Initialize (Rect frame, Border border, string title)
{
ColorScheme = Colors.TopLevel;
if (border == null) {
Border = new Border () {
BorderStyle = BorderStyle.Single,
Title = (ustring)title
};
} else {
Border = border;
}
AdjustContentView (frame);
}
void AdjustContentView (Rect frame)
{
var borderLength = Border.DrawMarginFrame ? 1 : 0;
var sumPadding = Border.GetSumThickness ();
var wp = new Point ();
var wb = new Size ();
if (frame == Rect.Empty) {
wp.X = borderLength + sumPadding.Left;
wp.Y = borderLength + sumPadding.Top;
wb.Width = borderLength + sumPadding.Right;
wb.Height = borderLength + sumPadding.Bottom;
if (Border.Child == null) {
Border.Child = new ChildContentView (this) {
X = wp.X,
Y = wp.Y,
Width = Dim.Fill (wb.Width),
Height = Dim.Fill (wb.Height)
};
} else {
Border.Child.X = wp.X;
Border.Child.Y = wp.Y;
Border.Child.Width = Dim.Fill (wb.Width);
Border.Child.Height = Dim.Fill (wb.Height);
}
} else {
wb.Width = (2 * borderLength) + sumPadding.Right + sumPadding.Left;
wb.Height = (2 * borderLength) + sumPadding.Bottom + sumPadding.Top;
var cFrame = new Rect (borderLength + sumPadding.Left, borderLength + sumPadding.Top, frame.Width - wb.Width, frame.Height - wb.Height);
if (Border.Child == null) {
Border.Child = new ChildContentView (cFrame, this);
} else {
Border.Child.Frame = cFrame;
}
}
if (Subviews?.Count == 0)
base.Add (Border.Child);
Border.ChildContainer = this;
}
/// <inheritdoc/>
public override void Add (View view)
{
Border.Child.Add (view);
if (view.CanFocus) {
CanFocus = true;
}
AddMenuStatusBar (view);
}
/// <inheritdoc/>
public override void Remove (View view)
{
if (view == null) {
return;
}
SetNeedsDisplay ();
var touched = view.Frame;
Border.Child.Remove (view);
if (Border.Child.InternalSubviews.Count < 1) {
CanFocus = false;
}
RemoveMenuStatusBar (view);
}
/// <inheritdoc/>
public override void RemoveAll ()
{
Border.Child.RemoveAll ();
}
/// <inheritdoc/>
public override void Redraw (Rect bounds)
{
if (!NeedDisplay.IsEmpty) {
Driver.SetAttribute (GetNormalColor ());
Clear ();
}
var savedClip = Border.Child.ClipToBounds ();
Border.Child.Redraw (Border.Child.Bounds);
Driver.Clip = savedClip;
ClearLayoutNeeded ();
ClearNeedsDisplay ();
Driver.SetAttribute (GetNormalColor ());
Border.DrawContent (this, false);
if (HasFocus)
Driver.SetAttribute (ColorScheme.HotNormal);
if (Border.DrawMarginFrame) {
if (!ustring.IsNullOrEmpty (Border.Title))
Border.DrawTitle (this);
else
Border.DrawTitle (this, Frame);
}
Driver.SetAttribute (GetNormalColor ());
// Checks if there are any SuperView view which intersect with this window.
if (SuperView != null) {
SuperView.SetNeedsLayout ();
SuperView.SetNeedsDisplay ();
}
}
/// <inheritdoc/>
public override void OnCanFocusChanged ()
{
if (Border?.Child != null) {
Border.Child.CanFocus = CanFocus;
}
base.OnCanFocusChanged ();
}
}
private class ChildContentView : View {
View instance;
public ChildContentView (Rect frame, View instance) : base (frame)
{
this.instance = instance;
}
public ChildContentView (View instance)
{
this.instance = instance;
}
public override bool MouseEvent (MouseEvent mouseEvent)
{
return instance.MouseEvent (mouseEvent);
}
}
/// <summary>
/// Invoked when any property of Border changes (except <see cref="Child"/>).
/// </summary>
public event Action<Border> BorderChanged;
private BorderStyle borderStyle;
private bool drawMarginFrame;
private Thickness borderThickness;
private Color? borderBrush;
private Color? background;
private Thickness padding;
private bool effect3D;
private Point effect3DOffset = new Point (1, 1);
private Attribute? effect3DBrush;
private ustring title = ustring.Empty;
private View child;
/// <summary>
/// Specifies the <see cref="Gui.BorderStyle"/> for a view.
/// </summary>
public BorderStyle BorderStyle {
get => borderStyle;
set {
if (value != BorderStyle.None && !drawMarginFrame) {
// Ensures drawn the border lines.
drawMarginFrame = true;
}
borderStyle = value;
OnBorderChanged ();
}
}
/// <summary>
/// Gets or sets if a margin frame is drawn around the <see cref="Child"/> regardless the <see cref="BorderStyle"/>
/// </summary>
public bool DrawMarginFrame {
get => drawMarginFrame;
set {
if (borderStyle != BorderStyle.None
&& (!value || !drawMarginFrame)) {
// Ensures drawn the border lines.
drawMarginFrame = true;
} else {
drawMarginFrame = value;
}
OnBorderChanged ();
}
}
/// <summary>
/// Gets or sets the relative <see cref="Thickness"/> of a <see cref="Border"/>.
/// </summary>
public Thickness BorderThickness {
get => borderThickness;
set {
borderThickness = value;
OnBorderChanged ();
}
}
/// <summary>
/// Gets or sets the <see cref="Color"/> that draws the outer border color.
/// </summary>
public Color BorderBrush {
get => borderBrush != null ? (Color)borderBrush : (Color)(-1);
set {
if (Enum.IsDefined (typeof (Color), value)) {
borderBrush = value;
OnBorderChanged ();
}
}
}
/// <summary>
/// Gets or sets the <see cref="Color"/> that fills the area between the bounds of a <see cref="Border"/>.
/// </summary>
public Color Background {
get => background != null ? (Color)background : (Color)(-1);
set {
if (Enum.IsDefined (typeof (Color), value)) {
background = value;
OnBorderChanged ();
}
}
}
/// <summary>
/// Gets or sets a <see cref="Thickness"/> value that describes the amount of space between a
/// <see cref="Border"/> and its child element.
/// </summary>
public Thickness Padding {
get => padding;
set {
padding = value;
OnBorderChanged ();
}
}
/// <summary>
/// Gets the rendered width of this element.
/// </summary>
public int ActualWidth {
get {
var driver = Application.Driver;
if (Parent?.Border == null) {
return Math.Min (Child?.Frame.Width + (2 * marginFrame) + Padding.Right
+ BorderThickness.Right + Padding.Left + BorderThickness.Left ?? 0, driver.Cols);
}
return Math.Min (Parent.Frame.Width, driver.Cols);
}
}
/// <summary>
/// Gets the rendered height of this element.
/// </summary>
public int ActualHeight {
get {
var driver = Application.Driver;
if (Parent?.Border == null) {
return Math.Min (Child?.Frame.Height + (2 * marginFrame) + Padding.Bottom
+ BorderThickness.Bottom + Padding.Top + BorderThickness.Top ?? 0, driver.Rows);
}
return Math.Min (Parent.Frame.Height, driver.Rows);
}
}
/// <summary>
/// Gets or sets the single child element of a <see cref="View"/>.
/// </summary>
public View Child {
get => child;
set {
child = value;
if (child != null && Parent != null) {
Parent.Removed += Parent_Removed;
}
}
}
private void Parent_Removed (View obj)
{
if (borderBrush != null) {
BorderBrush = default;
}
if (background != null) {
Background = default;
}
child.Removed -= Parent_Removed;
}
/// <summary>
/// Gets the parent <see cref="Child"/> parent if any.
/// </summary>
public View Parent { get => Child?.SuperView; }
/// <summary>
/// Gets or private sets by the <see cref="ToplevelContainer"/>
/// </summary>
public ToplevelContainer ChildContainer { get; private set; }
/// <summary>
/// Gets or sets the 3D effect around the <see cref="Border"/>.
/// </summary>
public bool Effect3D {
get => effect3D;
set {
effect3D = value;
OnBorderChanged ();
}
}
/// <summary>
/// Get or sets the offset start position for the <see cref="Effect3D"/>
/// </summary>
public Point Effect3DOffset {
get => effect3DOffset;
set {
effect3DOffset = value;
OnBorderChanged ();
}
}
/// <summary>
/// Gets or sets the color for the <see cref="Border"/>
/// </summary>
public Attribute? Effect3DBrush {
get => effect3DBrush;
set {
effect3DBrush = value;
OnBorderChanged ();
}
}
/// <summary>
/// The title to be displayed for this view.
/// </summary>
public ustring Title {
get => title;
set {
title = value;
OnBorderChanged ();
}
}
/// <summary>
/// Calculate the sum of the <see cref="Padding"/> and the <see cref="BorderThickness"/>
/// </summary>
/// <returns>The total of the <see cref="Border"/> <see cref="Thickness"/></returns>
public Thickness GetSumThickness ()
{
return new Thickness () {
Left = Padding.Left + BorderThickness.Left,
Top = Padding.Top + BorderThickness.Top,
Right = Padding.Right + BorderThickness.Right,
Bottom = Padding.Bottom + BorderThickness.Bottom
};
}
/// <summary>
/// Drawn the <see cref="BorderThickness"/> more the <see cref="Padding"/>
/// more the <see cref="Border.BorderStyle"/> and the <see cref="Effect3D"/>.
/// </summary>
/// <param name="view">The view to draw.</param>
/// <param name="fill">If it will clear or not the content area.</param>
public void DrawContent (View view = null, bool fill = true)
{
if (Child == null) {
Child = view;
}
if (Parent?.Border != null) {
DrawParentBorder (Parent.ViewToScreen (Parent.Bounds), fill);
} else {
DrawChildBorder (Child.ViewToScreen (Child.Bounds), fill);
}
}
/// <summary>
/// Same as <see cref="DrawContent"/> but drawing full frames for all borders.
/// </summary>
public void DrawFullContent ()
{
var borderThickness = BorderThickness;
var padding = Padding;
var marginFrame = DrawMarginFrame ? 1 : 0;
var driver = Application.Driver;
Rect scrRect;
if (Parent?.Border != null) {
scrRect = Parent.ViewToScreen (Parent.Bounds);
} else {
scrRect = Child.ViewToScreen (Child.Bounds);
}
Rect borderRect;
if (Parent?.Border != null) {
borderRect = scrRect;
} else {
borderRect = new Rect () {
X = scrRect.X - marginFrame - padding.Left - borderThickness.Left,
Y = scrRect.Y - marginFrame - padding.Top - borderThickness.Top,
Width = ActualWidth,
Height = ActualHeight
};
}
var savedAttribute = driver.GetAttribute ();
// Draw 3D effects
if (Effect3D) {
driver.SetAttribute (GetEffect3DBrush ());
var effectBorder = new Rect () {
X = borderRect.X + Effect3DOffset.X,
Y = borderRect.Y + Effect3DOffset.Y,
Width = ActualWidth,
Height = ActualHeight
};
//Child.Clear (effectBorder);
for (int r = effectBorder.Y; r < Math.Min (effectBorder.Bottom, driver.Rows); r++) {
for (int c = effectBorder.X; c < Math.Min (effectBorder.Right, driver.Cols); c++) {
AddRuneAt (driver, c, r, (Rune)driver.Contents [r, c, 0]);
}
}
}
// Draw border thickness
SetBorderBrush (driver);
Child.Clear (borderRect);
borderRect = new Rect () {
X = borderRect.X + borderThickness.Left,
Y = borderRect.Y + borderThickness.Top,
Width = Math.Max (borderRect.Width - borderThickness.Right - borderThickness.Left, 0),
Height = Math.Max (borderRect.Height - borderThickness.Bottom - borderThickness.Top, 0)
};
if (borderRect != scrRect) {
// Draw padding
driver.SetAttribute (new Attribute (Background));
Child.Clear (borderRect);
}
SetBorderBrushBackground (driver);
// Draw margin frame
if (DrawMarginFrame) {
if (Parent?.Border != null) {
var sumPadding = GetSumThickness ();
borderRect = new Rect () {
X = scrRect.X + sumPadding.Left,
Y = scrRect.Y + sumPadding.Top,
Width = Math.Max (scrRect.Width - sumPadding.Right - sumPadding.Left, 0),
Height = Math.Max (scrRect.Height - sumPadding.Bottom - sumPadding.Top, 0)
};
} else {
borderRect = new Rect () {
X = borderRect.X + padding.Left,
Y = borderRect.Y + padding.Top,
Width = Math.Max (borderRect.Width - padding.Right - padding.Left, 0),
Height = Math.Max (borderRect.Height - padding.Bottom - padding.Top, 0)
};
}
if (borderRect.Width > 0 && borderRect.Height > 0) {
driver.DrawWindowFrame (borderRect, 1, 1, 1, 1, BorderStyle != BorderStyle.None, fill: true, this);
}
}
driver.SetAttribute (savedAttribute);
}
private void DrawChildBorder (Rect frame, bool fill = true)
{
var drawMarginFrame = DrawMarginFrame ? 1 : 0;
var sumThickness = GetSumThickness ();
var padding = Padding;
var effect3DOffset = Effect3DOffset;
var driver = Application.Driver;
var savedAttribute = driver.GetAttribute ();
SetBorderBrush (driver);
// Draw the upper BorderThickness
for (int r = frame.Y - drawMarginFrame - sumThickness.Top;
r < frame.Y - drawMarginFrame - padding.Top; r++) {
for (int c = frame.X - drawMarginFrame - sumThickness.Left;
c < Math.Min (frame.Right + drawMarginFrame + sumThickness.Right, driver.Cols); c++) {
AddRuneAt (driver, c, r, ' ');
}
}
// Draw the left BorderThickness
for (int r = frame.Y - drawMarginFrame - padding.Top;
r < Math.Min (frame.Bottom + drawMarginFrame + padding.Bottom, driver.Rows); r++) {
for (int c = frame.X - drawMarginFrame - sumThickness.Left;
c < frame.X - drawMarginFrame - padding.Left; c++) {
AddRuneAt (driver, c, r, ' ');
}
}
// Draw the right BorderThickness
for (int r = frame.Y - drawMarginFrame - padding.Top;
r < Math.Min (frame.Bottom + drawMarginFrame + padding.Bottom, driver.Rows); r++) {
for (int c = frame.Right + drawMarginFrame + padding.Right;
c < Math.Min (frame.Right + drawMarginFrame + sumThickness.Right, driver.Cols); c++) {
AddRuneAt (driver, c, r, ' ');
}
}
// Draw the lower BorderThickness
for (int r = frame.Bottom + drawMarginFrame + padding.Bottom;
r < Math.Min (frame.Bottom + drawMarginFrame + sumThickness.Bottom, driver.Rows); r++) {
for (int c = frame.X - drawMarginFrame - sumThickness.Left;
c < Math.Min (frame.Right + drawMarginFrame + sumThickness.Right, driver.Cols); c++) {
AddRuneAt (driver, c, r, ' ');
}
}
SetBackground (driver);
// Draw the upper Padding
for (int r = frame.Y - drawMarginFrame - padding.Top;
r < frame.Y - drawMarginFrame; r++) {
for (int c = frame.X - drawMarginFrame - padding.Left;
c < Math.Min (frame.Right + drawMarginFrame + padding.Right, driver.Cols); c++) {
AddRuneAt (driver, c, r, ' ');
}
}
// Draw the left Padding
for (int r = frame.Y - drawMarginFrame;
r < Math.Min (frame.Bottom + drawMarginFrame, driver.Rows); r++) {
for (int c = frame.X - drawMarginFrame - padding.Left;
c < frame.X - drawMarginFrame; c++) {
AddRuneAt (driver, c, r, ' ');
}
}
// Draw the right Padding
for (int r = frame.Y - drawMarginFrame;
r < Math.Min (frame.Bottom + drawMarginFrame, driver.Rows); r++) {
for (int c = frame.Right + drawMarginFrame;
c < Math.Min (frame.Right + drawMarginFrame + padding.Right, driver.Cols); c++) {
AddRuneAt (driver, c, r, ' ');
}
}
// Draw the lower Padding
for (int r = frame.Bottom + drawMarginFrame;
r < Math.Min (frame.Bottom + drawMarginFrame + padding.Bottom, driver.Rows); r++) {
for (int c = frame.X - drawMarginFrame - padding.Left;
c < Math.Min (frame.Right + drawMarginFrame + padding.Right, driver.Cols); c++) {
AddRuneAt (driver, c, r, ' ');
}
}
SetBorderBrushBackground (driver);
// Draw the MarginFrame
if (DrawMarginFrame) {
var rect = new Rect () {
X = frame.X - drawMarginFrame,
Y = frame.Y - drawMarginFrame,
Width = frame.Width + (2 * drawMarginFrame),
Height = frame.Height + (2 * drawMarginFrame)
};
if (rect.Width > 0 && rect.Height > 0) {
driver.DrawWindowFrame (rect, 1, 1, 1, 1, BorderStyle != BorderStyle.None, fill, this);
DrawTitle (Child);
}
}
if (Effect3D) {
driver.SetAttribute (GetEffect3DBrush ());
// Draw the upper Effect3D
for (int r = frame.Y - drawMarginFrame - sumThickness.Top + effect3DOffset.Y;
r >= 0 && r < frame.Y - drawMarginFrame - sumThickness.Top; r++) {
for (int c = frame.X - drawMarginFrame - sumThickness.Left + effect3DOffset.X;
c >= 0 && c < Math.Min (frame.Right + drawMarginFrame + sumThickness.Right + effect3DOffset.X, driver.Cols); c++) {
AddRuneAt (driver, c, r, (Rune)driver.Contents [r, c, 0]);
}
}
// Draw the left Effect3D
for (int r = frame.Y - drawMarginFrame - sumThickness.Top + effect3DOffset.Y;
r >= 0 && r < Math.Min (frame.Bottom + drawMarginFrame + sumThickness.Bottom + effect3DOffset.Y, driver.Rows); r++) {
for (int c = frame.X - drawMarginFrame - sumThickness.Left + effect3DOffset.X;
c >= 0 && c < frame.X - drawMarginFrame - sumThickness.Left; c++) {
AddRuneAt (driver, c, r, (Rune)driver.Contents [r, c, 0]);
}
}
// Draw the right Effect3D
for (int r = frame.Y - drawMarginFrame - sumThickness.Top + effect3DOffset.Y;
r >= 0 && r < Math.Min (frame.Bottom + drawMarginFrame + sumThickness.Bottom + effect3DOffset.Y, driver.Rows); r++) {
for (int c = frame.Right + drawMarginFrame + sumThickness.Right;
c >= 0 && c < Math.Min (frame.Right + drawMarginFrame + sumThickness.Right + effect3DOffset.X, driver.Cols); c++) {
AddRuneAt (driver, c, r, (Rune)driver.Contents [r, c, 0]);
}
}
// Draw the lower Effect3D
for (int r = frame.Bottom + drawMarginFrame + sumThickness.Bottom;
r >= 0 && r < Math.Min (frame.Bottom + drawMarginFrame + sumThickness.Bottom + effect3DOffset.Y, driver.Rows); r++) {
for (int c = frame.X - drawMarginFrame - sumThickness.Left + effect3DOffset.X;
c >= 0 && c < Math.Min (frame.Right + drawMarginFrame + sumThickness.Right + effect3DOffset.X, driver.Cols); c++) {
AddRuneAt (driver, c, r, (Rune)driver.Contents [r, c, 0]);
}
}
}
driver.SetAttribute (savedAttribute);
}
private void DrawParentBorder (Rect frame, bool fill = true)
{
var sumThickness = GetSumThickness ();
var borderThickness = BorderThickness;
var effect3DOffset = Effect3DOffset;
var driver = Application.Driver;
var savedAttribute = driver.GetAttribute ();
SetBorderBrush (driver);
// Draw the upper BorderThickness
for (int r = Math.Max (frame.Y, 0);
r < Math.Min (frame.Y + borderThickness.Top, frame.Bottom); r++) {
for (int c = frame.X;
c < Math.Min (frame.Right, driver.Cols); c++) {
AddRuneAt (driver, c, r, ' ');
}
}
// Draw the left BorderThickness
for (int r = Math.Max (Math.Min (frame.Y + borderThickness.Top, frame.Bottom), 0);
r < Math.Min (frame.Bottom - borderThickness.Bottom, driver.Rows); r++) {
for (int c = frame.X;
c < Math.Min (frame.X + borderThickness.Left, frame.Right); c++) {
AddRuneAt (driver, c, r, ' ');
}
}
// Draw the right BorderThickness
for (int r = Math.Max (Math.Min (frame.Y + borderThickness.Top, frame.Bottom), 0);
r < Math.Min (frame.Bottom - borderThickness.Bottom, driver.Rows); r++) {
for (int c = Math.Max (frame.Right - borderThickness.Right, frame.X);
c < Math.Min (frame.Right, driver.Cols); c++) {
AddRuneAt (driver, c, r, ' ');
}
}
// Draw the lower BorderThickness
for (int r = Math.Max (frame.Bottom - borderThickness.Bottom, frame.Y);
r < Math.Min (frame.Bottom, driver.Rows); r++) {
for (int c = frame.X;
c < Math.Min (frame.Right, driver.Cols); c++) {
AddRuneAt (driver, c, r, ' ');
}
}
SetBackground (driver);
// Draw the upper Padding
for (int r = Math.Max (frame.Y + borderThickness.Top, 0);
r < Math.Min (frame.Y + sumThickness.Top, frame.Bottom - borderThickness.Bottom); r++) {
for (int c = frame.X + borderThickness.Left;
c < Math.Min (frame.Right - borderThickness.Right, driver.Cols); c++) {
AddRuneAt (driver, c, r, ' ');
}
}
// Draw the left Padding
for (int r = Math.Max (frame.Y + sumThickness.Top, 0);
r < Math.Min (frame.Bottom - sumThickness.Bottom, driver.Rows); r++) {
for (int c = frame.X + borderThickness.Left;
c < Math.Min (frame.X + sumThickness.Left, frame.Right - borderThickness.Right); c++) {
AddRuneAt (driver, c, r, ' ');
}
}
// Draw the right Padding
for (int r = Math.Max (frame.Y + sumThickness.Top, 0);
r < Math.Min (frame.Bottom - sumThickness.Bottom, driver.Rows); r++) {
for (int c = Math.Max (frame.Right - sumThickness.Right, frame.X + sumThickness.Left);
c < Math.Max (frame.Right - borderThickness.Right, frame.X + sumThickness.Left); c++) {
AddRuneAt (driver, c, r, ' ');
}
}
// Draw the lower Padding
for (int r = Math.Max (frame.Bottom - sumThickness.Bottom, frame.Y + borderThickness.Top);
r < Math.Min (frame.Bottom - borderThickness.Bottom, driver.Rows); r++) {
for (int c = frame.X + borderThickness.Left;
c < Math.Min (frame.Right - borderThickness.Right, driver.Cols); c++) {
AddRuneAt (driver, c, r, ' ');
}
}
SetBorderBrushBackground (driver);
// Draw the MarginFrame
if (DrawMarginFrame) {
var rect = new Rect () {
X = frame.X + sumThickness.Left,
Y = frame.Y + sumThickness.Top,
Width = Math.Max (frame.Width - sumThickness.Right - sumThickness.Left, 0),
Height = Math.Max (frame.Height - sumThickness.Bottom - sumThickness.Top, 0)
};
if (rect.Width > 0 && rect.Height > 0) {
driver.DrawWindowFrame (rect, 1, 1, 1, 1, BorderStyle != BorderStyle.None, fill, this);
DrawTitle (Parent);
}
}
if (Effect3D) {
driver.SetAttribute (GetEffect3DBrush ());
// Draw the upper Effect3D
for (int r = Math.Max (frame.Y + effect3DOffset.Y, 0);
r < frame.Y; r++) {
for (int c = Math.Max (frame.X + effect3DOffset.X, 0);
c < Math.Min (frame.Right + effect3DOffset.X, driver.Cols); c++) {
AddRuneAt (driver, c, r, (Rune)driver.Contents [r, c, 0]);
}
}
// Draw the left Effect3D
for (int r = Math.Max (frame.Y + effect3DOffset.Y, 0);
r < Math.Min (frame.Bottom + effect3DOffset.Y, driver.Rows); r++) {
for (int c = Math.Max (frame.X + effect3DOffset.X, 0);
c < frame.X; c++) {
AddRuneAt (driver, c, r, (Rune)driver.Contents [r, c, 0]);
}
}
// Draw the right Effect3D
for (int r = Math.Max (frame.Y + effect3DOffset.Y, 0);
r < Math.Min (frame.Bottom + effect3DOffset.Y, driver.Rows); r++) {
for (int c = frame.Right;
c < Math.Min (frame.Right + effect3DOffset.X, driver.Cols); c++) {
AddRuneAt (driver, c, r, (Rune)driver.Contents [r, c, 0]);
}
}
// Draw the lower Effect3D
for (int r = frame.Bottom;
r < Math.Min (frame.Bottom + effect3DOffset.Y, driver.Rows); r++) {
for (int c = Math.Max (frame.X + effect3DOffset.X, 0);
c < Math.Min (frame.Right + effect3DOffset.X, driver.Cols); c++) {
AddRuneAt (driver, c, r, (Rune)driver.Contents [r, c, 0]);
}
}
}
driver.SetAttribute (savedAttribute);
}
private void SetBorderBrushBackground (ConsoleDriver driver)
{
if (borderBrush != null && background != null) {
driver.SetAttribute (new Attribute (BorderBrush, Background));
} else if (borderBrush != null && background == null) {
driver.SetAttribute (new Attribute (BorderBrush, Parent.ColorScheme.Normal.Background));
} else if (borderBrush == null && background != null) {
driver.SetAttribute (new Attribute (Parent.ColorScheme.Normal.Foreground, Background));
} else {
driver.SetAttribute (Parent.ColorScheme.Normal);
}
}
private void SetBackground (ConsoleDriver driver)
{
if (background != null) {
driver.SetAttribute (new Attribute (Background));
} else {
driver.SetAttribute (new Attribute (Parent.ColorScheme.Normal.Background));
}
}
private void SetBorderBrush (ConsoleDriver driver)
{
if (borderBrush != null) {
driver.SetAttribute (new Attribute (BorderBrush));
} else {
driver.SetAttribute (new Attribute (Parent.ColorScheme.Normal.Foreground));
}
}
private Attribute GetEffect3DBrush ()
{
return Effect3DBrush == null
? new Attribute (Color.Gray, Color.DarkGray)
: (Attribute)Effect3DBrush;
}
private void AddRuneAt (ConsoleDriver driver, int col, int row, Rune ch)
{
if (col < driver.Cols && row < driver.Rows && col > 0 && driver.Contents [row, col, 2] == 0
&& Rune.ColumnWidth ((char)driver.Contents [row, col - 1, 0]) > 1) {
driver.Contents [row, col, 1] = driver.GetAttribute ();
return;
}
driver.Move (col, row);
driver.AddRune (ch);
}
/// <summary>
/// Draws the view <see cref="Title"/> to the screen.
/// </summary>
/// <param name="view">The view.</param>
public void DrawTitle (View view)
{
var driver = Application.Driver;
if (DrawMarginFrame) {
SetBorderBrushBackground (driver);
SetHotNormalBackground (view, driver);
var padding = view.Border.GetSumThickness ();
Rect scrRect;
if (view == Child) {
scrRect = view.ViewToScreen (new Rect (0, 0, view.Frame.Width + 2, view.Frame.Height + 2));
scrRect = new Rect (scrRect.X - 1, scrRect.Y - 1, scrRect.Width, scrRect.Height);
driver.DrawWindowTitle (scrRect, Title, 0, 0, 0, 0);
} else {
scrRect = view.ViewToScreen (new Rect (0, 0, view.Frame.Width, view.Frame.Height));
driver.DrawWindowTitle (scrRect, Parent.Border.Title,
padding.Left, padding.Top, padding.Right, padding.Bottom);
}
}
driver.SetAttribute (Child.GetNormalColor ());
}
private void SetHotNormalBackground (View view, ConsoleDriver driver)
{
if (view.HasFocus) {
if (background != null) {
driver.SetAttribute (new Attribute (Child.ColorScheme.HotNormal.Foreground, Background));
} else {
driver.SetAttribute (Child.ColorScheme.HotNormal);
}
}
}
/// <summary>
/// Draws the <see cref="View.Text"/> to the screen.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="rect">The frame.</param>
public void DrawTitle (View view, Rect rect)
{
var driver = Application.Driver;
if (DrawMarginFrame) {
SetBorderBrushBackground (driver);
SetHotNormalBackground (view, driver);
var padding = Parent.Border.GetSumThickness ();
var scrRect = Parent.ViewToScreen (new Rect (0, 0, rect.Width, rect.Height));
driver.DrawWindowTitle (scrRect, view.Text,
padding.Left, padding.Top, padding.Right, padding.Bottom);
}
driver.SetAttribute (view.GetNormalColor ());
}
/// <summary>
/// Invoke the <see cref="BorderChanged"/> event.
/// </summary>
public virtual void OnBorderChanged ()
{
BorderChanged?.Invoke (this);
}
}
}
|
using System;
using System.Threading.Tasks;
using HealthVaultMobileSample.UWP.Helpers;
using Microsoft.HealthVault.Clients;
using Microsoft.HealthVault.Connection;
using Microsoft.HealthVault.Record;
using Windows.UI.Core;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238
namespace HealthVaultMobileSample.UWP.Views.Navigation
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class HubPage : HealthVaultBasePage
{
private IHealthVaultConnection _connection;
public string ImageSource { get; private set; }
public string PersonName { get; set; }
public HubPage()
{
InitializeComponent();
}
public override async Task Initialize(NavigationParams navParams)
{
_connection = navParams.Connection;
HealthRecordInfo recordInfo = (await _connection.GetPersonInfoAsync()).SelectedRecord;
IThingClient thingClient = _connection.CreateThingClient();
//Set person name for UX
PersonName = recordInfo.Name;
OnPropertyChanged("PersonName");
//Configure navigation frame for the app
ContentFrame.Navigated += ContentFrame_Navigated;
SystemNavigationManager.GetForCurrentView().BackRequested += HubPage_BackRequested;
ContentFrame.Navigate(typeof(NavigationPage), new NavigationParams() { Connection = _connection });
}
#region Navigation
private void HubPage_BackRequested(object sender, BackRequestedEventArgs e)
{
if (ContentFrame.CanGoBack)
{
e.Handled = true;
ContentFrame.GoBack();
}
}
private void ContentFrame_Navigated(object sender, NavigationEventArgs e)
{
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
ContentFrame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;
}
#endregion
private void Home_Tapped(object sender, TappedRoutedEventArgs e)
{
ContentFrame.Navigate(typeof(NavigationPage), new NavigationParams() { Connection = _connection });
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chapter04_01
{
class Program
{
static void Main(string[] args)
{
string tmpStr1 = "15";
int tmpInt1 = Convert.ToInt32(tmpStr1);
Console.WriteLine("str1 :{0}", tmpStr1);
string tmpStr2 = "AAA";
//int tmpInt2 = Convert.ToInt32(tmpStr2);
int tmpInt2;
try
{
tmpInt2 = Convert.ToInt32(tmpStr2);
}catch(FormatException e)
{
tmpInt2 = 0;
//Console.WriteLine(e.ToString());
}
Console.WriteLine("str2 :{0}", tmpInt2);
int i;
string[] tmpStrs = { "12", "23", "ABC", "0" };
try
{
for (i = 0; i < 6; i++)
{
try
{
int tmpInt = Convert.ToInt32(tmpStrs[i]);
Console.WriteLine("Num{0} : {1}", i, 100 / tmpInt);
}
catch (FormatException e)
{
Console.WriteLine("Num{0} : {1}", i, "Convert Error");
}
catch (DivideByZeroException)
{
Console.WriteLine("Num{0} : {1}", i, "Divide By Zero");
}
catch (Exception)
{
Console.WriteLine("Unknown Error!");
}
}
}
catch
{
Console.WriteLine("Error!");
}
CVector tmpVec = new CVector(1, 2);
tmpVec[0] = 3;
tmpVec[1] = 4;
Console.WriteLine("Vec:{0}, {1}", tmpVec[0], tmpVec[1]);
try
{
tmpVec[2] = 7;
Console.WriteLine("Vec:{0}, {1}", tmpVec[0], tmpVec[1]);
}
catch
{
Console.WriteLine("Vec:Error");
}
finally
{
Console.WriteLine("finally");
}
Console.ReadKey();
}
}
}
|
using System;
using System.Dynamic;
using System.IO;
class CopyBinaryFile
{
static void Main()
{
FileStream fsRead = new FileStream(@"../../test.JPG", FileMode.Open);
FileStream fsWrite = new FileStream(@"../../test_copy.JPG", FileMode.Create);
using (fsRead)
{
using (fsWrite)
{
byte[] buffer = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = fsRead.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
break;
}
else
{
fsWrite.Write(buffer, 0, bytesRead);
}
}
}
}
}
} |
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace Shipwreck.TypeScriptModels.Declarations
{
// 8.4.2
public sealed class MethodDeclaration : FunctionDeclarationBase, IClassMember, IInterfaceMember, ICallSignature
{
/// <summary>
/// Gets or sets the value representing the accessibility modifier of the method.
/// </summary>
[DefaultValue(AccessibilityModifier.None)]
public AccessibilityModifier Accessibility { get; set; }
/// <summary>
/// Gets or sets the value indicating whether the method has a <c>static</c> modifier.
/// </summary>
[DefaultValue(false)]
public bool IsStatic { get; set; }
/// <summary>
/// Gets or sets the value indicating whether the method has a <c>async</c> modifier.
/// </summary>
[DefaultValue(false)]
public bool IsAsync { get; set; }
/// <summary>
/// Gets or sets the value indicating whether the method has a <c>abstract</c> modifier.
/// </summary>
[DefaultValue(false)]
public bool IsAbstract { get; set; }
/// <summary>
/// Gets or sets the binding identifier of this method.
/// </summary>
[DefaultValue(null)]
public string MethodName { get; set; }
#region Decorators
private Collection<Decorator> _Decorators;
/// <summary>
/// Gets a value indicating whether the value of <see cref="Decorators" /> contains any element;
/// </summary>
public bool HasDecorator
=> _Decorators?.Count > 0;
/// <summary>
/// Gets or sets the all decorators of the method.
/// </summary>
public Collection<Decorator> Decorators
{
get
{
return CollectionHelper.GetOrCreate(ref _Decorators);
}
set
{
CollectionHelper.Set(ref _Decorators, value);
}
}
/// <summary>
/// Determines a value indicating whether the value of <see cref="Decorators" /> needs to be persisted.
/// </summary>
/// <returns><c>true</c> if the property should be persisted; otherwise, <c>false</c>.</returns>
public bool ShouldSerializeDecorators()
=> HasDecorator;
/// <summary>
/// Resets the value for <see cref="Decorators" /> of the method to the default value.
/// </summary>
public void ResetDecorators()
=> _Decorators?.Clear();
#endregion Decorators
public void Accept<T>(IClassMemberVisitor<T> visitor)
=> visitor.VisitMethod(this);
public void Accept<T>(IInterfaceMemberVisitor<T> visitor)
=> visitor.VisitMethod(this);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DA
{
public class GetInformation
{
public IQueryable<Posts> GetPosts { get; set; }
public IQueryable<Pages> GetPages { get; set; }
public IQueryable<Categories> GetCateGories { get; set; }
public IQueryable<Tags> GetTags { get; set; }
public Posts NewsPosts { get; set; }
}
}
|
using SGCFT.Dominio.Entidades;
namespace SGCFT.Dominio.Contratos.Repositorios
{
public interface IUsuarioRepositorio
{
bool ValidarEmailCadastrado(string email);
bool ValidarDocumentoCadastrado(long documento, bool isCpf);
void Inserir(Usuario usuario);
void Alterar(Usuario usuario);
int ObterIdUsuarioPorEmail(string email);
}
}
|
namespace Fingo.Auth.Domain.CustomData.ConfigurationClasses.Project
{
public class NumberProjectConfiguration : ProjectConfiguration
{
public int Default { get; set; }
public int LowerBound { get; set; }
public int UpperBound { get; set; }
}
} |
using Quokka.RISCV.Integration.DTO;
using Quokka.RISCV.Integration.RuleHandlers;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Quokka.RISCV.Integration.Engine
{
public class Toolchain : IDisposable
{
Guid _correlationId;
public string RootPath { get; private set; }
private List<RuleHandler> _rules = new List<RuleHandler>();
public Toolchain(Guid correlationId)
{
Console.WriteLine($"======================================================");
Console.WriteLine($"Toolchain request {correlationId}");
_correlationId = correlationId;
RootPath = Path.Combine(Path.GetTempPath(), _correlationId.ToString());
Directory.CreateDirectory(RootPath);
}
public void SaveSnapshot(FSSnapshot fsSnashot)
{
new FSManager(RootPath).SaveSnapshot(fsSnashot);
}
public FSSnapshot LoadSnapshot(ExtensionClasses classes)
{
return new FSManager(RootPath)
.LoadSnapshot(
classes,
_rules
.SelectMany(r => r.MatchingFiles())
.ToHashSet());
}
public void SetupRules(IEnumerable<FileRule> rules)
{
DisposeRules();
_rules = new RulesManager(RootPath).CreateRules(rules);
}
public void Invoke(IEnumerable<ToolchainOperation> operations)
{
var current = Directory.GetCurrentDirectory();
try
{
Directory.SetCurrentDirectory(RootPath);
foreach (var cmd in operations)
{
switch (cmd)
{
case CommandLineInfo commandLine:
{
Console.WriteLine($"Running {commandLine.Arguments}");
var psi = new ProcessStartInfo()
{
FileName = commandLine.FileName,
Arguments = commandLine.Arguments,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
var process = new Process()
{
StartInfo = psi
};
process.Start();
string result = process.StandardOutput.ReadToEnd();
string errors = process.StandardError.ReadToEnd();
process.WaitForExit();
Console.WriteLine($"Completed with {process.ExitCode}");
Console.WriteLine($"Stdout: {result}");
Console.WriteLine($"Stderror {errors}");
if (process.ExitCode != 0)
throw new Exception(errors);
} break;
case ResetRules rst:
{
_rules.ForEach(r => r.Reset());
} break;
}
}
}
finally
{
Directory.SetCurrentDirectory(current);
}
}
#region IDisposable Support
void DisposeRules()
{
if (_rules != null)
{
_rules.ForEach(r => r.Dispose());
}
_rules = null;
}
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
DisposeRules();
Directory.Delete(RootPath, true);
}
disposedValue = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
Dispose(true);
}
#endregion
public static InvokeResponse Invoke(InvokeRequest request)
{
var response = new InvokeResponse()
{
CorrelationId = request.CorrelationId
};
using (var toolchain = new Toolchain(request.CorrelationId))
{
toolchain.SaveSnapshot(request.Source);
toolchain.SetupRules(request.ResultRules);
toolchain.Invoke(request.Operations);
response.Result = toolchain.LoadSnapshot(request.ExtensionClasses);
}
return response;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using FXB.Data;
using FXB.DataManager;
using FXB.Common;
namespace FXB.DataManager
{
class HYMgr
{
private static HYMgr ins;
private SortedDictionary<Int64, HYData> allHYData;
public SortedDictionary<Int64, HYData> AllHYData
{
get { return allHYData; }
}
private HYMgr()
{
allHYData = new SortedDictionary<Int64, HYData>();
}
public static HYMgr Instance()
{
if (ins == null)
{
ins = new HYMgr();
}
return ins;
}
public void Init()
{
//将回佣数据添加到订单引用
foreach (var item in allHYData)
{
HYData data = item.Value;
QtOrder order = OrderMgr.Instance().AllOrderData[data.OrderId];
order.AllHYData[item.Key] = data;
}
}
public HYData AddNewHY(Int64 orderId, double amount, UInt32 addTime, string entryJobNumber, double shouxufei, double shuifei)
{
if (!OrderMgr.Instance().AllOrderData.ContainsKey(orderId))
{
throw new ConditionCheckException(string.Format("订单id[{0}]不存在", orderId));
}
QtOrder order = OrderMgr.Instance().AllOrderData[orderId];
if (amount > order.CommissionAmount)
{
throw new ConditionCheckException(string.Format("回佣金额[{0}]大于佣金总额[{1}]", amount, order.CommissionAmount));
}
double totoalHy = amount;
foreach (var item in order.AllHYData)
{
HYData hyData = item.Value;
totoalHy += hyData.Amount;
}
if (totoalHy > order.CommissionAmount)
{
throw new ConditionCheckException(string.Format("回佣金额[{0}]累加起来,大于佣金总额[{1}]", totoalHy, order.CommissionAmount));
}
if (!order.CheckState)
{
//订单未审核不能添加回佣
throw new ConditionCheckException(string.Format("订单id[{0}]未审核不能添加回佣", orderId));
}
//HY的时间就不审核了
SqlCommand command = new SqlCommand();
command.Connection = SqlMgr.Instance().SqlConnect;
command.CommandType = CommandType.Text;
command.CommandText = @"INSERT INTO qtorderhy(
orderid,
amount,
addtime,
entryjobnumber,
shouxufei,
shuifei,
checkstate,
checkjobnumber,
checktime) output inserted.Id VALUES(
@orderid,
@amount,
@addtime,
@entryjobnumber,
@shouxufei,
@shuifei,
@checkstate,
@checkjobnumber,
@checktime);select @@identity";
command.Parameters.AddWithValue("@orderid", orderId);
command.Parameters.AddWithValue("@amount", amount);
command.Parameters.AddWithValue("@addtime", (Int32)addTime);
command.Parameters.AddWithValue("@entryjobnumber", entryJobNumber);
command.Parameters.AddWithValue("@shouxufei", shouxufei);
command.Parameters.AddWithValue("@shuifei", shuifei);
command.Parameters.AddWithValue("@checkstate", false);
command.Parameters.AddWithValue("@checkjobnumber", "");
command.Parameters.AddWithValue("@checktime", (Int32)0);
Int64 hyId = (Int64)command.ExecuteScalar();
HYData newHyData = new HYData(hyId, orderId, amount, addTime, entryJobNumber, shouxufei, shuifei, false, "", 0);
allHYData[hyId] = newHyData;
order.AllHYData[hyId] = newHyData;
return newHyData;
}
public void UpdateAmount(Int64 hyId, double amount, double shouxufei, double shuifei, UInt32 newTime)
{
if (!allHYData.ContainsKey(hyId))
{
throw new ConditionCheckException(string.Format("回佣id[{0}]不存在", hyId));
}
HYData hyData = allHYData[hyId];
if (hyData.CheckState)
{
//订单未审核不能添加回佣
throw new ConditionCheckException(string.Format("回佣[{0}]已经审核不能修改", hyId));
}
QtOrder order = OrderMgr.Instance().AllOrderData[hyData.OrderId];
double totoalHy = 0;
foreach (var item in order.AllHYData)
{
if (item.Key == hyId)
{
totoalHy += amount;
}
else
{
HYData tmpData = item.Value;
totoalHy += tmpData.Amount;
}
}
if (totoalHy > order.CommissionAmount)
{
throw new ConditionCheckException(string.Format("回佣金额[{0}]累加起来,大于佣金总额[{1}]", totoalHy, order.CommissionAmount));
}
EmployeeData curEmployeeData = AuthMgr.Instance().CurLoginEmployee;
SqlCommand command = new SqlCommand();
command.Connection = SqlMgr.Instance().SqlConnect;
command.CommandType = CommandType.Text;
command.CommandText = @"update qtorderhy set
entryjobnumber=@entryjobnumber,
amount=@amount,
shouxufei=@shouxufei,
shuifei=@shuifei where id=@id";
command.Parameters.AddWithValue("@entryjobnumber", curEmployeeData.JobNumber);
command.Parameters.AddWithValue("@amount", amount);
command.Parameters.AddWithValue("@addtime", (Int32)newTime);
command.Parameters.AddWithValue("@shouxufei", shouxufei);
command.Parameters.AddWithValue("@shuifei", shuifei);
command.Parameters.AddWithValue("@id", hyId);
command.ExecuteNonQuery();
hyData.Amount = amount;
hyData.Shouxufei = shouxufei;
hyData.Shuifei = shuifei;
hyData.EntryJobNumber = curEmployeeData.JobNumber;
hyData.AddTime = newTime;
}
public void UpdateCheckState(Int64 hyId, bool checkState, string checkjobnumber, UInt32 checktime)
{
if (!allHYData.ContainsKey(hyId))
{
throw new ConditionCheckException(string.Format("回佣id[{0}]不存在", hyId));
}
HYData hyData = allHYData[hyId];
//检测回佣对应的工资是否结算,结算了则不能修改
//if (hyData.IsSettlement)
//{
// throw new ConditionCheckException(string.Format("回佣id[{0}]已经结算不能变更审核状态", hyId));
//}
SqlCommand command = new SqlCommand();
command.Connection = SqlMgr.Instance().SqlConnect;
command.CommandType = CommandType.Text;
command.CommandText = @"update qtorderhy set
checkstate=@checkstate,
checkjobnumber=@checkjobnumber,
checktime=@checktime where id=@id";
command.Parameters.AddWithValue("@checkstate", checkState);
command.Parameters.AddWithValue("@checkjobnumber", checkjobnumber);
command.Parameters.AddWithValue("@checktime", (Int32)checktime);
command.Parameters.AddWithValue("@id", hyId);
command.ExecuteNonQuery();
hyData.CheckState = checkState;
hyData.CheckJobNumber = checkjobnumber;
hyData.CheckTime = checktime;
}
public void RemoveHY(Int64 hyId)
{
if (!allHYData.ContainsKey(hyId))
{
throw new ConditionCheckException(string.Format("回佣id[{0}]不存在", hyId));
}
//检测回佣对应的工资是否结算,结算了则不能删除
//if (hyData.IsSettlement)
//{
// throw new ConditionCheckException(string.Format("回佣id[{0}]已经结算不能变更审核状态", hyId));
//}
HYData hyData = allHYData[hyId];
if (hyData.CheckState)
{
throw new ConditionCheckException(string.Format("回佣id[{0}]已经审核不能删除", hyId));
}
QtOrder order = OrderMgr.Instance().AllOrderData[hyData.OrderId];
SqlCommand command = new SqlCommand();
command.Connection = SqlMgr.Instance().SqlConnect;
command.CommandType = CommandType.Text;
command.CommandText = "delete from qtorderhy where id=@id";
command.Parameters.AddWithValue("@id", hyId);
command.ExecuteScalar();
order.AllHYData.Remove(hyId);
allHYData.Remove(hyId);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using PluginDevelopment.Helper;
using PluginDevelopment.Helper.Dapper.NET;
using PluginDevelopment.Model;
namespace PluginDevelopment.DAL.DapperDal
{
public class DapperMethod
{
private static readonly DbBase Dbbase = new DbBase("DefaultConnectionString");
/// <summary>
/// 查询数据
/// </summary>
public static void MappingOne()
{
string sqlStr = "select a.ID from textedit a where Id=@Id";
string id = "732ef249-f8b2-11e6-a5a1-0021cc65b235";
using (var conDbconnection = Dbbase.DbConnecttion)
{
var editsa = conDbconnection.Query<TextEdit>(sqlStr, new { Id = id });
}
}
/// <summary>
/// 一对一映射
/// </summary>
public static void MappingDouble()
{
//string sqlStr = "select a.id,a.name,a.oper,b.id,b.category,b.entrycontent from messageinfo a,textedit b where a.id=b.id and a.id=@Id";
string sqlStr = "select a.Id,b.category,b.entryContent, b.TextId from messageinfo a join textedit b on a.TextId=b.TextId";
using (var conDbconnection = Dbbase.DbConnecttion)
{
List<Message> ed = conDbconnection.Query<Message, TextEdit, Message>(sqlStr, (message, messageinfo) =>
{
message.TextEdit = messageinfo;
return message;
},null,null,false, "TextId").ToList<Message>();
}
}
/// <summary>
/// 一对多映射
/// </summary>
public static void MappingMany()
{
}
/// <summary>
/// 插入数据
/// </summary>
public static void MappingInsert()
{
TextEdit textEdit = new TextEdit()
{
TextId = "e0d405a5-fa3a-11e6-a5a1-0021cc65b235",
Category = "等级1"
};
string sqlStr = "insert into textedit(ID,category) values(@Id,@Category)";
using (var conDbconnection = Dbbase.DbConnecttion)
{
int row = conDbconnection.Execute(sqlStr, textEdit);
}
}
/// <summary>
/// 更新数据
/// </summary>
public static void MapperingUpdate()
{
TextEdit textEdit = new TextEdit()
{
TextId = "e0d405a5-fa3a-11e6-a5a1-0021cc65b235",
Category = "等级2"
};
string sqlStr = "update textedit a set a.category=@Category where a.id=@Id";
using (var conDbconnection = Dbbase.DbConnecttion)
{
int row = conDbconnection.Execute(sqlStr, textEdit);
}
}
/// <summary>
/// 删除数据
/// </summary>
public static void MappingDelete()
{
TextEdit textEdit = new TextEdit()
{
TextId = "e0d405a5-fa3a-11e6-a5a1-0021cc65b235"
};
string sqlStr = "delete from textedit where id=@Id";
using (var conDbconnection = Dbbase.DbConnecttion)
{
int row = conDbconnection.Execute(sqlStr, textEdit);
}
}
/// <summary>
/// 使用事物
/// </summary>
public static void MappingTransaction()
{
string sqlStr = "update textedit a set a.category=@Category where a.id=@Id";
string strSql = "update messageinfo a set a.name=@Name where a.id=@Id";
TextEdit textEdit = new TextEdit()
{
TextId = "e0d405a5-fa3a-11e6-a5a1-0021cc65b235",
Category = "等级4"
};
MessageInfo message = new MessageInfo()
{
Id = "cee99d43-f9a9-11e6-a5a1-0021cc65b235",
Name = "测试1"
};
using (IDbConnection connection = Dbbase.DbConnecttion)
{
IDbTransaction transaction = connection.BeginTransaction();
try
{
int row = connection.Execute(sqlStr, textEdit, transaction);
int rows = connection.Execute(strSql,message, transaction);
transaction.Commit();
}
catch (Exception ex)
{
throw ex;
}
finally
{
transaction.Rollback();
}
}
}
}
}
|
namespace tenpay
{
using System;
using System.Collections;
using System.Text;
using System.Xml;
public class ClientResponseHandler
{
private string charset = "gb2312";
protected string content;
private string debugInfo;
private string key;
protected Hashtable parameters = new Hashtable();
public virtual bool _isTenpaySign(ArrayList akeys)
{
StringBuilder builder = new StringBuilder();
foreach (string str in akeys)
{
string strB = (string) this.parameters[str];
if ((((strB != null) && ("".CompareTo(strB) != 0)) && ("sign".CompareTo(str) != 0)) && ("key".CompareTo(str) != 0))
{
builder.Append(str + "=" + strB + "&");
}
}
builder.Append("key=" + this.getKey());
string str3 = MD5Util.GetMD5(builder.ToString(), this.getCharset()).ToLower();
this.setDebugInfo(builder.ToString() + " => sign:" + str3);
return this.getParameter("sign").ToLower().Equals(str3);
}
protected virtual string getCharset()
{
return this.charset;
}
public string getContent()
{
return this.content;
}
public string getDebugInfo()
{
return this.debugInfo;
}
public string getKey()
{
return this.key;
}
public string getParameter(string parameter)
{
string str = (string) this.parameters[parameter];
return ((str == null) ? "" : str);
}
public virtual bool isTenpaySign()
{
StringBuilder builder = new StringBuilder();
ArrayList list = new ArrayList(this.parameters.Keys);
list.Sort();
foreach (string str in list)
{
string strB = (string) this.parameters[str];
if ((((strB != null) && ("".CompareTo(strB) != 0)) && ("sign".CompareTo(str) != 0)) && ("key".CompareTo(str) != 0))
{
builder.Append(str + "=" + strB + "&");
}
}
builder.Append("key=" + this.getKey());
string str3 = MD5Util.GetMD5(builder.ToString(), this.getCharset()).ToLower();
this.setDebugInfo(builder.ToString() + " => sign:" + str3);
return this.getParameter("sign").ToLower().Equals(str3);
}
public void setCharset(string charset)
{
this.charset = charset;
}
public virtual void setContent(string content)
{
this.content = content;
XmlDocument document = new XmlDocument();
document.LoadXml(content);
XmlNodeList childNodes = document.SelectSingleNode("root").ChildNodes;
foreach (XmlNode node2 in childNodes)
{
this.setParameter(node2.Name, node2.InnerXml);
}
}
protected void setDebugInfo(string debugInfo)
{
this.debugInfo = debugInfo;
}
public void setKey(string key)
{
this.key = key;
}
public void setParameter(string parameter, string parameterValue)
{
if ((parameter != null) && (parameter != ""))
{
if (this.parameters.Contains(parameter))
{
this.parameters.Remove(parameter);
}
this.parameters.Add(parameter, parameterValue);
}
}
}
}
|
using System ;
using System.Collections.Generic;
using System.Linq ;
using System.Text;
using System.Xml.Serialization;
using KartObjects;
namespace KartExchangeEngine
{
[Serializable]
public class ФайлОбмена
{
[XmlAttribute]
public string КонечнаяДатаВыгрузки { get; set; }
[XmlAttribute]
public string НачальнаяДатаВыгрузки { get; set; }
[XmlAttribute]
public string Подразделение { get; set; }
[XmlAttribute]
public string КодПодразделения { get; set; }
[XmlAttribute]
public DateTime ДатаВыгрузки { get; set; }
[XmlElement]
public СписокДокументов СписокДокументов;
}
public class СписокДокументов
{
[XmlAttribute]
public int ВсегоДокументов { get; set; }
[XmlElement]
public List<Документ> Документ;
}
public class Документ
{
[XmlAttribute]
public string ДатаДокВнеш { get; set; }
[XmlAttribute]
public string НомерДокВнеш { get; set; }
[XmlAttribute]
public string ДатаДок { get; set; }
[XmlAttribute]
public string НомерДок { get; set; }
[XmlAttribute]
public string ТипДокСимв { get; set; }
[XmlAttribute]
public string ТипДок { get; set; }
[XmlElement]
public ЗаголовокДокумента ЗаголовокДокумента;
[XmlElement]
public ТоварныеПозиции ТоварныеПозиции;
}
public class ЗаголовокДокумента
{
public Отправитель Отправитель;
public Получатель Получатель;
public ИтогоПоДокументу ИтогоПоДокументу;
}
public class Отправитель
{
[XmlAttribute]
public string КодВыгрузки { get; set; }
[XmlAttribute]
public string КодАУ { get; set; }
[XmlAttribute]
public string Наименование { get; set; }
}
public class Получатель : Отправитель
{ }
public class ИтогоПоДокументу
{
[XmlAttribute]
public decimal СуммаРеализСкид { get; set; }
[XmlAttribute]
public decimal СуммаРеализ { get; set; }
[XmlAttribute]
public decimal СуммаРозн { get; set; }
[XmlAttribute]
public decimal СуммаОптВклНДС { get; set; }
[XmlAttribute]
public decimal СуммаОпт { get; set; }
}
public class ТоварныеПозиции
{
[XmlElement]
public List<ГруппаПозиций> ГруппаПозиций;
}
public class ГруппаПозиций
{
[XmlAttribute]
public decimal СуммаРеализСкид { get; set; }
[XmlAttribute]
public decimal СуммаРеализ { get; set; }
[XmlAttribute]
public decimal СуммаРозн { get; set; }
[XmlAttribute]
public decimal СуммаОптВклНДС { get; set; }
[XmlAttribute]
public decimal СуммаОпт { get; set; }
[XmlAttribute]
public decimal СтавкаНДС { get; set; }
}
} |
using System;
using System.IO;
using System.Threading;
using log4net;
namespace Cradiator.Config
{
public interface IConfigFileWatcher
{
void Start();
}
public class ConfigFileWatcher : IConfigFileWatcher
{
static readonly ILog _log = LogManager.GetLogger(typeof(ConfigFileWatcher).Name);
const long DelayInMilliseconds = 100;
readonly string _configFile;
readonly IConfigSettings _configSettings;
FileSystemWatcher _fileSystemWatcher;
Timer _timer;
public FileSystemWatcher FileSystemWatcher
{
get { return _fileSystemWatcher; }
}
public ConfigFileWatcher(IConfigSettings configSettings, string configFile)
{
_configSettings = configSettings;
_configFile = configFile;
}
public void Start()
{
_fileSystemWatcher = CreateFileSystemWatcher();
_fileSystemWatcher.EnableRaisingEvents = true;
}
FileSystemWatcher CreateFileSystemWatcher()
{
// Create the timer that will be used to deliver events. Set as disabled
_timer = new Timer(OnDelayedForBatching_ConfigFileChanged, null, Timeout.Infinite, Timeout.Infinite);
var watcher = new FileSystemWatcher
{
NotifyFilter = NotifyFilters.LastWrite,
Path = Path.GetDirectoryName(_configFile),
Filter = Path.GetFileName(_configFile)
};
watcher.Changed += OnConfigFileChanged;
return watcher;
}
void OnConfigFileChanged(object sender, FileSystemEventArgs e)
{
_timer.Change(DelayInMilliseconds, Timeout.Infinite);
}
void OnDelayedForBatching_ConfigFileChanged(object state)
{
try
{
_configSettings.Load();
_configSettings.NotifyObservers();
_configSettings.Log();
}
catch (Exception exception)
{
_log.Error(exception);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace StanbicIBTC.BotServices.Models
{
public class QuestionsBank
{
public int Id { get; set; }
public string Question { get; set; }
public bool? Answer { get; set; }
public bool? IsAnswer { get; set; }
public bool? IsPublished { get; set; }
public bool? Published { get; set; }
public DateTime DateCreated { get; set; }
public QuestionsBank()
{
DateCreated = DateTime.Now;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName ="Flock/Filter/Obsctacle")]
public class ObstacleFilter : ContextFilter
{
public LayerMask mask;
public override List<Transform> Filter(Boids boid, List<Transform> original)
{
List<Transform> filtered = new List<Transform>();
foreach (Transform element in original)
{
if(mask == (mask| (1 << element.gameObject.layer)))
{
filtered.Add(element);
}
}
return filtered;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General;
using Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Contractual;
using Pe.Stracon.SGC.Presentacion.Core.ViewModel.Base;
namespace Pe.Stracon.SGC.Presentacion.Core.ViewModel.Contractual.VariablePlantilla
{
/// <summary>
/// Modelo de vista Variable Plantilla Campo Formulario
/// </summary>
/// <remarks>
/// Creación: GMD 20150709
/// Modificación:
/// </remarks>
public class VariablePlantillaCampoFormulario : GenericViewModel
{
#region Propiedades
/// <summary>
/// Campos de Variable
/// </summary>
public VariableCampoResponse VariableCampo { get; set; }
/// <summary>
/// Lista de Tipos de Alineamiento
/// </summary>
public List<SelectListItem> TipoAlineamiento { get; set; }
#endregion
/// <summary>
/// Constructor de la Clase
/// </summary>
public VariablePlantillaCampoFormulario(string codigoVariable, List<CodigoValorResponse> listaTipoAlineamiento)
{
this.VariableCampo = new VariableCampoResponse();
if (codigoVariable != null && codigoVariable != "" && codigoVariable != "00000000-0000-0000-0000-000000000000")
{
this.VariableCampo.CodigoVariable = new Guid(codigoVariable);
}
this.TipoAlineamiento = this.GenerarListadoOpcioneGenericoFormulario(listaTipoAlineamiento);
}
/// <summary>
/// Constructor de la Clase
/// </summary>
public VariablePlantillaCampoFormulario(VariableCampoResponse variableCampoResponse, List<CodigoValorResponse> listaTipoAlineamiento)
{
this.VariableCampo = variableCampoResponse;
this.TipoAlineamiento = this.GenerarListadoOpcioneGenericoFormulario(listaTipoAlineamiento, variableCampoResponse.TipoAlineamiento);
}
}
}
|
using UnityEngine;
using System.Collections;
public class RandomizeBlockSpawn : MonoBehaviour {
public Transform spawnPoint;
public GameObject[] objectToSpawn;
public GameObject finalBlock;
public float TimeRemaining;
// Use this for initialization
void Start ()
{
SpawnTimer();
}
// Update is called once per frame
void Update ()
{
TimeRemaining -= Time.deltaTime;
if(TimeRemaining <= 0.1f)
{
Invoke("SpawnFinalBlock" ,0.09f);
}
if(TimeRemaining <= 0)
{
CancelInvoke();
}
}
void Spawn()
{
for(int i = 0; i < 1; i++)
{
GameObject obj = objectToSpawn[Random.Range(0, objectToSpawn.Length)];
Instantiate(obj, spawnPoint.transform.position, spawnPoint.rotation);
}
//Instantiate(finalBlock, spawnPoint.transform.position, spawnPoint.rotation);
}
void SpawnTimer()
{
InvokeRepeating("Spawn", 1f , 1f);
}
void SpawnFinalBlock()
{
Instantiate(finalBlock, spawnPoint.transform.position, spawnPoint.rotation);
}
}
|
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;
using CIPMSBC;
public partial class AwardNotificationReqest : System.Web.UI.Page
{
private CamperApplication _objCamperApplication = new CamperApplication();
private General _objGen = new General();
DataSet dsANReportCampers = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
tblReportDetails.Visible = grdANReport.Visible;
int cntOfRecordsinPreMode = _objCamperApplication.GetExistingCountOfANPremilinaryRecords(Application["CampYear"].ToString());
if (cntOfRecordsinPreMode > 0 && rdbtnlstMode.SelectedItem.Value != "1") rdbtnlstMode.SelectedItem.Value = "0";
if (cntOfRecordsinPreMode > 0 && ddlRecCount.Enabled)
{
lblMessage.Visible = true;
lblMessage.Text = "Note: There are already " + cntOfRecordsinPreMode.ToString() + " camper applications which are in premiliminary mode, untill these records are run in final mode you cannot change the no. of records you want to view";
ddlRecCount.Enabled = false;
}
else
{
lblMessage.Visible = false;
lblMessage.Text = "";
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string strMode = rdbtnlstMode.SelectedItem.Value;
lblMode.Text = strMode == "1" ? "Final" : "Prelimary";
// 2013-07-30 Seth asked to generate second time camper's list for survey purpose
string type = "";
if (rdoFirstTime.Checked)
type = "FirstTimer";
else
type = "SecondTimer";
if (strMode == "0") //Preliminary Mode
{
dsANReportCampers = GetAnReportCampers(ddlRecCount.SelectedValue, Application["CampYear"].ToString(), 0, type);
//grdANReport.DataSource = UpdateDays(dsANReportCampers.Tables[0]);//Wil calculate no. of days from startdate and enddate columns
grdANReport.DataSource = dsANReportCampers.Tables[0];
grdANReport.PageIndex = 0;
grdANReport.DataBind();
ddlRecCount.Enabled = false;
Session["ANReportID"] = "0";
}
else if (strMode == "1" && chkFinal.Checked)//Final Mode
{
dsANReportCampers = _objCamperApplication.RunFinalMode(Application["CampYear"].ToString(), type);
//grdANReport.DataSource = UpdateDays(dsANReportCampers.Tables[0]);//Wil calculate no. of days from startdate and enddate columns
grdANReport.DataSource = dsANReportCampers.Tables[0];
grdANReport.PageIndex = 0;
grdANReport.DataBind();
ddlRecCount.Enabled = true;
string strFolder = Request.MapPath(ConfigurationManager.AppSettings["AwardNotificationFolderPath"], Request.ApplicationPath, false);
string strANReportID = string.Empty;
if (dsANReportCampers.Tables[1].Rows.Count>0)
{
strANReportID = dsANReportCampers.Tables[1].Rows[0]["ANReportID"].ToString();
Session["ANReportID"] = String.IsNullOrEmpty(strANReportID) ? "0" : strANReportID;
}
if (Directory.Exists(strFolder))
{
ProcessFile(strFolder, strANReportID);
}
else
{
Directory.CreateDirectory(strFolder);
ProcessFile(strFolder, strANReportID);
}
}
lblNoOfRecords.Text = dsANReportCampers.Tables[0].Rows.Count.ToString();
int cntPreANRecords = _objCamperApplication.GetExistingCountOfANPremilinaryRecords(Application["CampYear"].ToString());
if (cntPreANRecords > 0 && strMode == "0" && ddlRecCount.Enabled)
{
lblMessage.Visible = true;
lblMessage.Text = "Note: There are already " + cntPreANRecords.ToString() + " camper applications which are in premiliminary mode, untill these records are run in final mode you cannot change the no. of records you want to view.";
ddlRecCount.Enabled = false;
}
else if (cntPreANRecords == 0 && strMode == "0")
{
lblMessage.Visible = true;
lblMessage.Text = "Note: There are no campers with payment request status, please try running the preliminary mode later.";
}
else if (cntPreANRecords == 0 && strMode == "1" && dsANReportCampers.Tables[0].Rows.Count<=0)
{
lblMessage.Visible = true;
lblMessage.Text = "Note: There are no records in preliminary mode, please run the report in preliminary mode by selecting the mode option provided above.";
}
if (pnlFinal.Visible) pnlFinal.Visible = false;
lblReqTime.Text = DateTime.Now.ToString();
tblReportDetails.Visible = grdANReport.Visible = true;
}
private DataSet GetAnReportCampers(string recordCount, string campyear, int ANReportID, string type)
{
return _objCamperApplication.usp_GetANReport(Int32.Parse(recordCount), campyear, ANReportID, type);
}
private DataTable UpdateDays(DataTable dt)
{
if (dt.Rows.Count > 0)
for (int i = 0; i < dt.Rows.Count; i++)
{
if (String.IsNullOrEmpty(dt.Rows[i]["Days"].ToString()))
{
string startDate = dt.Rows[i]["StartDate"].ToString();
string endDate = dt.Rows[i]["EndDate"].ToString();
if (String.IsNullOrEmpty(startDate) || String.IsNullOrEmpty(endDate))
dt.Rows[i]["Days"] = "0";
else
{
DateTime dtStartDate, dtEndDate;
TimeSpan ts = new TimeSpan();
dtStartDate = dtEndDate = DateTime.Now;
if (DateTime.TryParse(startDate, out dtStartDate) && DateTime.TryParse(endDate, out dtEndDate))
{
if (dtEndDate > dtStartDate)
{
ts = dtEndDate.Subtract(dtStartDate);
dt.Rows[i]["Days"] = (ts.Days + 1).ToString();
}
else
dt.Rows[i]["Days"] = "0";
}
}
}
}
return dt;
}
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
// 2013-07-30 Seth asked to generate second time camper's list for survey purpose
string type = "";
if (rdoFirstTime.Checked)
type = "FirstTimer";
else
type = "SecondTimer";
dsANReportCampers = GetAnReportCampers(ddlRecCount.SelectedValue, Application["CampYear"].ToString(), Int32.Parse(Session["ANReportID"].ToString()), type);
grdANReport.DataSource = UpdateDays(dsANReportCampers.Tables[0]);//Wil calculate no. of days from startdate and enddate columns
grdANReport.PageIndex = e.NewPageIndex;
grdANReport.DataBind();
if (rdbtnlstMode.SelectedItem.Value == "1" && dsANReportCampers.Tables[0].Rows.Count > 0)
{
if (Session["url"] != null)
{
string url = Session["url"].ToString();
lblMessage.Text = "Note: Award notification final mode was successful and txt file generated with camper details, please <a href='http://" + url + "' target='_blank'>click here</a> to download it";
lblMessage.Visible = true;
}
}
}
protected void rdbtnlstMode_SelectedIndexChanged(object sender, EventArgs e)
{
if (rdbtnlstMode.SelectedItem != null)
{
if (rdbtnlstMode.SelectedItem.Value == "1")
{ pnlFinal.Visible = true; if (chkFinal.Checked) chkFinal.Checked = false; }
else
pnlFinal.Visible = false;
tblReportDetails.Visible = grdANReport.Visible = false;
}
}
private void ProcessFile(string strFolderPath, string strANReportId)
{
string strFileName = string.Empty;
string strFilePath = string.Empty;
string strFileExtension = string.Empty;
string strGeneratedFileName = string.Empty;
try
{
strFileName = ConfigurationManager.AppSettings["AwardNotificationFileName"];
strFileExtension = ConfigurationManager.AppSettings["AwardNotificationFileExtension"];
strGeneratedFileName = DateTime.Now.Date.ToString("MMM-dd-yyyy") + "_" + strFileName + strFileExtension;
strFilePath = strFolderPath + strGeneratedFileName;
DataSet dsANFinalCamperNotificationList = new DataSet();
dsANFinalCamperNotificationList = _objCamperApplication.GetANFinalModeCampersOnReportID(Application["CampYear"].ToString(), strANReportId);
if (dsANFinalCamperNotificationList.Tables.Count > 0)
{
if (dsANFinalCamperNotificationList.Tables[0].Rows.Count > 0)
{
DataTable dtANFinalCamperNotificationList = dsANFinalCamperNotificationList.Tables[0];
//DataTable dtANFinalCamperNotificationList = UpdateDays(dsANFinalCamperNotificationList.Tables[0]);
//dtANFinalCamperNotificationList.Columns.Remove("StartDate");
//dtANFinalCamperNotificationList.Columns.Remove("EndDate");
//dtANFinalCamperNotificationList.Columns["Days"].ColumnName = "Number of days";
for (int i = 0; i < dtANFinalCamperNotificationList.Rows.Count; i++)
{
if (dtANFinalCamperNotificationList.Rows[i]["Federation ID"].ToString().Length == 1)
dtANFinalCamperNotificationList.Rows[i]["Federation ID"] = dtANFinalCamperNotificationList.Rows[i]["Federation ID"].ToString().Insert(0, "00");
else if (dtANFinalCamperNotificationList.Rows[i]["Federation ID"].ToString().Length == 2)
dtANFinalCamperNotificationList.Rows[i]["Federation ID"] = dtANFinalCamperNotificationList.Rows[i]["Federation ID"].ToString().Insert(0, "0");
}
if (File.Exists(strFilePath))
{
File.Delete(strFilePath);
}
StreamWriter strmWriterFile = new StreamWriter(strFilePath, false); //true defines append to the file if exists
//if file does not exists creates new and header (true) if file exists writeheader to be set as false
_objGen.ProduceTabDelimitedFile(dtANFinalCamperNotificationList, strmWriterFile, true, 0);
}
}
string localpath = Request.ApplicationPath + "/" + ConfigurationManager.AppSettings["AwardNotificationFolderPath"].Replace('\\', '/');
string url = Request.ServerVariables["HTTP_HOST"] + localpath + HttpUtility.UrlEncode(strGeneratedFileName);
lblMessage.Text = "Note: Award notification final mode was successful and txt file generated with camper details, please <a href='http://"+url+"' target='_blank'>click here</a> to download it";
lblMessage.Visible = true;
Session["url"] = url;
}
catch (FileNotFoundException ex)
{
throw ex;
}
}
}
|
using System.Collections.Generic;
using ServiceDeskSVC.Domain.Entities.ViewModels.AssetManager;
namespace ServiceDeskSVC.Managers
{
public interface IAssetManagerModelsManager
{
List<AssetManager_Models_vm> GetAllModels();
bool DeleteModelById(int id);
int CreateModel(AssetManager_Models_vm model);
int EditModelById(int id, AssetManager_Models_vm model);
}
}
|
using SFA.DAS.CommitmentsV2.Api.Client;
using SFA.DAS.CommitmentsV2.Api.Types.Requests;
using SFA.DAS.CommitmentsV2.Shared.Interfaces;
using SFA.DAS.ProviderCommitments.Web.Models.Cohort;
using System.Threading.Tasks;
namespace SFA.DAS.ProviderCommitments.Web.Mappers.Cohort
{
public class ConfirmEmployerViewModelToCreateEmptyCohortRequestMapper : IMapper<ConfirmEmployerViewModel, CreateEmptyCohortRequest>
{
private readonly ICommitmentsApiClient _commitmentsApiClient;
public ConfirmEmployerViewModelToCreateEmptyCohortRequestMapper(ICommitmentsApiClient commitmentsApiClient)
{
_commitmentsApiClient = commitmentsApiClient;
}
public async Task<CreateEmptyCohortRequest> Map(ConfirmEmployerViewModel source)
{
var accountLegalEntity = await _commitmentsApiClient.GetAccountLegalEntity(source.AccountLegalEntityId);
return new CreateEmptyCohortRequest
{
AccountId = accountLegalEntity.AccountId,
AccountLegalEntityId = source.AccountLegalEntityId,
ProviderId = source.ProviderId,
};
}
}
}
|
namespace RepositoryInterface
{
public interface IRepository<T> : IReadOnlyRepository<T> where T : class
{
int Update(T entity);
int InsertOnSubmit(T entity);
int DeleteOnSubmit(T entity, bool deleteOnCascade = false);
int SaveChanges();
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace DistCWebSite.Core.Entities
{
public class Contract
{
/// <summary>
/// 年度承诺开始时间
/// </summary>
public int AnnualCommitmentBeginDate { get; set; }
/// <summary>
/// 年度承诺结束时间
/// </summary>
public int AnnualCommitmentEndDate { get; set; }
public string Area_Manager { get; set; }
public string BA { get; set; }
/// <summary>
/// 合同周期
/// </summary>
public int ContractDuration { get; set; }
/// <summary>
/// 合同号
/// </summary>
public string ContractNumber { get; set; }
/// <summary>
/// 合同状态
/// </summary>
public string ContractStatus { get; set; }
/// <summary>
/// 合同类型
/// </summary>
public string ContractType { get; set; }
/// <summary>
/// 经销商
/// </summary>
public string Distributor { get; set; }
/// <summary>
/// 经销商编码
/// </summary>
public string Distributorcode { get; set; }
/// <summary>
/// 终端医院
/// </summary>
public string EndCustomer { get; set; }
/// <summary>
/// 终端医院编码
/// </summary>
public string EndCustomerCode { get; set; }
public int ExtensionDate { get; set; }
/// <summary>
/// 第一次安装日期
/// </summary>
public int FirstSetUpDate { get; set; }
/// <summary>
/// 仪器
/// </summary>
public string Instrument { get; set; }
public string National_Sales_Manager { get; set; }
public int OTDate { get; set; }
/// <summary>
/// 产品名称
/// </summary>
public string ProductName { get; set; }
/// <summary>
/// 省份
/// </summary>
public string Province { get; set; }
public string PurchaseReagentType { get; set; }
public string ReagentCommitmentMonetwhetherincludingTaxcontractperiodtotalReagentCommitment { get; set; }
/// <summary>
/// 区域
/// </summary>
public string Region { get; set; }
/// <summary>
/// 区域经理
/// </summary>
public string Regional_Director { get; set; }
/// <summary>
/// 移回日期
/// </summary>
public int ReloccationDate { get; set; }
/// <summary>
/// 返回日期
/// </summary>
public int ReturnedDate { get; set; }
public string RollUPCUST { get; set; }
public string ROLLUPCUSTNAME { get; set; }
public string RollupDistributor { get; set; }
public string RollupDistributorCode { get; set; }
public string RollUpEndCustomer { get; set; }
public string RollUpEndCustomerCode { get; set; }
/// <summary>
/// 销售经理
/// </summary>
public string Sales_Manager { get; set; }
public string Sales_Rep { get; set; }
public string SalesOrg { get; set; }
/// <summary>
/// 销售团队
/// </summary>
public string SalesTeam { get; set; }
/// <summary>
/// 序列号
/// </summary>
public string SerialNumber { get; set; }
public string Supervisor { get; set; }
/// <summary>
/// 承诺目标量
/// </summary>
public decimal CommitmentTargetAmount { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
public class shoot : MonoBehaviour {
public static float CDRED, CDGREEN, CDBLUE;
public float bulSpeed, shotTimer;
public GameObject bullet, barrel;
public int timer;
// Use this for initialization
void Start () {
timer = 0;
}
// Update is called once per frame
void Update() {
if (timer == 0) {
AkSoundEngine.SetState("Fire", "No_Fire");
}
else
timer--;
if (Input.GetButtonDown("Fire1")) {
if (gameObject.GetComponent<mode>().tankMode == 1)
AkSoundEngine.SetState("Fire", "Fire_Light");
else if (gameObject.GetComponent<mode>().tankMode == 2)
AkSoundEngine.SetState("Fire", "Fire_Med");
else if (gameObject.GetComponent<mode>().tankMode == 3)
AkSoundEngine.SetState("Fire", "Fire_Heavy");
timer = 5;
GameObject newBullet = (GameObject)GameObject.Instantiate(bullet, barrel.transform.position, barrel.transform.rotation);
newBullet.GetComponent<Rigidbody>().AddRelativeForce(new Vector3(0f, 0f, 0.00001f * bulSpeed));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
#nullable enable
namespace NW.ManyQueues.Test {
class TestPluginReflection: IPluginStep1 {
public TestPluginReflection() {
}
public int GetPriority() {
return 1;
}
public FirePluginResult GetResult(FirePluginResult? previous) {
return previous ?? new FirePluginResult();
}
public void SetCaller<T>(T caller) where T : class {
}
public bool Step(int number) {
return number < 0;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ELearningPlatform.Models;
namespace ELearningPlatform.Data
{
public class ModuleData
{
public const string DataTypeImg = "img";
public const string DataTypeString = "string";
private readonly ELearningPlatformContext _context;
public ModuleData(ELearningPlatformContext context)
{
_context = context;
}
public Module GetModule(int IdModule)
{
return _context.Module.Find(IdModule);
}
public List<Module> GetModulesCourse(int IdCourse)
{
return _context.Module.Where(m => m.IdCourse == IdCourse).ToList();
}
public List<int> GetCompletedModule(int IdCourse, int IdUser)
{
List<int> completedModules = new List<int>();
try
{
List<Module> modules = _context.Module.Where(m => m.IdCourse == IdCourse).ToList();
foreach (Module module in modules)
{
if (_context.Completed.Where(e => e.IdModule == module.Id && e.IdUser == IdUser).ToList().Count() > 0)
completedModules.Add(module.Id);
}
}
catch
{
return null;
}
return completedModules;
}
public string GetInstructor(int IdModule)
{
return _context.User.Where(e => e.Id == _context.Module.Find(IdModule).IdInstructor).FirstOrDefault().Username;
}
public IDictionary<int, string> GetInstructorForAllModuleCourse(int idCourse)
{
List<Module> modules = GetModulesCourse(idCourse);
IDictionary<int, string> InstructorName = new Dictionary<int, string>();
foreach(Module module in modules)
{
InstructorName[module.Id] = GetInstructor(module.Id);
}
return InstructorName;
}
public bool CompleteModule(int idModule, int idUser)
{
Completed completed = new Completed();
completed.IdModule = idModule;
completed.IdUser = idUser;
try
{
_context.Completed.Add(completed);
_context.SaveChanges();
}
catch
{
return false;
}
return true;
}
public List<Content> GetContents(int idModule)
{
return _context.Content.Where(e => e.idModule == idModule).ToList();
}
public bool isFinished(int idModule, int idUser)
{
return (_context.Completed.Where(e => e.IdModule == idModule && e.IdUser == idUser).Count() > 0);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using BenefitDeduction.EmployeesSalary;
namespace BenefitDeduction.EmployeeBenefitDeduction.Employees.Calculators
{
public class CalculateDeductionDetailRespository : ICalculateDeductionDetailRespository
{
public CalculateDeductionDetailRespository()
{
}
public IBenefitDeductionDetail CalculateDeductionDetail(ISalary salary, List<IBenefitDeductionItem> benefitDeductionItems) {
var ABenefitDeductionDetail = new BenefitDeductionDetail() {
AnnualTotalCostGross = CalculateAnnualTotalCostGross(benefitDeductionItems),
AnnualTotalCostNet = CalculateAnnualTotalCostNet(benefitDeductionItems),
PerPayPeriodTotalCostGross = CalculatePerPayPeriodTotalCostGross(benefitDeductionItems),
PerPayPeriodTotalCostNet = CalculatePerPayPeriodTotalCostNet(benefitDeductionItems),
BenefitDeductionItems = benefitDeductionItems,
EmployeeSalary = salary.GrossSalaryAnnual,
EmployeeSalaryPerPayPeriod = salary.GrossSalaryPerPayPeriod
};
ABenefitDeductionDetail.AnnualSalaryAjustment =
CalculateAnnualSalaryAjustment(salary, ABenefitDeductionDetail);
ABenefitDeductionDetail.PerPayPeriodSalaryAjustment =
CalculatePerPayPeriodSalaryAjustment(salary, ABenefitDeductionDetail);
ABenefitDeductionDetail.PerPayPeriodBenefitAjustment =
CalculatePerPayPeriodBenefitAjustment(ABenefitDeductionDetail);
return ABenefitDeductionDetail;
}
private decimal CalculateAnnualTotalCostGross(List<IBenefitDeductionItem> benefitDeductionItems) {
var Total = benefitDeductionItems.Select(aItem => aItem.AnnualCostGross).Sum() + .00m;
return Math.Round(Total, 2);
}
private decimal CalculateAnnualTotalCostNet(List<IBenefitDeductionItem> benefitDeductionItems) {
var Total = benefitDeductionItems.Select(aItem => aItem.AnnualCostNet).Sum() +.00m;
return Math.Round(Total, 2);
}
private decimal CalculatePerPayPeriodTotalCostGross(List<IBenefitDeductionItem> benefitDeductionItems) {
var Total = benefitDeductionItems.Select(aItem => aItem.PerPayPeriodCostGross).Sum() + .00m;
return Math.Round(Total, 2);
}
private decimal CalculatePerPayPeriodTotalCostNet(List<IBenefitDeductionItem> benefitDeductionItems) {
var Total = benefitDeductionItems.Select(aItem => aItem.PerPayPeriodCostNet).Sum() +.00m;
return Math.Round(Total, 2);
}
private decimal CalculateAnnualSalaryAjustment(ISalary salary, BenefitDeductionDetail benefitDeductionDetail) {
var Total = (salary.GrossSalaryAnnual - benefitDeductionDetail.AnnualTotalCostNet) + .00m;
return Math.Round(Total, 2);
}
private decimal CalculatePerPayPeriodSalaryAjustment(ISalary salary, BenefitDeductionDetail benefitDeductionDetail)
{
var Total = (salary.GrossSalaryPerPayPeriod - benefitDeductionDetail.PerPayPeriodTotalCostNet) + .00m;
return Math.Round(Total, 2, MidpointRounding.AwayFromZero);
}
private decimal CalculatePerPayPeriodBenefitAjustment(BenefitDeductionDetail benefitDeductionDetail)
{
if (benefitDeductionDetail.PerPayPeriodTotalCostGross == benefitDeductionDetail.PerPayPeriodTotalCostNet) {
return benefitDeductionDetail.PerPayPeriodTotalCostGross;
}
return benefitDeductionDetail.PerPayPeriodTotalCostNet;
}
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace Voluntariat.Data.Migrations
{
public partial class Add_Columns_To_NGO : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "HeadquartersAddress",
table: "Ongs",
nullable: false,
defaultValue: "");
migrationBuilder.AddColumn<string>(
name: "IdentificationNumber",
table: "Ongs",
nullable: false,
defaultValue: "");
migrationBuilder.AddColumn<string>(
name: "Website",
table: "Ongs",
nullable: false,
defaultValue: "");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "HeadquartersAddress",
table: "Ongs");
migrationBuilder.DropColumn(
name: "IdentificationNumber",
table: "Ongs");
migrationBuilder.DropColumn(
name: "Website",
table: "Ongs");
}
}
}
|
using EddiEvents;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using Utilities;
namespace EddiSpeechResponder
{
/// <summary>
/// A personality is a combination of scripts used to respond to specific events
/// </summary>
public class Personality : INotifyPropertyChanged
{
[JsonProperty("name")]
public string Name
{
get => _name;
private set
{
if (_name != value)
{
_name = value;
OnPropertyChanged();
}
}
}
[JsonProperty("description")]
public string Description
{
get => _description;
private set
{
if (_description != value)
{
_description = value;
OnPropertyChanged();
}
}
}
[JsonProperty("scripts")]
public Dictionary<string, Script> Scripts
{
get => _scripts;
private set
{
if (_scripts != value)
{
_scripts = value;
OnPropertyChanged();
}
}
}
[JsonIgnore]
public bool IsCustom
{
get => _isCustom;
set
{
_isCustom = value;
OnPropertyChanged();
}
}
[JsonIgnore]
private string _name;
[JsonIgnore]
private string _description;
[JsonIgnore]
private Dictionary<string, Script> _scripts;
[JsonIgnore]
private bool _isCustom;
[JsonIgnore]
private string dataPath;
private static readonly string[] obsoleteScriptKeys =
{
"Jumping", // Replaced by "FSD engaged" script
"Crew member role change", // This name is mismatched to the key (should be "changed"), so EDDI couldn't match the script name to the .json key correctly. The default script has been corrected.
"Ship low fuel", // Accidental duplicate. The real event is called 'Low fuel'
"Modification applied", // Event deprecated by FDev, no longer written.
"List launchbays", // Replaced by "Launchbay report" script
"Combat promotion", // Replaced by "Commander promotion" script
"Empire promotion", // Replaced by "Commander promotion" script
"Exploration promotion", // Replaced by "Commander promotion" script
"Federation promotion", // Replaced by "Commander promotion" script
"Trade promotion", // Replaced by "Commander promotion" script
"Ship repurchased" // Replaced by "Respawned" script
};
private static readonly string[] ignoredEventKeys =
{
// Shares updates with monitors / responders but are not intended to be user facing
"Cargo",
"Fleet carrier materials",
"Market",
"Outfitting",
"Shipyard",
"Squadron startup",
"Stored ships",
"Stored modules",
"Unhandled event"
};
private static readonly string DIRECTORYPATH = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static readonly string DEFAULT_PATH = new DirectoryInfo(DIRECTORYPATH).FullName + @"\" + Properties.SpeechResponder.default_personality_script_filename;
private static readonly string DEFAULT_USER_PATH = Constants.DATA_DIR + @"\personalities\" + Properties.SpeechResponder.default_personality_script_filename;
private static readonly List<string> upgradedPersonalities = new List<string>();
public Personality(string name, string description, Dictionary<string, Script> scripts)
{
// Ensure that the name doesn't have any illegal characters
string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
Regex r = new Regex($"[{Regex.Escape(regexSearch)}]");
Name = r.Replace(name, "");
Name = name;
Description = description;
Scripts = scripts;
}
/// <summary>
/// Obtain all personalities from a directory. If the directory name is not supplied the
/// default of Constants.Data_DIR\personalities is used
/// </summary>
public static List<Personality> AllFromDirectory(string directory = null)
{
List<Personality> personalities = new List<Personality>();
if (directory == null)
{
directory = Constants.DATA_DIR + @"\personalities";
Directory.CreateDirectory(directory);
}
foreach (FileInfo file in new DirectoryInfo(directory).GetFiles("*.json", SearchOption.AllDirectories))
{
Personality personality = FromFile(file.FullName);
if (personality != null)
{
personalities.Add(personality);
}
}
return personalities;
}
public static Personality FromName(string name)
{
if (name == "EDDI")
{
return Default();
}
else
{
return FromFile(Constants.DATA_DIR + @"\personalities\" + name.ToLowerInvariant() + ".json");
}
}
/// <summary>
/// Obtain the default personality
/// </summary>
public static Personality Default()
{
return FromFile(DEFAULT_PATH, true);
}
/// <summary>
/// Obtain personality from a file.
/// </summary>
public static Personality FromFile(string filename = null, bool isDefault = false)
{
if (filename == null)
{
filename = DEFAULT_USER_PATH;
isDefault = true;
}
Personality personality = null;
string data = Files.Read(filename);
if (data != null)
{
try
{
personality = JsonConvert.DeserializeObject<Personality>(data);
}
catch (Exception e)
{
if (!isDefault)
{
// malformed JSON for some reason: rename so that the user can examine and fix it.
string newFileName = filename + ".malformed";
if (File.Exists(newFileName))
{
// no point keeping a history: only the latest is likely to be useful. Pro users will be using version control anyway.
File.Delete(newFileName);
}
File.Move(filename, newFileName);
Logging.Error($"Could not parse \"{filename}\": moved to \"{newFileName}\". Error was \"{e.Message}\"");
}
else
{
throw new FormatException("Could not parse default personality (eddi.json)");
}
}
}
if (personality != null)
{
personality.dataPath = filename;
personality.IsCustom = !isDefault;
fixPersonalityInfo(personality);
}
return personality;
}
/// <summary>
/// Write personality to a file.
/// </summary>
public void ToFile(string filename = null)
{
if (filename == null)
{
filename = dataPath;
}
if (filename == null)
{
filename = DEFAULT_USER_PATH;
}
if (filename != DEFAULT_PATH)
{
string json = JsonConvert.SerializeObject(this, Formatting.Indented);
Files.Write(filename, json);
}
}
public static void incrementPersonalityBackups(Personality personality)
{
if (!personality.IsCustom) { return; }
var filesToMove = new Dictionary<string, string>(); // Key = FROM, Value = TO
var filesToDelete = new List<string>();
// Obtain files, sorting by last write time to ensure that older files are incremented prior to newer files
var personalityDirInfo = new FileInfo(personality.dataPath).Directory;
if (personalityDirInfo is null) { return; }
foreach (FileInfo file in personalityDirInfo.GetFiles()
.Where(f =>
f.Name.StartsWith(personality.Name, StringComparison.InvariantCultureIgnoreCase) &&
f.Name.EndsWith(".bak", StringComparison.InvariantCultureIgnoreCase))
.OrderBy(f => f.LastWriteTimeUtc)
.ToList())
{
bool parsed = int.TryParse(file.FullName
.Replace($@"{personality.dataPath}", "")
.Replace(".bak", "")
.Replace(".", ""), out int i);
++i; // Increment our index number
if (i >= 10)
{
filesToDelete.Add(file.FullName);
}
else
{
filesToMove.Add(file.FullName, $@"{personality.dataPath}.{i}.bak");
}
}
try
{
LockManager.GetLock(nameof(personality.Name), () =>
{
foreach (var deleteFilePath in filesToDelete)
{
File.Delete(deleteFilePath);
}
foreach (var moveFilePath in filesToMove)
{
File.Move(moveFilePath.Key, moveFilePath.Value);
}
});
}
catch (Exception)
{
// Someone may have had the file open when this code executed? Nothing to do, we'll try again on the next run
}
// Save the most recent backup
personality.ToFile($"{personality.dataPath}.bak");
}
/// <summary>
/// Create a copy of this file, altering the datapath appropriately
/// </summary>
public Personality Copy(string name, string description)
{
// Tidy the name up to avoid bad characters
string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
name = r.Replace(name, "");
// Save a copy of this personality
string iname = name.ToLowerInvariant();
string copyPath = Constants.DATA_DIR + @"\personalities\" + iname + ".json";
// Ensure it doesn't exist
if (!File.Exists(copyPath))
{
ToFile(copyPath);
}
// Load the personality back in
Personality newPersonality = FromFile(copyPath);
// Change its name and description and save it back out again
newPersonality.Name = name;
newPersonality.Description = description;
newPersonality.ToFile();
// And finally return it
return newPersonality;
}
public void RemoveFile()
{
File.Delete(dataPath);
}
/// <summary>
/// Fix up the personality information to ensure that it contains the correct event
/// </summary>
private static void fixPersonalityInfo(Personality personality)
{
if (upgradedPersonalities.Contains(personality.dataPath)) { return; }
// Create or update a simple backup before we begin
incrementPersonalityBackups(personality);
// Default personality for reference scripts
var defaultPersonality = !personality.IsCustom ? null : Default();
var fixedScripts = new Dictionary<string, Script>();
// First, iterate through our default event scripts. Ensure that every required event script is present.
List<string> missingScripts = new List<string>();
foreach (var defaultEvent in Events.DESCRIPTIONS)
{
personality.Scripts.TryGetValue(defaultEvent.Key, out Script script);
Script defaultScript = null;
defaultPersonality?.Scripts?.TryGetValue(defaultEvent.Key, out defaultScript);
script = UpgradeScript(script, defaultScript);
if (!obsoleteScriptKeys.Contains(defaultEvent.Key))
{
if (script == null && !ignoredEventKeys.Contains(defaultEvent.Key))
{
missingScripts.Add(defaultEvent.Key);
}
else if (script != null)
{
script.PersonalityIsCustom = personality.IsCustom;
fixedScripts.Add(defaultEvent.Key, script);
}
}
}
// Report missing scripts which ought to be present for events, except those we have specifically named
if (missingScripts.Count > 0)
{
Logging.Info("Failed to find scripts" + string.Join(";", missingScripts));
}
// Also add any secondary scripts present in the default personality but which aren't present in the events list
if (defaultPersonality?.Scripts != null)
{
foreach (var personalityScriptKV in personality.Scripts.Where(s => !fixedScripts.Keys.Contains(s.Key)))
{
#pragma warning disable IDE0018 // Inline variable declaration - we fail CI testing when we try to in-line this.
Script defaultScript = null;
#pragma warning restore IDE0018 // Inline variable declaration
if ((defaultPersonality.Scripts?.TryGetValue(personalityScriptKV.Key, out defaultScript) ?? false) &&
!obsoleteScriptKeys.Contains(personalityScriptKV.Key))
{
var script = UpgradeScript(personalityScriptKV.Value, defaultScript);
script.PersonalityIsCustom = personality.IsCustom;
fixedScripts.Add(personalityScriptKV.Key, script);
}
}
}
// Next, iterate through the personality's scripts and add any secondary scripts from the personality.
foreach (var kv in personality.Scripts)
{
// Add non-event scripts from the personality for which we do not have a default
if (!fixedScripts.ContainsKey(kv.Key) && !obsoleteScriptKeys.Contains(kv.Key))
{
var script = kv.Value;
script.PersonalityIsCustom = personality.IsCustom;
fixedScripts.Add(kv.Key, script);
}
}
// Sort scripts and save to file
personality.Scripts = fixedScripts.OrderBy(s => s.Key).ToDictionary(s => s.Key, s => s.Value);
personality.ToFile();
upgradedPersonalities.Add(personality.dataPath);
}
public static Script UpgradeScript(Script personalityScript, Script defaultScript)
{
Script script = personalityScript ?? defaultScript;
if (script != null)
{
if (defaultScript != null)
{
if (script.Default)
{
// This is a default script so take the latest value
script.Value = defaultScript.Value;
}
// Set the default value of our script
script.defaultValue = defaultScript.Value;
if (defaultScript.Responder)
{
// This is a responder script so update applicable parameters
script.Description = defaultScript.Description;
script.Responder = defaultScript.Responder;
}
}
}
return script;
}
#region INotifyPropertyChanged
/// <summary>
/// Raised when a property on this object has a new value.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ingresso.TestePauloRocha.Model
{
[Table("SES_SESSOES")]
public class Sessoes
{
[Key]
public int Fil_ID { get; set; }
public int Cin_ID { get; set; }
public int Sal_ID { get; set; }
public DateTime Ses_Data_Hora_Inicio { get; set; }
public virtual Filmes filme { get; set; }
}
}
|
using gView.Framework.Data;
using gView.Framework.Data.Metadata;
using gView.Framework.Geometry;
using gView.Framework.IO;
using gView.Framework.system;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace gView.DataSources.OGR
{
[gView.Framework.system.RegisterPlugIn("7a972c29-4955-4899-b142-98f6e05bb063")]
public class Dataset : DatasetMetadata, IFeatureDataset, IDisposable, IDataset2, IPlugInDependencies
{
private string _connectionString, _lastErrMsg = "";
private DatasetState _state = DatasetState.unknown;
private List<IDatasetElement> _elements = null;
public Dataset()
{
OSGeo.Initializer.RegisterAll();
}
#region IFeatureDataset Member
public Task<IEnvelope> Envelope()
{
return Task.FromResult<IEnvelope>(new Envelope());
}
public Task<ISpatialReference> GetSpatialReference()
{
return Task.FromResult<ISpatialReference>(null);
}
public void SetSpatialReference(ISpatialReference sRef) { }
#endregion
#region IDataset Member
public string ConnectionString
{
get
{
return _connectionString;
}
}
public Task<bool> SetConnectionString(string value)
{
_connectionString = value;
return Task.FromResult(true);
}
public string DatasetGroupName
{
get { return "gView.GDAL"; }
}
public string DatasetName
{
get { return "gView.OGR"; }
}
public string ProviderName
{
get { return "gView.GIS"; }
}
public DatasetState State
{
get { return _state; }
}
public Task<bool> Open()
{
try
{
switch (OSGeo.Initializer.InstalledVersion)
{
case OSGeo.GdalVersion.V1:
using (var dataSourceV1 = OSGeo_v1.OGR.Ogr.Open(_connectionString, 0))
{
if (dataSourceV1 != null)
{
_state = DatasetState.opened;
return Task.FromResult(true);
}
}
break;
case OSGeo.GdalVersion.V3:
using (var dataSourceV3 = OSGeo_v3.OGR.Ogr.Open(_connectionString, 0))
{
if (dataSourceV3 != null)
{
_state = DatasetState.opened;
return Task.FromResult(true);
}
}
break;
}
return Task.FromResult(false);
}
catch (Exception ex)
{
_lastErrMsg = ex.Message;
return Task.FromResult(false);
}
}
public string LastErrorMessage
{
get { return _lastErrMsg; }
set { _lastErrMsg = value; }
}
public int order
{
get
{
return 0;
}
set
{
}
}
public IDatasetEnum DatasetEnum
{
get { return null; }
}
public Task<List<IDatasetElement>> Elements()
{
if (_elements != null && _elements.Count > 0)
{
return Task.FromResult(_elements);
}
_elements = new List<IDatasetElement>();
if (_state != DatasetState.opened)
{
return Task.FromResult(_elements);
}
if (OSGeo.Initializer.InstalledVersion == OSGeo.GdalVersion.V1)
{
using (var dataSourceV1 = OSGeo_v1.OGR.Ogr.Open(_connectionString, 0))
{
var layerCount = dataSourceV1.GetLayerCount();
for (int i = 0; i < layerCount; i++)
{
OSGeo_v1.OGR.Layer ogrLayerV1 = dataSourceV1?.GetLayerByIndex(i);
if (ogrLayerV1 != null)
{
_elements.Add(new DatasetElement(new FeatureClassV1(this, ogrLayerV1)));
}
}
}
}
else if (OSGeo.Initializer.InstalledVersion == OSGeo.GdalVersion.V3)
{
using (var dataSourceV3 = OSGeo_v3.OGR.Ogr.Open(_connectionString, 0))
{
var layerCount = dataSourceV3.GetLayerCount();
for (int i = 0; i < layerCount; i++)
{
using (var ogrLayerV3 = dataSourceV3.GetLayerByIndex(i))
{
if (ogrLayerV3 != null)
{
_elements.Add(new DatasetElement(new FeatureClassV3(this, ogrLayerV3.GetName())));
}
}
}
}
}
return Task.FromResult(_elements);
}
public string Query_FieldPrefix
{
get { return String.Empty; }
}
public string Query_FieldPostfix
{
get { return String.Empty; }
}
public gView.Framework.FDB.IDatabase Database
{
get
{
return null;
}
}
async public Task<IDatasetElement> Element(string title)
{
foreach (IDatasetElement element in await this.Elements())
{
if (element.Class != null &&
element.Class.Name == title)
{
return element;
}
}
return null;
}
public Task RefreshClasses()
{
return Task.CompletedTask;
}
#endregion
#region IDisposable Member
public void Dispose()
{
}
#endregion
static public bool hasUnsolvedDependencies
{
get
{
return OSGeo.Initializer.RegisterAll() != true;
}
}
#region IDataset2 Member
async public Task<IDataset2> EmptyCopy()
{
Dataset dataset = new Dataset();
await dataset.SetConnectionString(ConnectionString);
await dataset.Open();
return dataset;
}
public Task AppendElement(string elementName)
{
if (_elements == null)
{
_elements = new List<IDatasetElement>();
}
foreach (IDatasetElement e in _elements)
{
if (e.Title == elementName)
{
return Task.CompletedTask;
}
}
if (_state == DatasetState.opened)
{
if (OSGeo.Initializer.InstalledVersion == OSGeo.GdalVersion.V1)
{
using (var dataSourceV1 = OSGeo_v1.OGR.Ogr.Open(_connectionString, 0))
{
var layerCount = dataSourceV1.GetLayerCount();
for (int i = 0; i < layerCount; i++)
{
string ogrLayerName = dataSourceV1.GetLayerByIndex(i)?.GetName();
if (ogrLayerName == elementName)
{
OSGeo_v1.OGR.Layer ogrLayerV1 = dataSourceV1.GetLayerByIndex(i);
if (ogrLayerV1 != null)
{
_elements.Add(new DatasetElement(new FeatureClassV1(this, ogrLayerV1)));
}
}
}
}
}
else if (OSGeo.Initializer.InstalledVersion == OSGeo.GdalVersion.V3)
{
using (var dataSourceV3 = OSGeo_v3.OGR.Ogr.Open(_connectionString, 0))
{
var layerCount = dataSourceV3.GetLayerCount();
for (int i = 0; i < layerCount; i++)
{
string ogrLayerName = dataSourceV3.GetLayerByIndex(i)?.GetName();
if (ogrLayerName == elementName)
{
using (var ogrLayerV3 = dataSourceV3.GetLayerByIndex(i))
{
if (ogrLayerV3 != null)
{
_elements.Add(new DatasetElement(new FeatureClassV3(this, ogrLayerV3.GetName())));
}
}
}
}
}
}
}
return Task.CompletedTask;
}
#endregion
#region IPlugInDependencies Member
public bool HasUnsolvedDependencies()
{
return hasUnsolvedDependencies;
}
#endregion
#region IPersistable Member
public Task<bool> LoadAsync(IPersistStream stream)
{
_connectionString = (string)stream.Load("connectionstring", String.Empty);
return Task.FromResult(true);
}
public void Save(IPersistStream stream)
{
stream.SaveEncrypted("connectionstring", _connectionString);
//this.Open();
}
#endregion
}
}
|
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Markup;
using Cradiator.Model;
using Cradiator.Services;
namespace Cradiator.Converters
{
[MarkupExtensionReturnType(typeof(ImagePathConverter))]
public class ImagePathConverter : MarkupExtension, IValueConverter
{
readonly IBuildBuster _buildBuster;
/// <summary>
/// xaml insists on this DO NOT USE
/// </summary>
public ImagePathConverter() {}
public ImagePathConverter([InjectBuildBusterImageDecorator] IBuildBuster buildBuster)
{
_buildBuster = buildBuster;
}
/// <summary>
/// convert from CurrentMessage to the FileName of an image to load (using breaker's name eg bsimpson.jpg)
/// </summary>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return _buildBuster.FindBreaker(value as string);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return Ninjector.Get<ImagePathConverter>();
}
}
} |
using Microsoft.EntityFrameworkCore.Migrations;
namespace AnyTest.DbAccess.Migrations
{
public partial class AddCourseToPrecondition : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_Preconditions",
table: "Preconditions");
migrationBuilder.AddColumn<long>(
name: "CourseId",
table: "Preconditions",
nullable: false,
defaultValue: 0L);
migrationBuilder.AddPrimaryKey(
name: "PK_Preconditions",
table: "Preconditions",
columns: new[] { "TestId", "CourseId", "PreconditionId" });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_Preconditions",
table: "Preconditions");
migrationBuilder.DropColumn(
name: "CourseId",
table: "Preconditions");
migrationBuilder.AddPrimaryKey(
name: "PK_Preconditions",
table: "Preconditions",
columns: new[] { "TestId", "PreconditionId" });
}
}
}
|
using System;
namespace DivideAndConquer
{
class Program
{
static int MaxElem(int[] array, int start, int end)
{
var length = end - start + 1;
if (array == null || array.Length == 0 || length < 1)
throw new InvalidOperationException();
else if (length == 1)
return array[start];
else
{
var threshold = start + length/2;
var max1 = MaxElem(array, start, threshold - 1);
var max2 = MaxElem(array, threshold, end);
return max1 > max2 ? max1 : max2;
}
}
static void Main()
{
var arr = new int[] { 10, 1, 2, 100, -5, 0, 7, 4, 25};
Console.WriteLine(MaxElem(arr, 0, arr.Length - 1));
Console.ReadKey();
}
}
}
|
/******************************************************************************\
* Copyright (C) 2012-2016 Leap Motion, Inc. All rights reserved. *
* Leap Motion proprietary and confidential. Not for distribution. *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
\******************************************************************************/
using System;
using System.Collections.Generic;
using Leap;
namespace LeapInternal
{
public class PendingImages
{
List<ImageFuture> _pending = new List<ImageFuture>(20);
UInt32 _pendingTimeLimit = 90000; // microseconds
private object _locker = new object();
public UInt32 pendingTimeLimit { get{ return _pendingTimeLimit; }
set{ _pendingTimeLimit = value; } }
public void Add(ImageFuture pendingImage)
{
lock(_locker){
_pending.Add(pendingImage);
}
}
public ImageFuture FindAndRemove(LEAP_IMAGE_FRAME_REQUEST_TOKEN token)
{
lock(_locker){
for (int i = 0; i < _pending.Count; i++) {
ImageFuture ir = _pending[i];
if (ir.Token.requestID == token.requestID) {
_pending.RemoveAt(i);
return ir;
}
}
}
return null;
}
public int purgeOld(IntPtr connection)
{
Int64 now = LeapC.GetNow();
int purgeCount = 0;
lock(_locker){
for (int i = _pending.Count - 1; i >= 0; i--) {
ImageFuture ir = _pending[i];
if ((now - ir.Timestamp) > pendingTimeLimit){
_pending.RemoveAt(i);
LeapC.CancelImageFrameRequest(connection, ir.Token);
purgeCount++;
}
}
}
return purgeCount;
}
public int purgeAll(IntPtr connection)
{
int purgeCount = 0;
lock(_locker){
purgeCount = _pending.Count;
for (int i = 0; i < _pending.Count; i++) {
LeapC.CancelImageFrameRequest(connection, _pending[i].Token);
}
_pending.Clear();
}
return purgeCount;
}
}
}
|
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Helpers;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.ContentItemVersions;
using Microsoft.Extensions.Configuration;
using OrchardCore.ContentManagement;
namespace DFC.ServiceTaxonomy.GraphSync.GraphSyncers.ContentItemVersions
{
public class PublishedContentItemVersion : ContentItemVersion, IPublishedContentItemVersion
{
public PublishedContentItemVersion(IConfiguration configuration)
: base(GraphReplicaSetNames.Published,
VersionOptions.Published,
(null, true),
GetContentApiBaseUrlFromConfig(configuration, "ContentApiPrefix"))
{
}
}
}
|
using System;
using Atc.Rest.Extended.Options;
using Atc.Rest.Options;
using Microsoft.Extensions.Configuration;
// ReSharper disable InvertIf
// ReSharper disable once CheckNamespace
namespace Microsoft.Extensions.DependencyInjection
{
public static class RestApiExtendedExtensions
{
public static IServiceCollection AddRestApi<TStartup>(this IServiceCollection services)
{
return services.AddRestApi<TStartup>(mvc => { }, new RestApiExtendedOptions());
}
public static IServiceCollection AddRestApi<TStartup>(
this IServiceCollection services,
RestApiExtendedOptions restApiOptions,
IConfiguration configuration)
{
return services.AddRestApi<TStartup>(mvc => { }, restApiOptions, configuration);
}
public static IServiceCollection AddRestApi<TStartup>(
this IServiceCollection services,
Action<IMvcBuilder> setupMvcAction,
RestApiExtendedOptions restApiOptions,
IConfiguration configuration)
{
if (setupMvcAction == null)
{
throw new ArgumentNullException(nameof(setupMvcAction));
}
if (restApiOptions == null)
{
throw new ArgumentNullException(nameof(restApiOptions));
}
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
services.AddSingleton(restApiOptions);
services.AddSingleton<RestApiOptions>(restApiOptions);
if (restApiOptions.UseApiVersioning)
{
services.ConfigureOptions<ConfigureApiVersioningOptions>();
services.AddApiVersioning();
services.AddVersionedApiExplorer(o => o.GroupNameFormat = "'v'VV");
}
if (restApiOptions.UseOpenApiSpec)
{
services.ConfigureOptions<ConfigureSwaggerOptions>();
services.AddSwaggerGen();
}
services.AddRestApi<TStartup>(setupMvcAction, restApiOptions);
if (restApiOptions.UseFluentValidation)
{
services.AddFluentValidation<TStartup>(restApiOptions.UseAutoRegistrateServices, restApiOptions.AssemblyPairs);
}
configuration.Bind(AuthorizationOptions.ConfigurationSectionName, restApiOptions.Authorization);
services.ConfigureOptions<ConfigureAuthorizationOptions>();
services.AddAuthentication().AddJwtBearer();
return services;
}
}
} |
using Autofac;
using Autofac.Extras.DynamicProxy;
using KMS.Twelve.Controllers;
using KMS.Twelve.Message;
using KMS.Twelve.Test;
using System.Linq;
using System.Reflection;
using Module = Autofac.Module;
namespace KMS.Twelve
{
public class DefaultModule : Module
{
protected override void Load(ContainerBuilder builder)
{
////注入测试服务
//builder.RegisterType<TestService>().As<ITestService>();
//属性注入
//builder.RegisterType<TestService>().As<ITestService>().PropertiesAutowired();
//builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
//builder.RegisterType<InMemoryCache>().As<ICache>().InstancePerLifetimeScope();
// Register 方式指定具体类
builder.Register(c => new InjectionTestService()).As<IService>().InstancePerDependency();
// RegisterType 方式指定具体类
builder.RegisterType<InjectionTestService>().As<IService>().InstancePerDependency();
// 自动注入的方式,不需要知道具体类的名称
/* BuildManager.GetReferencedAssemblies()
* 程序集的集合,包含 Web.config 文件的 assemblies 元素中指定的程序集、
* 从 App_Code 目录中的自定义代码生成的程序集以及其他顶级文件夹中的程序集。
*
* 依赖注入之Autofac使用总结
* https://www.cnblogs.com/struggle999/p/6986903.html
*/
// 获取包含继承了IService接口类的程序集
var allAssemblies = Assembly.GetEntryAssembly()
.GetReferencedAssemblies()
.Select(Assembly.Load)
.Where(
assembly =>
assembly.GetTypes().FirstOrDefault(type => type.GetInterfaces()
.Contains(typeof(IService))) != null
)
;
// RegisterAssemblyTypes 注册程序集
//.net core如何读取所有页面的程序集
// https://q.cnblogs.com/q/113026/
var enumerable = allAssemblies as Assembly[] ?? allAssemblies.ToArray();
if (enumerable.Any())
{
builder.RegisterAssemblyTypes(enumerable)
.Where(type => type.GetInterfaces().Contains(typeof(IService))).AsSelf().InstancePerDependency();
}
//containerBuilder.RegisterType<AutoDIController>().PropertiesAutowired();
builder.RegisterAssemblyTypes(typeof(AutoDIController).Assembly)
.Where(t => t.Name.EndsWith("Controller") || t.Name.EndsWith("AppService")).PropertiesAutowired();
//builder.RegisterAssemblyTypes(typeof(StuEducationRepo).Assembly)
// .Where(t => t.Name.EndsWith("Repo"))
// .AsImplementedInterfaces().InstancePerLifetimeScope();
//builder.RegisterAssemblyTypes(typeof(StudentRegisterDmnService).Assembly)
// .Where(t => t.Name.EndsWith("DmnService"))
// .AsImplementedInterfaces().InstancePerLifetimeScope();
//builder.RegisterAssemblyTypes(typeof(StuEducationAppService).Assembly)
// .Where(t => t.Name.EndsWith("AppService"))
//属性注入控制器
//containerBuilder.RegisterType<AutoDIController>().PropertiesAutowired();
builder.Register(c => new AOPTest());
//加上EnableInterfaceInterceptors来开启你的拦截.
builder.RegisterType<TestService>().As<ITestService>()
.PropertiesAutowired().EnableInterfaceInterceptors();
typeof(IMessage).Assembly.GetTypes()
.Where(t => t.GetInterfaces().Contains(typeof(IMessage))).ToList()
.ForEach(type =>
{
builder.RegisterType(type);
//builder.RegisterType<type>();
// 注册type
});
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace ConFutureNce.Models
{
public class Reviewer : UserType
{
[Display(Name = "Scientific title")]
public string ScTitle { get; set; }
[Display(Name = "Ordanization's name")]
public string OrgName { get; set; }
[Required]
public int Language1Id { get; set; }
public int? Language2Id { get; set; }
public int? Language3Id { get; set; }
[ForeignKey("Language1Id")]
public Language Language1 { get; set; }
[ForeignKey("Language2Id")]
public Language Language2 { get; set; }
[ForeignKey("Language3Id")]
public Language Language3 { get; set; }
public ICollection<Paper> Papers { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private int mode = 0;
//mode == 0 - просмотр;
//mode == 1 - создание;
//mode == 2 - редактирование;
//mode == 3 - режим выбора нескольких позиций;
private int indexCar;
private Image tempImage; //Временная переменная для изображения
private string pathNewImage; //Путь к новому изображению
private string commandText; //Команда для БД
//Заголовки параметров в таблице dataGridView
private string makeHeader = "Марка";
private string modelHeader = "Модель";
private string yearHeader = "Год выпуска";
private string bodyStyleHeader = "Тип кузова";
List<Car> CarList = new List<Car>();//Список автомобилей
//Загрузка данных с БД
private void LoadFromDatabase()
{
using (SQLiteConnection Database = new SQLiteConnection("Data Source=Cars.db; Version=3;"))
{
try
{
Database.Open();
//Проверяем существование таблицы
commandText = "SELECT Id, Make, Model, Year, BodyStyle, Image FROM Cars";
SQLiteCommand Command = new SQLiteCommand(commandText, Database);
SQLiteDataReader reader = Command.ExecuteReader();
while (reader.Read())
{
Int32.TryParse(Convert.ToString(reader["Year"]), out int year);
CarList.Add(new Car(Convert.ToInt32(reader["Id"]), Convert.ToString(reader["Make"]), Convert.ToString(reader["Model"]), year, Convert.ToString(reader["BodyStyle"]), Convert.ToString(reader["Image"])));
}
}
catch
{
MessageBox.Show("База данных не найдена или повреждена и будет создана заново", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Information);
//Удаляем существующую таблицу
commandText = "DROP TABLE IF EXISTS Cars";
SQLiteCommand Command = new SQLiteCommand(commandText, Database);
Command.ExecuteNonQuery();
//Создаем новую таблицу
commandText = "CREATE TABLE [Cars] ( [Id] INTEGER PRIMARY KEY AUTOINCREMENT, [Make] TEXT, [Model] TEXT, " +
"[Year] INTEGER, [BodyStyle] TEXT, [Image] TEXT)";
Command = new SQLiteCommand(commandText, Database);
Command.ExecuteNonQuery();
//Заполняем по умолчанию
if (CarList.Count == 0)
{
CarList.Add(new Car(1, "Toyota", "Allion", 2009, "Седан", "C:\\Users\\Admin\\Desktop\\WindowsFormsApp1\\WindowsFormsApp1\\images\\1.jpg"));
CarList.Add(new Car(2, "Волга", "3110", 2001, "Седан", "C:\\Users\\Admin\\Desktop\\WindowsFormsApp1\\WindowsFormsApp1\\images\\2.jpg"));
CarList.Add(new Car(3, "Нива", "Урбан", 2016, "Хетчбек", "C:\\Users\\Admin\\Desktop\\WindowsFormsApp1\\WindowsFormsApp1\\images\\3.jpg"));
}
for (byte i = 0; i < CarList.Count; i++)
{
SaveIntoDatabase(CarList[i].Make, CarList[i].Model, CarList[i].Year, CarList[i].BodyStyle, CarList[i].Image);
}
}
Database.Close();
}
}
//Сохранение данных с БД
private void SaveIntoDatabase(string make, string model, int year, string bodyStyle, string image)
{
using (SQLiteConnection DataBase = new SQLiteConnection("Data Source=Cars.db; Version=3;"))
{
try
{
DataBase.Open();
commandText = $"INSERT INTO Cars ([Make], [Model], [Year], [BodyStyle], [Image]) VALUES('{make}', '{model}', '{year}', '{bodyStyle}', '{image}');";
SQLiteCommand Command = new SQLiteCommand(commandText, DataBase);
Command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error);
LoadFromDatabase();
}
DataBase.Close();
}
}
//Удаление данных с БД
private void DeleteFromDatabase(int id)
{
using (SQLiteConnection Database = new SQLiteConnection("Data Source=Cars.db; Version=3;"))
{
try
{
Database.Open();
commandText = $"DELETE FROM Cars WHERE id = {id};";
SQLiteCommand Command = new SQLiteCommand(commandText, Database);
Command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error);
LoadFromDatabase();
}
Database.Close();
}
}
//Обновление данных в БД
private void UpdateDatabase(int id, string make, string model, int year, string bodyStyle, string image)
{
using (SQLiteConnection Database = new SQLiteConnection("Data Source=Cars.db; Version=3;"))
{
try
{
Database.Open();
commandText = $"UPDATE Cars SET Make = '{make}', Model = '{model}', Year = '{year}', BodyStyle = '{bodyStyle}', Image = '{image}' WHERE Id = '{id}';";
SQLiteCommand Command = new SQLiteCommand(commandText, Database);
Command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error);
LoadFromDatabase();
}
Database.Close();
}
}
//Функция получения списка автомобилей
private void GetCarList()
{
listView1.Clear();
imageList1.Images.Clear();
dataGridView1.Rows.Clear();
CarList.Clear();
dataGridView1.Visible = false;
LoadFromDatabase();
pictureBox1.Image = null;
button_DeleteCar.Enabled = false;
ListViewItem Car = new ListViewItem();
imageList1.ImageSize = new Size(30, 30); //Задаем размер изображений для listView
listView1.LargeImageList = imageList1; //Задаем библиотеку изображений
//Заполняем библиотеку изображений, выводим базу автомобилей
for (int i = 0; i < CarList.Count; i++)
{
try
{
imageList1.Images.Add(Image.FromFile(CarList[i].Image));
}
catch
{
imageList1.Images.Add(Properties.Resources.emptyImage);
}
ListViewItem listViewItem = new ListViewItem();
listViewItem.Tag = i;
listViewItem.Text = CarList[i].Make + " " + CarList[i].Model + "\n(" + CarList[i].Year + ")";
listViewItem.ImageIndex = i;
listView1.Items.Add(listViewItem);
}
}
//Функция получения данных о выбранном автомобиле
private void GetCarInfo(int indexCar)
{
dataGridView1.Enabled = true;
dataGridView1.Rows.Clear();
dataGridView1.Rows.Add(makeHeader, CarList[indexCar].Make);
dataGridView1.Rows.Add(modelHeader, CarList[indexCar].Model);
dataGridView1.Rows.Add(yearHeader, Convert.ToString(CarList[indexCar].Year));
dataGridView1.Rows.Add(bodyStyleHeader, CarList[indexCar].BodyStyle);
try
{
pictureBox1.Image = Image.FromFile(CarList[indexCar].Image);
}
catch
{
pictureBox1.Image = Properties.Resources.emptyImage;
}
}
public Form1()
{
InitializeComponent();
ChangeWorkMode(0);
dataGridView1.AllowUserToResizeColumns = false;
dataGridView1.AllowUserToResizeRows = false;
dataGridView1.AllowUserToAddRows = false;
openFileDialog1.Filter = "JPEG-files(*.jpg)|*.jpg";
GetCarList();
}
//Получаем информацию о выбранном автомобиле
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
button_DeleteCar.Enabled = false;
dataGridView1.Visible = true;
int count = listView1.SelectedItems.Count;
if (count == 0)
{
ChangeWorkMode(0);
dataGridView1.Rows.Clear();
pictureBox1.Image = null;
button_CancelChange.Enabled = false;
dataGridView1.Visible = false;
}
if (count == 1)
{
ChangeWorkMode(0);
indexCar = Convert.ToInt32(listView1.SelectedItems[0].Tag);
GetCarInfo(indexCar);
button_DeleteCar.Enabled = true;
}
if (count > 1)
{
ChangeWorkMode(3);
button_DeleteCar.Enabled = true;
dataGridView1.Visible = false;
}
}
//Запрещаем выделение ячеек первого столбца
private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
for (byte i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1[0, i].Selected) dataGridView1.ClearSelection();
}
}
//Кнопка добавления/изменения автомобиля
private void Button1_Click(object sender, EventArgs e)
{
//Режим редактирования данных
if (mode == 1 || mode == 2)
{
dataGridView1.ClearSelection();
try
{
bool error = false;
int year;
Int32.TryParse(dataGridView1[1, 2].Value.ToString(), out year);
string make = Convert.ToString(dataGridView1[1, 0].Value);
string model = Convert.ToString(dataGridView1[1, 1].Value);
string bodyStyle = Convert.ToString(dataGridView1[1, 3].Value);
string image = "";
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (Convert.ToString(dataGridView1.Rows[i].Cells[1].Value) == "")
{
dataGridView1.Rows[i].Cells[1].Style.BackColor = System.Drawing.Color.Red;
error = true;
}
}
if (error) throw new Exception("Заполнены не все поля");
if (year < 1884 || year > DateTime.Now.Year)
{
dataGridView1.Rows[2].Cells[1].Style.BackColor = System.Drawing.Color.Red;
throw new Exception($"Значение года должно быть в диапазоне от 1884 до {DateTime.Now.Year}");
}
if (mode == 1)
{
image = (pathNewImage != null) ? (pathNewImage) : ("");
CarList.Add(new Car(0, make, model, year, bodyStyle, image));
SaveIntoDatabase(make, model, year, bodyStyle, image);
}
if (mode == 2)
{
image = (pathNewImage != null) ? (pathNewImage) : (CarList[indexCar].Image);
CarList[indexCar].Id = CarList[indexCar].Id;
CarList[indexCar].Year = year;
CarList[indexCar].Make = make;
CarList[indexCar].Model = model;
CarList[indexCar].BodyStyle = bodyStyle;
CarList[indexCar].Image = image;
UpdateDatabase(CarList[indexCar].Id, CarList[indexCar].Make,
CarList[indexCar].Model, CarList[indexCar].Year,
CarList[indexCar].BodyStyle, CarList[indexCar].Image);
}
GetCarList();
dataGridView1.Rows.Clear();
pictureBox1.Image = null;
ChangeWorkMode(0);
return;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
//Перейти в режим добавления автомобиля
if (mode == 0 || mode == 3)
{
if (listView1.SelectedItems.Count > 0)
{
for (int i = 0; i < listView1.SelectedItems.Count; i++)
{
if (listView1.SelectedItems[i].Selected)
{
listView1.SelectedItems[i].Selected = false;
i--;
}
}
}
try
{
pictureBox1.Image = Properties.Resources.emptyImage;
}
catch
{
pictureBox1.Image = null;
}
dataGridView1.Rows.Clear();
dataGridView1.Rows.Add(makeHeader, "");
dataGridView1.Rows.Add(modelHeader, "");
dataGridView1.Rows.Add(yearHeader, "");
dataGridView1.Rows.Add(bodyStyleHeader, "");
dataGridView1.ClearSelection();
ChangeWorkMode(1);
}
}
//Выбор режима работы (редактирование/создание)
public void ChangeWorkMode(int _mode)
{
button_CancelChange.Enabled = false;
button_AddSaveCar.Text = "Добавить автомобиль";
button_DeleteCar.Text = "Удалить автомобиль";
button_CancelChange.Text = "Отменить изменения";
if (_mode == 0) //mode == 0 - просмотр;
{
mode = 0;
}
if (_mode == 1) //mode == 1 - создание;
{
mode = 1;
button_AddSaveCar.Text = "Сохранить";
button_CancelChange.Text = "Отменить";
button_CancelChange.Enabled = true;
dataGridView1.Visible = true;
}
if (_mode == 2) //mode == 2 - редактирование;
{
mode = 2;
button_AddSaveCar.Text = "Принять изменения";
button_CancelChange.Enabled = true;
}
if (_mode == 3) //mode == 3 - режим выбора нескольких позиций;
{
mode = 3;
button_DeleteCar.Text = "Удалить автомобили";
dataGridView1.Rows.Clear();
dataGridView1.ClearSelection();
pictureBox1.Image = null;
}
pathNewImage = null;
}
//Изменение значения параметра автомобиля
private void DataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
int index;
if (dataGridView1.SelectedCells.Count > 0)
{
index = Convert.ToInt32(dataGridView1.SelectedCells[0].RowIndex);
dataGridView1.Rows[index].Cells[1].Style.BackColor = System.Drawing.Color.White;
}
if (mode == 0)
{
ChangeWorkMode(2);
}
}
//Вывод подскази при наведении на изображение
private void PictureBox1_MouseEnter(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count == 0) return;
tempImage = pictureBox1.Image;
pictureBox1.Image = (mode == 1) ? (Properties.Resources.addImage) : (Properties.Resources.changeImage);
}
//Возвращение исходного изображения
private void PictureBox1_MouseLeave(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count == 0) return;
pictureBox1.Image = tempImage;
}
//Изменение изображения
private void PictureBox1_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count == 0) return;
if (openFileDialog1.ShowDialog() == DialogResult.Cancel) return;
if (mode == 0) ChangeWorkMode(2); //Перевод в режим редактирования
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
pathNewImage = openFileDialog1.FileName;
}
//Кнопка удаления автомобиля
private void Button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < listView1.SelectedItems.Count; i++)
{
if (listView1.SelectedItems[i].Selected)
{
indexCar = Convert.ToInt32(listView1.SelectedItems[i].Tag);
DeleteFromDatabase(CarList[indexCar].Id);
listView1.SelectedItems[i].Remove();
i--;
}
}
GetCarList();
ChangeWorkMode(0);
}
//Кнопка отмена изменений
private void Button3_Click(object sender, EventArgs e)
{
if (mode == 1)
{
pictureBox1.Image = null;
dataGridView1.Rows.Clear();
dataGridView1.Enabled = false;
}
if (mode == 2) GetCarInfo(indexCar);
ChangeWorkMode(0);
}
//Разблокируем dataGridView при добавлении строк
private void DataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
dataGridView1.Enabled = true;
}
}
}
|
using System;
using System.IO;
using Sibusten.Philomena.Api.Models;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace Sibusten.Philomena.Client.Images
{
public class PhilomenaImage : IPhilomenaImage
{
public ImageModel Model { get; private init; }
private readonly int _id;
public bool IsSvgImage => Model.Format == "svg";
public PhilomenaImage(ImageModel model)
{
if (model is null)
{
throw new ArgumentNullException(nameof(model));
}
if (model.Id is null)
{
throw new ArgumentNullException("Image is missing an ID", nameof(model.Id));
}
Model = model;
_id = model.Id.Value;
}
public string RawMetadata => JsonConvert.SerializeObject(Model);
public int Id => _id;
public string? Name
{
get
{
if (Model.ViewUrl is null)
{
return null;
}
string localPath = new Uri(Model.ViewUrl).LocalPath;
return Path.GetFileNameWithoutExtension(localPath);
}
}
public string? OriginalName
{
get
{
if (Model.Name is null)
{
return null;
}
return Path.GetFileNameWithoutExtension(Model.Name);
}
}
public string? ShortViewUrl => Model.Representations?.Full;
public string? ShortSvgViewUrl
{
get
{
if (ShortViewUrl is null)
{
return null;
}
// Modify the URL to point to the SVG image
string urlWithoutExtension = ShortViewUrl.Substring(0, ShortViewUrl.LastIndexOf('.'));
return urlWithoutExtension + ".svg";
}
}
public string? ViewUrl => Model.ViewUrl;
public string? SvgViewUrl
{
get
{
if (ViewUrl is null)
{
return null;
}
// Modify the URL to point to the SVG image
string urlWithoutExtension = ViewUrl.Substring(0, ViewUrl.LastIndexOf('.'));
return urlWithoutExtension + ".svg";
}
}
public string? Format
{
get
{
if (IsSvgImage)
{
// The image is an SVG image, which has two possible formats
// Assume rasters are always png, and return that as the format since rasters are what is presented to the booru user
return "png";
}
return Model.Format;
}
}
public int? FileSize => Model.Size;
public string? Hash => Model.Sha512Hash;
public string? OriginalHash => Model.OrigSha512Hash;
public List<string> TagNames => Model.Tags?.ToList() ?? new List<string>(); // .ToList to prevent editing the original model list
public List<int> TagIds => Model.TagIds?.ToList() ?? new List<int>(); // .ToList to prevent editing the original model list
public int? Score => Model.Score;
public string? SourceUrl => Model.SourceUrl;
public bool? IsSpoilered => Model.IsSpoilered;
public int? TagCount => Model.TagCount;
public bool? ThumbnailsGenerated => Model.ThumbnailsGenerated;
public DateTime? UpdatedAt => Model.UpdatedAt;
public string? Uploader => Model.Uploader;
public int? UploaderId => Model.UploaderId;
public int? Upvotes => Model.Upvotes;
public bool? Processed => Model.Processed;
public string? MimeType => Model.MimeType;
public bool? IsAnimated => Model.IsAnimated;
public double? AspectRatio => Model.AspectRatio;
public int? CommentCount => Model.CommentCount;
public DateTime? CreatedAt => Model.CreatedAt;
public string? DeletionReason => Model.DeletionReason;
public string? Description => Model.Description;
public int? Downvotes => Model.Downvotes;
public int? Width => Model.Width;
public int? DuplicateOf => Model.DuplicateOf;
public int? Faves => Model.Faves;
public DateTime? FirstSeenAt => Model.FirstSeenAt;
public int? Height => Model.Height;
public bool? IsHiddenFromUsers => Model.IsHiddenFromUsers;
public double? Duration => Model.Duration;
public double? WilsonScore => Model.WilsonScore;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio.Models.City.Map;
using Welic.Dominio.Models.City.Service;
using Welic.Dominio.Patterns.Repository.Pattern.Repositories;
using Welic.Dominio.Patterns.Service.Pattern;
namespace Services.City
{
public class ServiceCity :Service<CityMap>, IServiceCity
{
public ServiceCity(IRepositoryAsync<CityMap> repository) : base(repository)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ereditariea
{
class Program
{
static void Main(string[] args)
{
//BaseClass baseclass1 = new BaseClass();
DerivedClass derivedclass = new DerivedClass();
//BaseClass baseClass2 = new DerivedClass();
//DerivedClass derivedclass2 = new BaseClass(); error
//baseclass1.Method1();
//derivedclass.Method1();
//derivedclass.Method2();
//baseClass2.Method1();
//baseClass2.Method2(); error
derivedclass.Method1();
//derivedclass2.Method2(); //error
Console.ReadLine();
}
}
} |
using System;
using System.Windows.Forms;
namespace gView.Framework.UI.Dialogs
{
public partial class FormAddNetworkDirectory : Form
{
public FormAddNetworkDirectory()
{
InitializeComponent();
}
private void btnGetPath_Click(object sender, EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
dlg.SelectedPath = txtPath.Text;
if (dlg.ShowDialog() == DialogResult.OK)
{
txtPath.Text = dlg.SelectedPath;
}
}
public string Path
{
get { return txtPath.Text; }
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletKill : MonoBehaviour
{
void OnTriggerEnter (Collider kabe)
{
if (kabe.tag == "kabe")
{
Destroy (this.gameObject);
}
}
} |
using System.Collections.Generic;
namespace Boxofon.Web.Helpers
{
public interface IUrlHelper
{
string GetAbsoluteUrl(string path);
string GetAbsoluteUrl(string path, IDictionary<string, string> queryParameters);
}
} |
using OnboardingSIGDB1.Domain.Cargos.Dtos;
using OnboardingSIGDB1.Domain.Cargos.Validators;
using OnboardingSIGDB1.Domain.Interfaces;
using OnboardingSIGDB1.Domain.Notifications;
using System.Linq;
using System.Threading.Tasks;
namespace OnboardingSIGDB1.Domain.Cargos.Services
{
public class ArmazenadorDeCargo
{
private readonly IRepository<Cargo> _cargoRepository;
private readonly NotificationContext _notificationContext;
private readonly IValidadorDeCargoExistente _validadorDeCargoExistente;
public ArmazenadorDeCargo(IRepository<Cargo> cargoRepository,
NotificationContext notificationContext,
IValidadorDeCargoExistente validadorDeCargoExistente)
{
_cargoRepository = cargoRepository;
_notificationContext = notificationContext;
_validadorDeCargoExistente = validadorDeCargoExistente;
}
public async Task Armazenar(CargoDto cargoDto)
{
if (cargoDto.Id == 0)
await NovoCargo(cargoDto);
else
await EditarCargo(cargoDto);
}
public async Task NovoCargo(CargoDto cargoDto)
{
var cargo = new Cargo(cargoDto.Descricao);
if (!cargo.Valid)
{
_notificationContext.AddNotifications(cargo.ValidationResult);
return;
}
await _cargoRepository.Add(cargo);
}
public async Task EditarCargo(CargoDto cargoDto)
{
var cargoDatabase = (await _cargoRepository.Get(c => c.Id == cargoDto.Id)).FirstOrDefault();
_validadorDeCargoExistente.Valid(cargoDatabase);
if (_notificationContext.HasNotifications)
return;
cargoDatabase.AlterarDescricao(cargoDto.Descricao);
if (!cargoDatabase.Validate(cargoDatabase, new CargoValidator()))
{
_notificationContext.AddNotifications(cargoDatabase.ValidationResult);
return;
}
await _cargoRepository.Update(cargoDatabase);
}
}
}
|
using FirebirdSql.Data.FirebirdClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Projekt_3_Schichten_Architektur
{
public class Datenbankhaltung : IDatenhaltung
{
private FbConnection Connection;
public Datenbankhaltung()
{
FbConnectionStringBuilder connectionString = new FbConnectionStringBuilder();
connectionString.Database = Environment.CurrentDirectory + "\\Datenbank\\AUTORENBUECHER.FDB";
connectionString.Password = " ";
connectionString.UserID = "sysdba";
connectionString.ServerType = FbServerType.Embedded;
Connection = new FbConnection(connectionString.ToString());
}
~Datenbankhaltung()
{
if (Connection == null)
return;
if (Connection.State == System.Data.ConnectionState.Open)
{
try
{
Connection.Close();
}
catch (NullReferenceException n)
{
throw new NullReferenceException("Verbindung zur Datenbank konnte nicht beendet werden.", n);
}
}
}
public bool AktualisiereAutor(int ID, string Name)
{
if (string.IsNullOrEmpty(Name))
return false;
string statement = "UPDATE T_Autoren SET ";
statement += "Name = '" + Name + "' ";
statement += "WHERE ";
statement += "Autoren_id = " + ID + ";";
return StatementAusfuehren(statement);
}
public bool AktualisiereBuch(string ISBN, string Titel)
{
if (string.IsNullOrEmpty(Titel))
return false;
string statement = "UPDATE T_Buecher SET ";
statement += "Titel = '" + Titel + "' ";
statement += "WHERE ";
statement += "ISBN = '" + ISBN + "';";
Console.WriteLine(statement);
return StatementAusfuehren(statement);
}
public void VerbindungOeffnen()
{
if (Connection == null)
throw new NullReferenceException("Verbindung zur Datenbank fehlgechlagen.");
if (Connection.State != System.Data.ConnectionState.Open)
{
try
{
Connection.Open();
}
catch (NullReferenceException n)
{
throw new NullReferenceException("Verbindung zur Datenbank fehlgeschlagen.", n);
}
}
}
public List<Autor> GetAutoren()
{
VerbindungOeffnen();
string statement = "SELECT * " +
"FROM T_Autoren";
FbCommand reader = new FbCommand(statement, Connection);
FbDataAdapter adapter = new FbDataAdapter(reader);
DataSet Data = new DataSet();
adapter.FillSchema(Data, SchemaType.Source);
adapter.Fill(Data);
List<Autor> autoren = new List<Autor>();
foreach (DataRow item in Data.Tables[0].Rows)
{
autoren.Add(new Autor((int)item["Autoren_id"], item["Name"].ToString()));
}
return autoren;
}
public List<Buch> GetBuecher(int Autoren_id = 0)
{
VerbindungOeffnen();
string statement = "SELECT * " +
"FROM T_Buecher ";
if (Autoren_id > 0)
statement += "WHERE F_Autoren_id = " + Autoren_id;
FbCommand reader = new FbCommand(statement, Connection);
FbDataAdapter adapter = new FbDataAdapter(reader);
DataSet Data = new DataSet();
adapter.FillSchema(Data, SchemaType.Source);
adapter.Fill(Data);
List<Buch> buecher = new List<Buch>();
foreach (DataRow item in Data.Tables[0].Rows)
{
buecher.Add(new Buch(item["ISBN"].ToString(), item["Titel"].ToString()));
}
return buecher;
}
public bool LoescheAutor(int ID)
{
string statement = "DELETE FROM T_Autoren ";
statement += "WHERE Autoren_id = " + ID + ";";
return StatementAusfuehren(statement);
}
public bool LoescheBuch(string ISBN)
{
string statement = "DELETE FROM T_Buecher ";
statement += "WHERE ISBN = '" + ISBN + "';";
return StatementAusfuehren(statement);
}
public bool SpeichereAutor(string Name)
{
if (string.IsNullOrEmpty(Name))
return false;
string statement = "INSERT INTO T_Autoren ";
statement += "(Name) ";
statement += "VALUES ";
statement += "('" + Name + "');";
return StatementAusfuehren(statement);
}
public bool SpeichereBuch(int Autoren_id, string ISBN, string Titel)
{
if (string.IsNullOrEmpty(Titel))
return false;
string statement = "INSERT INTO T_Buecher ";
statement += "(F_Autoren_id, ISBN, Titel) ";
statement += "VALUES ";
statement += "(" + Autoren_id + ", '" + ISBN + "', '" + Titel + "');";
return StatementAusfuehren(statement);
}
private bool StatementAusfuehren(string Statement)
{
VerbindungOeffnen();
bool b = false;
FbCommand writer = null;
try
{
writer = new FbCommand(Statement, Connection, Connection.BeginTransaction());
writer.ExecuteNonQuery();
writer.Transaction.Commit();
b = true;
}
catch
{
writer?.Transaction?.Rollback();
}
finally
{
writer?.Connection?.Close();
}
return b;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Linq;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
namespace Kreczmerowka
{
[Serializable()]
public class Problems
{
public List<Problem> ListOfProblems { get; set; }
public static int Version { get; set; }
public static string Author { get; set; }
public static string Comment { get; set; }
public static DateTime Modified { get; set; }
public Problems()
{
ListOfProblems = new List<Problem>();
}
public bool LoadDatabase(string path)
{
try
{
ListOfProblems = QuestionDatabaseRepository.LoadFromFile(path).ToList();
}
catch (Exception exc)
{
MessageBox.Show("Wystąpił błąd podczas wczytywania pliku bazy:" + Environment.NewLine + exc.Message, "Kreczmerówka", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
return true;
}
public bool LoadDatabase(MemoryStream stream)
{
try
{
ListOfProblems = QuestionDatabaseRepository.LoadFromStream(stream).ToList();
}
catch (Exception exc)
{
MessageBox.Show("Wystąpił błąd podczas wczytywania pliku bazy:" + Environment.NewLine + exc.Message, "Kreczmerówka", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
return true;
}
public void SaveDatabase(string path)
{
try
{
QuestionDatabaseRepository.SaveToFile(path, ListOfProblems);
}
catch (Exception exc)
{
MessageBox.Show("Wystąpił błąd podczas zapisywania pliku bazy:" + Environment.NewLine + exc.Message, "Kreczmerówka", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void ShuffleQuestions()
{
Random rng = new Random();
int n = ListOfProblems.Count();
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
Problem value = ListOfProblems[k];
ListOfProblems[k] = ListOfProblems[n];
ListOfProblems[n] = value;
}
foreach (var item in ListOfProblems)
{
Random r = new Random();
int x = item.Questions.Count();
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
Question value = item.Questions[k];
item.Questions[k] = item.Questions[n];
item.Questions[n] = value;
}
}
}
public int Count()
{
return ListOfProblems.Count();
}
public Question GetQuestion(int problemId, int questionId)
{
return ListOfProblems[problemId].Questions[questionId];
}
}
}
|
using System;
namespace ApplicationServices.Interfaces
{
public interface ISecurityService
{
bool IsCurrentUserAdmin { get; }
string[] CurrentUserPermissions { get; }
}
}
|
namespace Sentry.Infrastructure;
/// <summary>
/// File logger used by the SDK to report its internal logging to a file.
/// </summary>
/// <remarks>
/// Primarily used to capture debug information to troubleshoot the SDK itself.
/// </remarks>
public class FileDiagnosticLogger : DiagnosticLogger
{
private readonly bool _alsoWriteToConsole;
private readonly StreamWriter _writer;
/// <summary>
/// Creates a new instance of <see cref="FileDiagnosticLogger"/>.
/// </summary>
/// <param name="path">The path to the file to write logs to. Will overwrite any existing file.</param>
/// <param name="alsoWriteToConsole">If <c>true</c>, will write to the console as well as the file.</param>
public FileDiagnosticLogger(string path, bool alsoWriteToConsole = false)
: this(path, SentryLevel.Debug, alsoWriteToConsole)
{
}
/// <summary>
/// Creates a new instance of <see cref="FileDiagnosticLogger"/>.
/// </summary>
/// <param name="path">The path to the file to write logs to. Will overwrite any existing file.</param>
/// <param name="minimalLevel">The minimal level to log.</param>
/// <param name="alsoWriteToConsole">If <c>true</c>, will write to the console as well as the file.</param>
public FileDiagnosticLogger(string path, SentryLevel minimalLevel, bool alsoWriteToConsole = false)
: base(minimalLevel)
{
var stream = File.OpenWrite(path);
_writer = new StreamWriter(stream);
_alsoWriteToConsole = alsoWriteToConsole;
AppDomain.CurrentDomain.ProcessExit += (_, _) =>
{
_writer.Flush();
_writer.Dispose();
};
}
/// <inheritdoc />
protected override void LogMessage(string message)
{
_writer.WriteLine(message);
if (_alsoWriteToConsole)
{
Console.WriteLine(message);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XH.Shared.Setting
{
/// <summary>
///
/// </summary>
public class WebSiteConfig : SiteConfig
{
}
} |
namespace Microsoft.UnifiedPlatform.Service.Common.Telemetry
{
public class MetricContext : LogContext
{
public string MetricName { get; set; }
public double Value { get; set; }
public MetricContext() : base() { }
public MetricContext(string metricName, double value, string correlationId, string transactionId, string source, string userId, string e2eTrackingId)
: base(TraceLevel.Metric, correlationId, transactionId, source, userId, e2eTrackingId)
{
MetricName = metricName;
Value = value;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Windows.Data;
namespace Beeffective.Converters
{
class TimeSpanToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string result = string.Empty;
if (value is TimeSpan timeSpan)
{
if (timeSpan.TotalDays > 1)
{
result += $"{timeSpan.Days}d ";
}
if (timeSpan.TotalHours > 1)
{
result += $"{timeSpan.Hours}h ";
}
if (timeSpan.TotalMinutes > 1)
{
result += $"{timeSpan.Minutes}m ";
}
if (timeSpan.TotalSeconds > 1)
{
result += $"{timeSpan.Seconds}s";
}
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
using System;
namespace oaggoc
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
Random random = new Random();
int[] a = new int[n];
for (int i = 0; i < a.Length; i++)
{
a[i] = random.Next();
}
foreach (var item in a)
{
Console.WriteLine(item);
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class Room : MonoBehaviour {
public int xIndex, zIndex;
public Color[] roomColors = new Color[5];
Level levelManager;
public string roomName = "Room Name Goes Here!";
// Use this for initialization
void Start () {
//print("Room " + xIndex + " : " + zIndex);
levelManager = transform.parent.parent.GetComponent<Level>();
// if(roomColors[0] != Color.black){
// //Set Color on Touch Icon
// }
}
// Update is called once per frame
void Update () {
}
}
|
using Hayaa.BaseModel;
using Hayaa.BaseModel.Model;
using Hayaa.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
namespace Hayaa.CompanyWebSecurity.Client
{
public class UserAuthorityFilterAttribute : ActionFilterAttribute
{
/// <summary>
/// 仅支持form格式数据提交
/// </summary>
/// <param name="context"></param>
public override void OnActionExecuting(ActionExecutingContext context)
{
var request = context.HttpContext.Request;
bool isPost = request.Method.ToLower().Equals("post");
bool isJson = request.Headers.Values.Contains("application/json, text/plain, */*");
var urlParamater = new Dictionary<string, string>();
var requestFrom = context.HttpContext.Request.Form;
var requestQuery= context.HttpContext.Request.Query;
String token = isPost?requestFrom["authtoken"]: requestQuery["authtoken"];
String path = context.HttpContext.Request.Path;
int userId = UserSecurityProvider.BaseAuth(token);
Boolean baseAuth = userId > 0;
if (!baseAuth)
{
context.Result = new JsonResult(new TransactionResult<bool>()
{
Data = false,
Code = ErrorCode.LoginFail,
Message = "未登陆"
});
return;
}
Boolean configResult = (userId > 0) ? UserSecurityProvider.PermissionAuth(userId, path, userId > 0) : false;
if (!configResult)
{
context.Result = new JsonResult(new TransactionResult<bool>()
{
Data = false,
Code = ErrorCode.NoPermission,
Message = "未授权"
});
}
}
}
}
|
using System;
using Utilities;
namespace EddiEvents
{
[PublicAPI]
public class DropshipDeploymentEvent : Event
{
public const string NAME = "Dropship deployment";
public const string DESCRIPTION = "Triggered when exiting a military dropship at an on-foot conflict zone";
public const string SAMPLE = "{ \"timestamp\":\"2021-05-25T04:03:12Z\", \"event\":\"DropshipDeploy\", \"StarSystem\":\"HIP 61072\", \"SystemAddress\":1694104586603, \"Body\":\"HIP 61072 A 3 a\", \"BodyID\":21, \"OnStation\":false, \"OnPlanet\":true }";
[PublicAPI("The name of the star system where the commander is deployed")]
public string systemname { get; }
[PublicAPI("The name of the body where the commander is deployed")]
public string bodyname { get; private set; }
// Not intended to be user facing
public ulong systemAddress { get; }
public int? bodyId { get; }
public DropshipDeploymentEvent(DateTime timestamp, string system, ulong systemAddress, string body, int? bodyId) : base(timestamp, NAME)
{
this.systemname = system;
this.systemAddress = systemAddress;
this.bodyname = body;
this.bodyId = bodyId;
}
}
} |
using Microsoft.EntityFrameworkCore.Migrations;
namespace HomeBaseCore.Migrations
{
public partial class AddRootFolderID : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "RootFolderID",
table: "folders",
nullable: false,
defaultValue: 0);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RootFolderID",
table: "folders");
}
}
}
|
using Anywhere2Go.DataAccess.Entity;
using Anywhere2Go.DataAccess.Object;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace Claimdi.Account.Models
{
public class TaskViewModel
{
public TaskPicture TaskPicture { get; set; }
public List<TaskPicture> TaskPictureHistory { get; set; }
}
public class SurveyorModel
{
public Guid accId { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string gender { get; set; }
public string tel { get; set; }
public string address { get; set; }
public string email { get; set; }
public string picture { get; set; }
public string distance { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public bool? IsOnline { get; set; }
public bool IsWorking { get; set; }
public string lastUpdate { get; set; }
public string depName { get; set; }
public string rankId { get; set; }
public List<SurveyorJobModel> Task { get; set; }
}
public class SurveyorJobModel
{
public string taskId { get; set; }
public string informerName { get; set; }
public string informerTel { get; set; }
public string note { get; set; }
public DateTime? scheduleDate { get; set; }
public string schedulePlance { get; set; }
public string scheduleLatitude { get; set; }
public string scheduleLongitude { get; set; }
public string taskType { get; set; }
}
public class TaskModel
{
public Task model { get; set; }
public string reassignComment { get; set; }
public string editAppointmentComment { get; set; }
public string cancelComment { get; set; }
}
public class TaskCalendarModel
{
public class Index
{
public string DevId { get; set; }
}
public class CalenderElement
{
public string key { get; set; }
public string label { get; set; }
public bool open { get; set; }
public List<Children> children { get; set; }
}
public class Children
{
public string key { get; set; }
public string label { get; set; }
public string tel { get; set; }
public string location { get; set; }
}
public class CalendarTask
{
public string id { get; set; }
public string start_date { get; set; }
public string end_date { get; set; }
public string text { get; set; }
public bool isChange { get; set; }
public string section_id { get; set; }
public string name { get; set; }
public string tel { get; set; }
public string car_brand { get; set; }
public string location { get; set; }
public string lat { get; set; }
public string lng { get; set; }
public string status_name { get; set; }
public string task_process_id { get; set; }
}
public class CalendarSave
{
public string task_id { get; set; }
public string section_id { get; set; }
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DBDiff.Schema.Model;
namespace DBDiff.Schema.SQLServer.Generates.Model
{
public class Roles : SchemaList<Role, Database>
{
public Roles(Database parent)
: base(parent)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace UI.Entidades
{
public class SaldoEvento
{
public decimal id_participante { get; set; }
public decimal id_evento { get; set; }
public string nombre_evento { get; set; }
public string fecha_inscripcion { get; set; }
public decimal valor { get; set; }
public decimal monto_total_evento { get; set; }
public decimal monto_abonado { get; set; }
public decimal saldo_pendiente { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace MyNurserySchool.Models
{
public class Class
{
#region Parameteres
public int Id { get; set; }
public string Name { get; set; }
public int Capacity { get; set; }
public Employee ClassTeacher { get; set; }
public string Description { get; set; }
public virtual ICollection<Child> Children { get; set; }
[ForeignKey("Nursery")]
public int? NurseryId { get; set; }
public DateTime Created { get; set; }
public string CreatedBy { get; set; }
public DateTime Modified { get; set; }
public string ModifiedBy { get; set; }
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Herança
{
class Professor:Pessoa
{
private float salario;
public float Salario
{
get
{
return salario;
}
set
{
salario = value;
}
}
public Professor(string nome,int idade,float salarioc)
{
this.Nome = nome;
this.Idade = idade;
this.Salario = salario;
}
}
}
|
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using FiiiCoin.Business;
using FiiiCoin.Models;
using FiiiCoin.Utility;
using FiiiCoin.Utility.Api;
using McMaster.Extensions.CommandLineUtils;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace FiiiCoin.Miner
{
class Program
{
static void Main(string[] args)
{
Run(args);
//string userCommand = "";
//while (userCommand.ToLower() != "exit")
//{
// userCommand = Console.ReadLine();
// string[] input = userCommand.Split(" ");
// Run(input);
//}
//Console.ReadKey();
}
static void Run(string[] args)
{
var app = new CommandLineApplication(false);
app.HelpOption("-?|-h|--help");
app.OnExecute(() =>
{
app.ShowHelp();
return;
});
app.Command("mining", command =>
{
command.Description = "begin mining";
command.HelpOption("-?|-h|--help");
CommandArgument nameArgument = command.Argument("[minerName]", "minerName");
CommandArgument addressArgument = command.Argument("[walletAddress]", "walletAddress");
command.OnExecute(async () =>
{
if (nameArgument != null && !string.IsNullOrEmpty(nameArgument.Value) && addressArgument != null && !string.IsNullOrEmpty(addressArgument.Value))
{
string name = nameArgument.Value;
string address = addressArgument.Value;
Program program = new Program();
BlockChainStatus chainStatus = await program.GetChainStatus();
if (chainStatus == null)
{
app.Out.WriteLine("there is something wrong with the api, you should check the fiiichain");
return;
}
//验证本地区块高度和网络区块高度
ApiResponse response = await NetworkApi.GetBlockChainInfo();
if (!response.HasError)
{
BlockChainInfo info = response.GetResult<BlockChainInfo>();
if (info.IsRunning)
{
if (info.RemoteLatestBlockHeight <= info.LocalLastBlockHeight)
{
command.Out.WriteLine($"current network is {chainStatus.ChainNetwork}");
//validate wallet address
if (AddressTools.AddressVerfy(chainStatus.ChainNetwork, address))
{
command.Out.WriteLine($"address verify success. prepare to mine");
await BlockMining.MiningAsync(name, address);
}
else
{
command.Out.WriteLine($"address verify fail. address: {address} is invalid");
return;
}
}
else
{
command.Out.WriteLine("Block Chain is in sync, please try it later");
return;
}
}
else
{
command.Out.WriteLine("Block Chain has stopped");
return;
}
}
else
{
command.Out.WriteLine(response.Error.Message);
return;
}
}
else
{
command.ShowHelp();
return;
}
});
});
app.Command("height", command =>
{
command.Description = "view current block height";
command.OnExecute(async () =>
{
Program program = new Program();
BlockChainStatus chainStatus = await program.GetChainStatus();
if (chainStatus == null)
{
app.Out.WriteLine("there is something wrong with the api, you should check the fiiichain");
return;
}
ApiResponse response = await BlockChainEngineApi.GetBlockCount();
if (!response.HasError)
{
long result = response.GetResult<long>();
command.Out.WriteLine($"current block height is {result}");
}
else
{
command.Out.WriteLine($"{response.Error.Message}");
}
});
});
app.Command("balance", command =>
{
command.Description = "view wallet balance";
command.OnExecute(async () =>
{
Program program = new Program();
BlockChainStatus chainStatus = await program.GetChainStatus();
if (chainStatus == null)
{
app.Out.WriteLine("there is something wrong with the api, you should check the fiiichain");
return;
}
ApiResponse response = await UtxoApi.GetTxOutSetInfo();
if (!response.HasError)
{
TxOutSet set = response.GetResult<TxOutSet>();
command.Out.WriteLine($"wallet balance is :{set.Total_amount}");
}
});
});
app.Command("transaction", command =>
{
command.Description = "view recent transaction record(default 5 content)";
CommandArgument recordArgument = command.Argument("[count]", "record content");
command.OnExecute(async () =>
{
if (recordArgument != null && !string.IsNullOrEmpty(recordArgument.Value))
{
if (int.TryParse(recordArgument.Value, out int count))
{
Program program = new Program();
BlockChainStatus chainStatus = await program.GetChainStatus();
if (chainStatus == null)
{
app.Out.WriteLine("there is something wrong with the api, you should check the fiiichain");
return;
}
ApiResponse response = await TransactionApi.ListTransactions("*", count);
if (!response.HasError)
{
List<Payment> result = response.GetResult<List<Payment>>();
if (result != null && result.Count > 0)
{
command.Out.WriteLine("recent transaction record blow:");
foreach (var item in result)
{
//time(需要转换为DataTime), comment, amount
string time = new DateTime(1970, 1, 1).AddMilliseconds(item.Time).ToString("yyyy-MM-dd HH:mm:ss");
command.Out.WriteLine($"Time:{time}; Comment:{item.Comment}; Amount:{item.Amount}");
}
}
else
{
command.Out.WriteLine("no recent transaction record.");
}
}
}
else
{
command.ShowHelp();
}
}
else
{
Program program = new Program();
BlockChainStatus chainStatus = await program.GetChainStatus();
if (chainStatus == null)
{
app.Out.WriteLine("there is something wrong with the api, you should check the fiiichain");
return;
}
ApiResponse response = await TransactionApi.ListTransactions();
if (!response.HasError)
{
List<Payment> result = response.GetResult<List<Payment>>();
if (result != null && result.Count > 0)
{
command.Out.WriteLine("recent transaction record blow:");
foreach (var item in result)
{
//time(需要转换为DataTime), comment, amount
string time = new DateTime(1970, 1, 1).AddMilliseconds(item.Time).ToString("yyyy-MM-dd HH:mm:ss");
command.Out.WriteLine($"Time:{time}; Comment:{item.Comment}; Amount:{item.Amount}");
}
}
else
{
command.Out.WriteLine("no recent transaction record.");
}
}
}
});
});
/*
if (args.Length > 1 && args[0].ToLower() == "fiiipay" && IsContainsCommand(args[1]))
{
List<string> list = new List<string>(args);
list.RemoveAt(0);
app.Execute(list.ToArray());
}
*/
if (args != null && args.Length > 0 && IsContainsCommand(args[0]))
{
app.Execute(args);
}
else
{
app.Execute(new[] { "-?" });
}
}
public static bool IsContainsCommand(string key)
{
string command = "mining|height|balance|transaction";
string[] commandArray = command.Split('|');
foreach (string item in commandArray)
{
if (item == key.ToLower())
{
return true;
}
}
return false;
}
public async Task<BlockChainStatus> GetChainStatus()
{
ApiResponse api = await BlockChainEngineApi.GetBlockChainStatus();
if (!api.HasError)
{
return api.GetResult<BlockChainStatus>();
}
else
{
return null;
}
}
}
}
|
/* The MIT License (MIT)
*
* Copyright (c) 2018 Marc Clifton
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/* Code Project Open License (CPOL) 1.02
* https://www.codeproject.com/info/cpol10.aspx
*/
using System;
using System.Collections.Generic;
using System.Linq;
namespace Clifton.Meaning
{
public class Relationships
{
public int Count => relationships.Count;
public IReadOnlyList<RelationshipDeclaration> RelationshipDeclarations => relationships.AsReadOnly();
protected List<RelationshipDeclaration> relationships = new List<RelationshipDeclaration>();
public RelationshipDeclaration Add<R, T, S>(string label = null)
where R : IRelationship
where T : IEntity
where S : IEntity
{
var rel = RelationshipDeclaration.Create<R, T, S>(label);
relationships.Add(rel);
return rel;
}
/*
/// <summary>
/// Returns true if the target entity type has a null relationship.
/// It can also have other relationships, but it must have one null relationship to be a root type.
/// </summary>
public bool IsRoot(Type entityType)
{
return relationships.Any(r => r.TargetType == entityType && r.RelationshipType == typeof(NullRelationship));
}
*/
/// <summary>
/// Returns true if the specified relationship between the target and source exists.
/// </summary>
public bool Exists<R, T, S>()
where R : IRelationship
where T : IEntity
where S : IEntity
{
return relationships.Any(r =>
r.RelationshipType == typeof(R) &&
r.TargetType == typeof(T) &&
r.SourceType == typeof(S)
);
}
public bool Exists<R>(IEntity target, IEntity source) where R : IRelationship
{
// TODO: Need to handle "and" relationship to entity type.
return relationships.Any(r =>
r.RelationshipType == typeof(R) &&
r.TargetType == target.GetType() &&
(
r.SourceType == source.GetType() ||
r.OrSourceTypes.Any(ot => ot == source.GetType())) ||
r.AndSourceTypes.Any(ot=>ot==source.GetType())
);
}
public bool Validate<R>(IEntity target, IEntity source, List<ContextEntity> entities, out int min, out int count)
{
min = 0;
count = 0;
bool ret = true;
var relationshipsToCheck = relationships.
Where(r =>
r.RelationshipType == typeof(R) &&
r.TargetType == target.GetType() &&
(r.SourceType == source.GetType() || r.OrSourceTypes.Any(ot => ot == source.GetType())));
foreach (var rcheck in relationshipsToCheck)
{
var possibleRelatedToTypes = new List<Type>() { rcheck.SourceType };
possibleRelatedToTypes.AddRange(rcheck.OrSourceTypes);
var entitiesInThisRelationship = entities.Where(e =>
e.RelationshipType == typeof(R) &&
e.ConcreteEntity == target &&
possibleRelatedToTypes.Any(rt => rt == e.RelatedTo.GetType()));
count = entitiesInThisRelationship.Count();
if (rcheck.Minimum > count || count > rcheck.Maximum)
{
min = rcheck.Minimum;
ret = false;
break;
}
}
return ret;
}
public bool Validate(ContextEntity ce, List<ContextEntity> entities)
{
bool ret = ValidateOrRelationships(ce, entities);
if (ret)
{
ret &= ValidateAndRelationships(ce, entities);
}
return ret;
}
protected bool ValidateOrRelationships(ContextEntity ce, List<ContextEntity> entities)
{
bool ret = true;
var relationshipsToCheck = relationships.
Where(r =>
r.RelationshipType == ce.RelationshipType &&
r.TargetType == ce.ConcreteEntity.GetType() &&
(r.SourceType == ce.RelatedTo.GetType() || r.OrSourceTypes.Any(ot=>ot == ce.RelatedTo.GetType())));
foreach (var rcheck in relationshipsToCheck)
{
var possibleRelatedToTypes = new List<Type>() { rcheck.SourceType };
possibleRelatedToTypes.AddRange(rcheck.OrSourceTypes);
var entitiesInThisRelationship = entities.Where(e =>
e.RelationshipType == ce.RelationshipType &&
e.ConcreteEntity == ce.ConcreteEntity &&
possibleRelatedToTypes.Any(rt => rt == ce.RelatedTo.GetType()));
int count = entitiesInThisRelationship.Count();
if (rcheck.Minimum > count || count > rcheck.Maximum)
{
ret = false;
break;
}
}
return ret;
}
protected bool ValidateAndRelationships(ContextEntity ce, List<ContextEntity> entities)
{
bool ret = true;
// All relationships of the relationshtype having the same target must match the "and" requirements.
var relationshipsToCheck = relationships.
Where(r =>
r.RelationshipType == ce.RelationshipType &&
r.TargetType == ce.ConcreteEntity.GetType());
foreach (var rcheck in relationshipsToCheck)
{
if (rcheck.AndSourceTypes.Count > 0)
{
var requiredRelatedToTypes = new List<Type>() { rcheck.SourceType };
requiredRelatedToTypes.AddRange(rcheck.AndSourceTypes);
var entitiesInThisRelationship = entities.Where(e =>
e.RelationshipType == ce.RelationshipType &&
e.ConcreteEntity == ce.ConcreteEntity &&
requiredRelatedToTypes.Any(rt => rt == ce.RelatedTo.GetType()));
ret = entitiesInThisRelationship.Count() == requiredRelatedToTypes.Count;
if (!ret)
{
ret = false;
break;
}
}
}
return ret;
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
//using System.Linq;
class MessageBaseInstance : MessageBase {
public string networkmsg = "";
}
class InstanceMsgTypes {
public static short PLAYER_REQUEST_INFO = 1001;
public static short SERVER_RESPONSE_INFO = 1002;
public static short PLAYER_REQUEST_MM = 1003;
public static short SERVER_RESPONE_MM = 1004;
public static short INSTANCE_REQUEST_PORT = 1007;
public static short SERVER_RESPONE_PORT = 1008;
public static short INSTANCE_BROADCAST = 1013;
};
public class Instanceserver : MonoBehaviour {
NetworkClient Client;
bool Connected = false;
bool DestroyCheck = false;
// Use this for initialization
void Start () {
ConnectToMasterServer ();
}
// Update is called once per frame
void Update () {
if (Client != null) {
if (Client.isConnected != false && Connected == false) {
RequestPort ();
Connected = true;
}
if (Client.isConnected == false && Connected == true) {
Connected = false;
}
if (NetworkServer.connections.Count == 0 && DestroyCheck == false) {
StartCoroutine (AutoDestroy());
}
if (Client.isConnected == true) {
NetworkServer.RegisterHandler (InstanceMsgTypes.SERVER_RESPONE_PORT, ReadNetworkMessage);
}
}
}
public void ConnectToMasterServer(){
string IpAddress = "127.0.0.1";
int port = 49001;
Client = new NetworkClient ();
Client.Connect (IpAddress, port);
}
void RequestPort(){
string info = "@REQUEST_INSTANCE_PORT";
var messageb = new MessageBaseClient ();
messageb.networkmsg = info;
Client.Send (InstanceMsgTypes.INSTANCE_REQUEST_PORT,messageb);
}
void CreateInstaceServer(int port){
NetworkServer.Listen (port);
}
IEnumerator AutoDestroy(){
DestroyCheck = true;
int clientcount = 0;
yield return new WaitForSeconds (600);
if(NetworkServer.connections.Count == 0) {
Application.Quit ();
Debug.Log ("Application Close");
}
DestroyCheck = false;
}
public void ReadNetworkMessage (NetworkMessage netmsg){
string rcvmsg = "";
int port;
MessageBaseLoginServer messageb = netmsg.ReadMessage<MessageBaseLoginServer>();
rcvmsg = messageb.networkmsg.ToString ();
if (rcvmsg.StartsWith ("@RESPONE_INSTACE_PORT")) {
rcvmsg = rcvmsg.Substring (rcvmsg.IndexOf ("#"));
rcvmsg = rcvmsg.Substring (1);
port = int.Parse (rcvmsg);
CreateInstaceServer (port);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HaiLangThreeCountriesKill.Models;
using NHibernate;
using NHibernate.Criterion;
namespace HaiLangThreeCountriesKill.Managers
{
class UserManager : IUserManager
{
/// <summary>
/// 添加用户
/// </summary>
/// <param name="user"></param>
public void Add(User user)
{
using (ISession session = NHibernateHelper.OpenSession())
{
//对数据库操作需要事务
using (ITransaction transaction = session.BeginTransaction())
{
try
{
session.Save(user);
transaction.Commit();
}
catch (Exception e)
{
transaction.Rollback();
Console.WriteLine(e);
}
}
}
}
/// <summary>
/// 删除用户
/// </summary>
/// <param name="user"></param>
public void Delete(User user)
{
using (ISession session = NHibernateHelper.OpenSession())
{
//对数据库操作需要事务
using (ITransaction transaction = session.BeginTransaction())
{
try
{
session.Delete(user);
transaction.Commit();
}
catch (Exception e)
{
transaction.Rollback();
Console.WriteLine(e);
}
}
}
}
/// <summary>
/// 获取所有用户
/// </summary>
/// <returns></returns>
public IList<User> GetAllUsers()
{
IList<User> users = null;
using (ISession session = NHibernateHelper.OpenSession())
{
users = session.CreateCriteria<User>().List<User>();//对话创建条件,列出所有用户
}
return users;
}
/// <summary>
/// 根据Id获取用户
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public User GetById(int id)
{
User user = null;
using (ISession session = NHibernateHelper.OpenSession())
{
user = session.Get<User>(id);//根据id获取用户
}
return user;
}
/// <summary>
/// 根据名字获取用户
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
public User GetByUsername(string username)
{
User user = null;
using (ISession session = NHibernateHelper.OpenSession())
{
//对话,创建条件,添加限制参数,获取唯一返回值(如果返回值有多个会报错)
user = session.CreateCriteria<User>().Add(Restrictions.Eq("Username", username)).UniqueResult<User>();
}
return user;
}
/// <summary>
/// 更新用户
/// </summary>
/// <param name="user"></param>
public void Update(User user)
{
using (ISession session = NHibernateHelper.OpenSession())
{
//操作数据库需要事务
using (ITransaction transaction = session.BeginTransaction())
{
try
{
session.Update(user);
transaction.Commit();
}
catch (Exception e)
{
transaction.Rollback();
Console.WriteLine(e);
}
}
}
}
}
}
|
// Utility.cs
//
using System;
using System.Collections;
using System.Html;
using System.Runtime.CompilerServices;
using jQueryApi;
namespace SportsLinkScript.Shared.Html
{
[IgnoreNamespace]
[Imported]
public sealed class H5ScriptElement : Element
{
public string ReadyState;
public string Src;
public string Type;
public bool Async;
}
}
|
using PhotonInMaze.Common.Controller;
using PhotonInMaze.Common.Flow;
using PhotonInMaze.Provider;
using UnityEngine;
namespace PhotonInMaze.GameCamera {
internal class CameraConfiguration : FlowBehaviour {
[SerializeField]
[Range(0.5f, 2f)]
private float cameraSpeed;
internal float CameraSpeed { get { return cameraSpeed * 0.15f; } }
[SerializeField]
[Range(0.5f, 2f)]
private float swipeIntensive = 1f;
internal float SwipeIntensive { get { return swipeIntensive * 0.5f; } }
[SerializeField]
[Range(0.5f, 2f)]
private float pinchIntensive = 1f;
internal float PinchIntensive { get { return pinchIntensive * 0.01f; } }
internal const float offsetCam = 2f;
internal readonly float minCameraYPosition = 10f;
internal GameCameraType type;
internal bool followThePhoton;
internal float initialOrtographicSize;
internal Vector3 initialCameraPosition;
public override void OnInit() {
type = GameCameraType.Area;
followThePhoton = false;
Camera camera = GetComponent<Camera>();
IMazeConfiguration mazeConfiguration = MazeObjectsProvider.Instance.GetMazeConfiguration();
float ratio = (float)Screen.width / Screen.height;
float x = mazeConfiguration.Columns * 2f - mazeConfiguration.CellSideLength / 2;
float z = mazeConfiguration.Rows * 2f - mazeConfiguration.CellSideLength / 2;
camera.transform.position = initialCameraPosition = new Vector3(x, 50, z);
float sizeForLongerColumnsLength = mazeConfiguration.Columns * (mazeConfiguration.CellSideLength / 2);
float sizeForLongerRowsLength = mazeConfiguration.Rows * (mazeConfiguration.CellSideLength / 2);
initialOrtographicSize = sizeForLongerColumnsLength * ratio > sizeForLongerRowsLength ?
sizeForLongerColumnsLength : sizeForLongerRowsLength;
camera.orthographicSize = initialOrtographicSize += offsetCam;
CameraViewCalculator calculator = new CameraViewCalculator(camera);
camera.fieldOfView = calculator.CalculateFOV(initialOrtographicSize, camera.transform.position.y);
camera.orthographic = true;
}
public override int GetInitOrder() {
return (int) InitOrder.CameraConfiguration;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[Serializable]
public class PlayerData
{
[SerializeField]
private string _nameSave = "save"; // name of the save state
[SerializeField]
private SaveTime _timeOfSaveState;
[SerializeField]
private SavePlayerInfos _savePlayerInfos;
[SerializeField]
private SaveSettings _saveSettingsPlayer;
[SerializeField]
private bool isAutoSave = false;
public PlayerData() {}
public PlayerData(SavePlayerInfos savePlayerInfos, SaveSettings saveSettings, SaveTime timeOfSaveState)
{
_savePlayerInfos = savePlayerInfos;
_saveSettingsPlayer = saveSettings;
_timeOfSaveState = timeOfSaveState;
}
public SavePlayerInfos SavePlayerInfos
{
get
{
return _savePlayerInfos;
}
set
{
_savePlayerInfos = value;
}
}
public SaveSettings SaveSettingsPlayer
{
get
{
return _saveSettingsPlayer;
}
set
{
_saveSettingsPlayer = value;
}
}
public string NameSave
{
get
{
return _nameSave;
}
set
{
_nameSave = value;
}
}
public SaveTime TimeOfSaveState
{
get
{
return _timeOfSaveState;
}
set
{
_timeOfSaveState = value;
}
}
public bool IsAutoSave
{
get
{
return isAutoSave;
}
set
{
isAutoSave = value;
}
}
}//class |
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PrismPopupSample.ViewModels
{
public class MainPageViewModel : BindableBase, INavigatingAware
{
private INavigationService _navigationService { get; }
public DelegateCommand LaunchPopupCommand { get; }
public MainPageViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
LaunchPopupCommand = new DelegateCommand(OnLaunchPopupCommandExecuted);
}
private async void OnLaunchPopupCommandExecuted() =>
await _navigationService.NavigateAsync("MainPage/PopupSamplePage");
public void OnNavigatingTo(INavigationParameters parameters)
{
}
}
}
|
using GatewayEDI.Logging.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Configuration;
namespace GatewayEDI.Logging.UnitTests
{
/// <summary>
///This is a test class for FactoryConfigurationCollectionTest and is intended
///to contain all FactoryConfigurationCollectionTest Unit Tests
///</summary>
[TestClass()]
public class FactoryConfigurationCollectionTest
{
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//Use ClassCleanup to run code after all tests in a class have run
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion
/// <summary>
///A test for FactoryConfigurationCollection Constructor
///</summary>
[TestMethod()]
public void FactoryConfigurationCollectionConstructorTest()
{
FactoryConfigurationCollection target = new FactoryConfigurationCollection();
Assert.Inconclusive("TODO: Implement code to verify target");
}
/// <summary>
///A test for BaseAdd
///</summary>
[TestMethod()]
[DeploymentItem("GatewayEDI.Logging.dll")]
public void BaseAddTest()
{
FactoryConfigurationCollection_Accessor target = new FactoryConfigurationCollection_Accessor(); // TODO: Initialize to an appropriate value
ConfigurationElement element = null; // TODO: Initialize to an appropriate value
target.BaseAdd(element);
Assert.Inconclusive("A method that does not return a value cannot be verified.");
}
/// <summary>
///A test for CreateNewElement
///</summary>
[TestMethod()]
[DeploymentItem("GatewayEDI.Logging.dll")]
public void CreateNewElementTest()
{
FactoryConfigurationCollection_Accessor target = new FactoryConfigurationCollection_Accessor(); // TODO: Initialize to an appropriate value
ConfigurationElement expected = null; // TODO: Initialize to an appropriate value
ConfigurationElement actual;
actual = target.CreateNewElement();
Assert.AreEqual(expected, actual);
Assert.Inconclusive("Verify the correctness of this test method.");
}
/// <summary>
///A test for GetElementKey
///</summary>
[TestMethod()]
[DeploymentItem("GatewayEDI.Logging.dll")]
public void GetElementKeyTest()
{
FactoryConfigurationCollection_Accessor target = new FactoryConfigurationCollection_Accessor(); // TODO: Initialize to an appropriate value
ConfigurationElement element = null; // TODO: Initialize to an appropriate value
object expected = null; // TODO: Initialize to an appropriate value
object actual;
actual = target.GetElementKey(element);
Assert.AreEqual(expected, actual);
Assert.Inconclusive("Verify the correctness of this test method.");
}
/// <summary>
///A test for Item
///</summary>
[TestMethod()]
public void ItemTest()
{
FactoryConfigurationCollection target = new FactoryConfigurationCollection(); // TODO: Initialize to an appropriate value
int index = 0; // TODO: Initialize to an appropriate value
FactoryConfigurationElement actual;
actual = target[index];
Assert.Inconclusive("Verify the correctness of this test method.");
}
}
}
|
using System;
namespace AnalogDisplay
{
/// <summary>
/// Summary description for Adapter.
/// </summary>
public class Adapter
{
protected HardwareDevice device;
protected string name;
protected double currValue;
public Adapter()
{
//
// TODO: Add constructor logic here
//
}
public Adapter(string aname)
{
name = aname;
}
public double CurrentValue
{
get
{
return currValue;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public HardwareDevice Device
{
get
{
return device;
}
set
{
device = value;
}
}
public virtual void SetDeviceValue (double input)
{
// by default, pass cast value straight into hardware device
currValue = input;
device.HardwareValue = TranslateValue(input);
}
public virtual int TranslateValue (double input)
{
return (int) input;
}
}
}
|
using BenchmarkDotNet.Attributes;
using Sentry.Extensibility;
namespace Sentry.Benchmarks;
public class StackFrameBenchmarks
{
private SentryOptions _options = new();
private SentryStackFrame[] data;
[Params(1000)]
public int N;
[GlobalSetup]
public void Setup()
{
data = new SentryStackFrame[N];
var rand = new Random(42);
for (var i = 0; i < N; i++)
{
var proto = _framePrototypes[rand.NextInt64(0, _framePrototypes.Length)];
data[i] = new()
{
Function = proto.Function,
Module = rand.NextSingle() < 0.5 ? null : proto.Module
};
}
}
[IterationCleanup]
public void IterationCleanup()
{
for (var i = 0; i < N; i++)
{
data[i].InApp = null;
}
}
[Benchmark]
public void ConfigureAppFrame()
{
for (var i = 0; i < N; i++)
{
data[i].ConfigureAppFrame(_options);
}
}
// These are real frames captured by a profiler session on Sentry.Samples.Console.Customized.
private SentryStackFrame[] _framePrototypes = new SentryStackFrame[] {
new SentryStackFrame() {
Function ="System.Threading.Monitor.Wait(class System.Object,int32)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.ManualResetEventSlim.Wait(int32,value class System.Threading.CancellationToken)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task.SpinThenBlockingWait(int32,value class System.Threading.CancellationToken)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task.InternalWaitCore(int32,value class System.Threading.CancellationToken)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(class System.Threading.Tasks.Task)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.TaskAwaiter.GetResult()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="System.Threading.LowLevelLifoSemaphore.WaitForSignal(int32)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.LowLevelLifoSemaphore.Wait(int32,bool)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.PortableThreadPool+WorkerThread.WorkerThreadStart()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Thread.StartCallback()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.WaitHandle.WaitOneNoCheck(int32)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.WaitHandle.WaitOne(int32)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.PortableThreadPool+GateThread.GateThreadStart()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.IO.Pipes.PipeStream.ReadCore(value class System.Span`1<unsigned int8>)",
Module ="System.IO.Pipes.il"
},
new SentryStackFrame() {
Function ="System.IO.Pipes.PipeStream.Read(unsigned int8[],int32,int32)",
Module ="System.IO.Pipes.il"
},
new SentryStackFrame() {
Function ="System.IO.BinaryReader.ReadBytes(int32)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="Microsoft.Diagnostics.NETCore.Client.IpcHeader.Parse(class System.IO.BinaryReader) {QuickJitted}",
Module ="Microsoft.Diagnostics.NETCore.Client"
},
new SentryStackFrame() {
Function ="Microsoft.Diagnostics.NETCore.Client.IpcMessage.Parse(class System.IO.Stream) {QuickJitted}",
Module ="Microsoft.Diagnostics.NETCore.Client"
},
new SentryStackFrame() {
Function ="Microsoft.Diagnostics.NETCore.Client.IpcClient.Read(class System.IO.Stream) {QuickJitted}",
Module ="Microsoft.Diagnostics.NETCore.Client"
},
new SentryStackFrame() {
Function ="Microsoft.Diagnostics.NETCore.Client.IpcClient.SendMessageGetContinuation(class Microsoft.Diagnostics.NETCore.Client.IpcEndpoint,class Microsoft.Diagnostics.NETCore.Client.IpcMessage) {QuickJitted}",
Module ="Microsoft.Diagnostics.NETCore.Client"
},
new SentryStackFrame() {
Function ="Microsoft.Diagnostics.NETCore.Client.EventPipeSession.Start(class Microsoft.Diagnostics.NETCore.Client.IpcEndpoint,class System.Collections.Generic.IEnumerable`1<class Microsoft.Diagnostics.NETCore.Client.EventPipeProvider>,bool,int32) {QuickJitted}",
Module ="Microsoft.Diagnostics.NETCore.Client"
},
new SentryStackFrame() {
Function ="Microsoft.Diagnostics.NETCore.Client.DiagnosticsClient.StartEventPipeSession(class System.Collections.Generic.IEnumerable`1<class Microsoft.Diagnostics.NETCore.Client.EventPipeProvider>,bool,int32) {QuickJitted}",
Module ="Microsoft.Diagnostics.NETCore.Client"
},
new SentryStackFrame() {
Function ="ProfilerSession..ctor(class System.Object) {QuickJitted}",
Module ="Sentry.Extensions.Profiling"
},
new SentryStackFrame() {
Function ="SamplingTransactionProfiler.Start(class Sentry.ITransaction) {QuickJitted}",
Module ="Sentry.Extensions.Profiling"
},
new SentryStackFrame() {
Function ="Sentry.Internal.Hub.StartTransaction(class Sentry.ITransactionContext,class System.Collections.Generic.IReadOnlyDictionary`2<class System.String,class System.Object>,class Sentry.DynamicSamplingContext) {QuickJitted}",
Module ="Sentry"
},
new SentryStackFrame() {
Function ="Sentry.Internal.Hub.StartTransaction(class Sentry.ITransactionContext,class System.Collections.Generic.IReadOnlyDictionary`2<class System.String,class System.Object>) {QuickJitted}",
Module ="Sentry"
},
new SentryStackFrame() {
Function ="Program+<Main>d__2.MoveNext() {Optimized}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Threading.Tasks.VoidTaskResult,Program+<Main>d__2].ExecutionContextCallback(class System.Object) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(class System.Threading.Thread,class System.Threading.ExecutionContext,class System.Threading.ContextCallback,class System.Object)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Threading.Tasks.VoidTaskResult,Program+<Main>d__2].MoveNext(class System.Threading.Thread) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Threading.Tasks.VoidTaskResult,Program+<Main>d__2].ExecuteFromThreadPool(class System.Threading.Thread) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.ThreadPoolWorkQueue.Dispatch()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.PortableThreadPool+WorkerThread.WorkerThreadStart()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="Sentry.Internal.Http.GzipBufferedRequestBodyHandler+<SendAsync>d__3.MoveNext() {QuickJitted}",
Module ="Sentry"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[System.__Canon].Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="Sentry.Internal.Http.GzipBufferedRequestBodyHandler.SendAsync(class System.Net.Http.HttpRequestMessage,value class System.Threading.CancellationToken) {QuickJitted}",
Module ="Sentry"
},
new SentryStackFrame() {
Function ="System.Net.Http.DelegatingHandler.SendAsync(class System.Net.Http.HttpRequestMessage,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="Sentry.Internal.Http.RetryAfterHandler.<>n__0(class System.Net.Http.HttpRequestMessage,value class System.Threading.CancellationToken) {QuickJitted}",
Module ="Sentry"
},
new SentryStackFrame() {
Function ="Sentry.Internal.Http.RetryAfterHandler+<SendAsync>d__8.MoveNext() {QuickJitted}",
Module ="Sentry"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[System.__Canon].Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="Sentry.Internal.Http.RetryAfterHandler.SendAsync(class System.Net.Http.HttpRequestMessage,value class System.Threading.CancellationToken) {QuickJitted}",
Module ="Sentry"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpMessageInvoker.SendAsync(class System.Net.Http.HttpRequestMessage,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpClient+<<SendAsync>g__Core|83_0>d.MoveNext()",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[System.__Canon].Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(class System.Net.Http.HttpRequestMessage,value class System.Net.Http.HttpCompletionOption,class System.Threading.CancellationTokenSource,bool,class System.Threading.CancellationTokenSource,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpClient.SendAsync(class System.Net.Http.HttpRequestMessage,value class System.Net.Http.HttpCompletionOption,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpClient.SendAsync(class System.Net.Http.HttpRequestMessage,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="Sentry.Internal.Http.HttpTransport+<SendEnvelopeAsync>d__3.MoveNext() {QuickJitted}",
Module ="Sentry"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="Sentry.Internal.Http.HttpTransport.SendEnvelopeAsync(class Sentry.Protocol.Envelopes.Envelope,value class System.Threading.CancellationToken) {QuickJitted}",
Module ="Sentry"
},
new SentryStackFrame() {
Function ="Sentry.Internal.BackgroundWorker+<DoWorkAsync>d__20.MoveNext() {Optimized}",
Module ="Sentry"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Threading.Tasks.VoidTaskResult,Sentry.Internal.BackgroundWorker+<DoWorkAsync>d__20].ExecutionContextCallback(class System.Object) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.ExecutionContext.RunInternal(class System.Threading.ExecutionContext,class System.Threading.ContextCallback,class System.Object)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Threading.Tasks.VoidTaskResult,Sentry.Internal.BackgroundWorker+<DoWorkAsync>d__20].MoveNext(class System.Threading.Thread) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Threading.Tasks.VoidTaskResult,Sentry.Internal.BackgroundWorker+<DoWorkAsync>d__20].MoveNext() {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(class System.Runtime.CompilerServices.IAsyncStateMachineBox,bool)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task.RunContinuations(class System.Object)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task.FinishContinuations()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task`1[System.Boolean].TrySetResult(!0)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[System.Boolean].SetExistingTaskResult(class System.Threading.Tasks.Task`1<!0>,!0)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.SemaphoreSlim+<WaitUntilCountOrTimeoutAsync>d__31.MoveNext()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Boolean,System.Threading.SemaphoreSlim+<WaitUntilCountOrTimeoutAsync>d__31].ExecutionContextCallback(class System.Object) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Boolean,System.Threading.SemaphoreSlim+<WaitUntilCountOrTimeoutAsync>d__31].MoveNext(class System.Threading.Thread) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Boolean,System.Threading.SemaphoreSlim+<WaitUntilCountOrTimeoutAsync>d__31].MoveNext() {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(class System.Action,bool)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task.RunContinuations(class System.Object)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task+CancellationPromise`1[System.Boolean].System.Threading.Tasks.ITaskCompletionAction.Invoke(class System.Threading.Tasks.Task)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.CompletionActionInvoker.System.Threading.IThreadPoolWorkItem.Execute()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.ThreadPoolWorkQueue.Dispatch()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Program.FindPrimeNumber(int32) {Optimized}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Program+<Main>d__2.MoveNext() {Optimized}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="System.Net.Http.WinInetProxyHelper..ctor()",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpWindowsProxy.TryCreate(class System.Net.IWebProxy&)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.SystemProxyInfo.ConstructSystemProxy()",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Lazy`1[System.__Canon].ViaFactory(value class System.Threading.LazyThreadSafetyMode)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Lazy`1[System.__Canon].ExecutionAndPublication(class System.LazyHelper,bool)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Lazy`1[System.__Canon].CreateValue()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Lazy`1[System.__Canon].get_Value()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpClient+<>c.<get_DefaultProxy>b__15_0()",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Threading.LazyInitializer.EnsureInitializedCore(!!0&,class System.Func`1<!!0>)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.LazyInitializer.EnsureInitialized(!!0&,class System.Func`1<!!0>)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpClient.get_DefaultProxy()",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionPoolManager..ctor(class System.Net.Http.HttpConnectionSettings)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.SocketsHttpHandler.SetupHandlerChain()",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.SocketsHttpHandler.SendAsync(class System.Net.Http.HttpRequestMessage,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.DelegatingHandler.SendAsync(class System.Net.Http.HttpRequestMessage,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="Sentry.Internal.Http.GzipBufferedRequestBodyHandler.<>n__0(class System.Net.Http.HttpRequestMessage,value class System.Threading.CancellationToken) {QuickJitted}",
Module ="Sentry"
},
new SentryStackFrame() {
Function ="System.IO.Stream+<>c.<BeginReadInternal>b__40_0(class System.Object)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task`1[System.Int32].InnerInvoke()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task+<>c.<.cctor>b__272_0(class System.Object)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task.ExecuteWithThreadLocal(class System.Threading.Tasks.Task&,class System.Threading.Thread)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task.ExecuteEntryUnsafe(class System.Threading.Thread)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task.ExecuteFromThreadPool(class System.Threading.Thread)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="Program+<>c.<Main>b__2_9() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task`1[System.Int64].InnerInvoke()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1[System.ValueTuple`2[System.__Canon,System.__Canon]].Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(class System.String,int32,class System.Net.Http.HttpRequestMessage,bool,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionPool+<ConnectAsync>d__97.MoveNext()",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1[System.ValueTuple`3[System.__Canon,System.__Canon,System.__Canon]].Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionPool.ConnectAsync(class System.Net.Http.HttpRequestMessage,bool,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionPool+<CreateHttp11ConnectionAsync>d__99.MoveNext()",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1[System.__Canon].Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(class System.Net.Http.HttpRequestMessage,bool,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionPool+<AddHttp11ConnectionAsync>d__74.MoveNext()",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionPool.AddHttp11ConnectionAsync(class System.Net.Http.HttpRequestMessage)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionPool+<>c__DisplayClass75_0.<CheckForHttp11ConnectionInjection>b__0()",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task`1[System.__Canon].InnerInvoke()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[System.__Canon].AwaitUnsafeOnCompleted(!!0&,!!1&,class System.Threading.Tasks.Task`1<!0>&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1[System.__Canon].AwaitUnsafeOnCompleted(!!0&,!!1&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionPool+<GetHttp11ConnectionAsync>d__76.MoveNext()",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1[System.__Canon].Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionPool.GetHttp11ConnectionAsync(class System.Net.Http.HttpRequestMessage,bool,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionPool+<SendWithVersionDetectionAndRetryAsync>d__84.MoveNext()",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1[System.__Canon].Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(class System.Net.Http.HttpRequestMessage,bool,bool,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionPoolManager.SendAsyncCore(class System.Net.Http.HttpRequestMessage,class System.Uri,bool,bool,bool,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionPoolManager.SendAsync(class System.Net.Http.HttpRequestMessage,bool,bool,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionHandler.SendAsync(class System.Net.Http.HttpRequestMessage,bool,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpMessageHandlerStage.SendAsync(class System.Net.Http.HttpRequestMessage,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.DiagnosticsHandler.SendAsync(class System.Net.Http.HttpRequestMessage,bool,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.RedirectHandler+<SendAsync>d__4.MoveNext()",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1[System.__Canon].Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.RedirectHandler.SendAsync(class System.Net.Http.HttpRequestMessage,bool,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.DecompressionHandler+<SendAsync>d__16.MoveNext()",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1[System.__Canon].Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.DecompressionHandler.SendAsync(class System.Net.Http.HttpRequestMessage,bool,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.SocketsHttpHandler.SendAsync(class System.Net.Http.HttpRequestMessage,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="System.Net.Security.SecureChannel.AcquireClientCredentials(unsigned int8[]&)",
Module ="System.Net.Security.il"
},
new SentryStackFrame() {
Function ="System.Net.Security.SecureChannel.GenerateToken(value class System.ReadOnlySpan`1<unsigned int8>,unsigned int8[]&)",
Module ="System.Net.Security.il"
},
new SentryStackFrame() {
Function ="System.Net.Security.SecureChannel.NextMessage(value class System.ReadOnlySpan`1<unsigned int8>)",
Module ="System.Net.Security.il"
},
new SentryStackFrame() {
Function ="System.Net.Security.SslStream+<ForceAuthenticationAsync>d__175`1[System.Net.Security.AsyncReadWriteAdapter].MoveNext()",
Module ="System.Net.Security.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Security.SslStream.ForceAuthenticationAsync(!!0,bool,unsigned int8[],bool)",
Module ="System.Net.Security.il"
},
new SentryStackFrame() {
Function ="System.Net.Security.SslStream.ProcessAuthenticationAsync(bool,bool,value class System.Threading.CancellationToken)",
Module ="System.Net.Security.il"
},
new SentryStackFrame() {
Function ="System.Net.Security.SslStream.AuthenticateAsClientAsync(class System.Net.Security.SslClientAuthenticationOptions,value class System.Threading.CancellationToken)",
Module ="System.Net.Security.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.ConnectHelper+<EstablishSslConnectionAsync>d__2.MoveNext()",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1[System.__Canon].Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.ConnectHelper.EstablishSslConnectionAsync(class System.Net.Security.SslClientAuthenticationOptions,class System.Net.Http.HttpRequestMessage,bool,class System.IO.Stream,value class System.Threading.CancellationToken)",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionPool+<ConnectAsync>d__97.MoveNext()",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.ValueTuple`3[System.__Canon,System.__Canon,System.__Canon],System.Net.Http.HttpConnectionPool+<ConnectAsync>d__97].ExecutionContextCallback(class System.Object) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.ValueTuple`3[System.__Canon,System.__Canon,System.__Canon],System.Net.Http.HttpConnectionPool+<ConnectAsync>d__97].MoveNext(class System.Threading.Thread) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.ValueTuple`3[System.__Canon,System.__Canon,System.__Canon],System.Net.Http.HttpConnectionPool+<ConnectAsync>d__97].MoveNext() {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task`1[System.ValueTuple`2[System.__Canon,System.__Canon]].TrySetResult(!0)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1[System.ValueTuple`2[System.__Canon,System.__Canon]].SetResult(!0)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Http.HttpConnectionPool+<ConnectToTcpHostAsync>d__98.MoveNext()",
Module ="System.Net.Http.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.ValueTuple`2[System.__Canon,System.__Canon],System.Net.Http.HttpConnectionPool+<ConnectToTcpHostAsync>d__98].ExecutionContextCallback(class System.Object) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.ValueTuple`2[System.__Canon,System.__Canon],System.Net.Http.HttpConnectionPool+<ConnectToTcpHostAsync>d__98].MoveNext(class System.Threading.Thread) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.ValueTuple`2[System.__Canon,System.__Canon],System.Net.Http.HttpConnectionPool+<ConnectToTcpHostAsync>d__98].MoveNext() {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task`1[System.Threading.Tasks.VoidTaskResult].TrySetResult(!0)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[System.Threading.Tasks.VoidTaskResult].SetExistingTaskResult(class System.Threading.Tasks.Task`1<!0>,!0)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder.SetResult()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Sockets.Socket+<<ConnectAsync>g__WaitForConnectWithCancellation|277_0>d.MoveNext()",
Module ="System.Net.Sockets.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Threading.Tasks.VoidTaskResult,System.Net.Sockets.Socket+<<ConnectAsync>g__WaitForConnectWithCancellation|277_0>d].ExecutionContextCallback(class System.Object) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Threading.Tasks.VoidTaskResult,System.Net.Sockets.Socket+<<ConnectAsync>g__WaitForConnectWithCancellation|277_0>d].MoveNext(class System.Threading.Thread) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Threading.Tasks.VoidTaskResult,System.Net.Sockets.Socket+<<ConnectAsync>g__WaitForConnectWithCancellation|277_0>d].MoveNext() {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.ThreadPool+<>c.<.cctor>b__87_0(class System.Object)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Sockets.Socket+AwaitableSocketAsyncEventArgs.InvokeContinuation(class System.Action`1<class System.Object>,class System.Object,bool,bool)",
Module ="System.Net.Sockets.il"
},
new SentryStackFrame() {
Function ="System.Net.Sockets.Socket+AwaitableSocketAsyncEventArgs.OnCompleted(class System.Net.Sockets.SocketAsyncEventArgs)",
Module ="System.Net.Sockets.il"
},
new SentryStackFrame() {
Function ="System.Net.Sockets.SocketAsyncEventArgs+<<DnsConnectAsync>g__Core|112_0>d.MoveNext()",
Module ="System.Net.Sockets.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Threading.Tasks.VoidTaskResult,System.Net.Sockets.SocketAsyncEventArgs+<<DnsConnectAsync>g__Core|112_0>d].ExecutionContextCallback(class System.Object) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Threading.Tasks.VoidTaskResult,System.Net.Sockets.SocketAsyncEventArgs+<<DnsConnectAsync>g__Core|112_0>d].MoveNext(class System.Threading.Thread) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Threading.Tasks.VoidTaskResult,System.Net.Sockets.SocketAsyncEventArgs+<<DnsConnectAsync>g__Core|112_0>d].MoveNext() {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Sources.ManualResetValueTaskSourceCore`1[System.Boolean].SignalCompletion()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Sources.ManualResetValueTaskSourceCore`1[System.Boolean].SetResult(!0)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Sockets.SocketAsyncEventArgs+MultiConnectSocketAsyncEventArgs.OnCompleted(class System.Net.Sockets.SocketAsyncEventArgs)",
Module ="System.Net.Sockets.il"
},
new SentryStackFrame() {
Function ="System.Net.Sockets.SocketAsyncEventArgs.OnCompletedInternal()",
Module ="System.Net.Sockets.il"
},
new SentryStackFrame() {
Function ="System.Net.Sockets.SocketAsyncEventArgs.ExecutionCallback(class System.Object)",
Module ="System.Net.Sockets.il"
},
new SentryStackFrame() {
Function ="System.Threading.ExecutionContext.Run(class System.Threading.ExecutionContext,class System.Threading.ContextCallback,class System.Object)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Sockets.SocketAsyncEventArgs+<>c.<.cctor>b__179_0(unsigned int32,unsigned int32,value class System.Threading.NativeOverlapped*)",
Module ="System.Net.Sockets.il"
},
new SentryStackFrame() {
Function ="System.Threading.ThreadPoolBoundHandleOverlapped.CompletionCallback(unsigned int32,unsigned int32,value class System.Threading.NativeOverlapped*)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading._IOCompletionCallback.PerformIOCompletionCallback(unsigned int32,unsigned int32,value class System.Threading.NativeOverlapped*)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[System.__Canon].AwaitUnsafeOnCompleted(!!0&,!!1&,class System.Threading.Tasks.Task`1<!0>&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1[System.__Canon].AwaitUnsafeOnCompleted(!!0&,!!1&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Security.SslStream+<ReceiveBlobAsync>d__176`1[System.Net.Security.AsyncReadWriteAdapter].MoveNext()",
Module ="System.Net.Security.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1[System.__Canon].Start(!!0&) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Security.SslStream.ReceiveBlobAsync(!!0)",
Module ="System.Net.Security.il"
},
new SentryStackFrame() {
Function ="System.Net.Security.SslStream+<ForceAuthenticationAsync>d__175`1[System.Net.Security.AsyncReadWriteAdapter].MoveNext()",
Module ="System.Net.Security.il"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Internal.Cryptography.Pal.ChainPal.BuildChain(bool,class Internal.Cryptography.ICertificatePal,class System.Security.Cryptography.X509Certificates.X509Certificate2Collection,class System.Security.Cryptography.OidCollection,class System.Security.Cryptography.OidCollection,value class System.Security.Cryptography.X509Certificates.X509RevocationMode,value class System.Security.Cryptography.X509Certificates.X509RevocationFlag,class System.Security.Cryptography.X509Certificates.X509Certificate2Collection,value class System.Security.Cryptography.X509Certificates.X509ChainTrustMode,value class System.DateTime,value class System.TimeSpan,bool)",
Module ="System.Security.Cryptography.X509Certificates.il"
},
new SentryStackFrame() {
Function ="System.Security.Cryptography.X509Certificates.X509Chain.Build(class System.Security.Cryptography.X509Certificates.X509Certificate2,bool)",
Module ="System.Security.Cryptography.X509Certificates.il"
},
new SentryStackFrame() {
Function ="System.Security.Cryptography.X509Certificates.X509Chain.Build(class System.Security.Cryptography.X509Certificates.X509Certificate2)",
Module ="System.Security.Cryptography.X509Certificates.il"
},
new SentryStackFrame() {
Function ="System.Net.CertificateValidation.BuildChainAndVerifyProperties(class System.Security.Cryptography.X509Certificates.X509Chain,class System.Security.Cryptography.X509Certificates.X509Certificate2,bool,bool,class System.String)",
Module ="System.Net.Security.il"
},
new SentryStackFrame() {
Function ="System.Net.Security.SecureChannel.VerifyRemoteCertificate(class System.Net.Security.RemoteCertificateValidationCallback,class System.Net.Security.SslCertificateTrust,class System.Net.Security.ProtocolToken&,value class System.Net.Security.SslPolicyErrors&,value class System.Security.Cryptography.X509Certificates.X509ChainStatusFlags&)",
Module ="System.Net.Security.il"
},
new SentryStackFrame() {
Function ="System.Net.Security.SslStream.CompleteHandshake(class System.Net.Security.ProtocolToken&,value class System.Net.Security.SslPolicyErrors&,value class System.Security.Cryptography.X509Certificates.X509ChainStatusFlags&)",
Module ="System.Net.Security.il"
},
new SentryStackFrame() {
Function ="System.Net.Security.SslStream.CompleteHandshake(class System.Net.Security.SslAuthenticationOptions)",
Module ="System.Net.Security.il"
},
new SentryStackFrame() {
Function ="System.Net.Security.SslStream+<ForceAuthenticationAsync>d__175`1[System.Net.Security.AsyncReadWriteAdapter].MoveNext()",
Module ="System.Net.Security.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Threading.Tasks.VoidTaskResult,System.Net.Security.SslStream+<ForceAuthenticationAsync>d__175`1[System.Net.Security.AsyncReadWriteAdapter]].ExecutionContextCallback(class System.Object) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Threading.Tasks.VoidTaskResult,System.Net.Security.SslStream+<ForceAuthenticationAsync>d__175`1[System.Net.Security.AsyncReadWriteAdapter]].MoveNext(class System.Threading.Thread) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Threading.Tasks.VoidTaskResult,System.Net.Security.SslStream+<ForceAuthenticationAsync>d__175`1[System.Net.Security.AsyncReadWriteAdapter]].MoveNext() {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task`1[System.__Canon].TrySetResult(!0)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[System.__Canon].SetExistingTaskResult(class System.Threading.Tasks.Task`1<!0>,!0)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1[System.__Canon].SetResult(!0)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Security.SslStream+<ReceiveBlobAsync>d__176`1[System.Net.Security.AsyncReadWriteAdapter].MoveNext()",
Module ="System.Net.Security.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.__Canon,System.Net.Security.SslStream+<ReceiveBlobAsync>d__176`1[System.Net.Security.AsyncReadWriteAdapter]].ExecutionContextCallback(class System.Object) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.__Canon,System.Net.Security.SslStream+<ReceiveBlobAsync>d__176`1[System.Net.Security.AsyncReadWriteAdapter]].MoveNext(class System.Threading.Thread) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.__Canon,System.Net.Security.SslStream+<ReceiveBlobAsync>d__176`1[System.Net.Security.AsyncReadWriteAdapter]].MoveNext() {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task`1[System.Int32].TrySetResult(!0)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[System.Int32].SetExistingTaskResult(class System.Threading.Tasks.Task`1<!0>,!0)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1[System.Int32].SetResult(!0)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Security.SslStream+<<FillHandshakeBufferAsync>g__InternalFillHandshakeBufferAsync|189_0>d`1[System.Net.Security.AsyncReadWriteAdapter].MoveNext()",
Module ="System.Net.Security.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Int32,System.Net.Security.SslStream+<<FillHandshakeBufferAsync>g__InternalFillHandshakeBufferAsync|189_0>d`1[System.Net.Security.AsyncReadWriteAdapter]].ExecutionContextCallback(class System.Object) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Int32,System.Net.Security.SslStream+<<FillHandshakeBufferAsync>g__InternalFillHandshakeBufferAsync|189_0>d`1[System.Net.Security.AsyncReadWriteAdapter]].MoveNext(class System.Threading.Thread) {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Int32,System.Net.Security.SslStream+<<FillHandshakeBufferAsync>g__InternalFillHandshakeBufferAsync|189_0>d`1[System.Net.Security.AsyncReadWriteAdapter]].MoveNext() {QuickJitted}",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Net.Sockets.SocketAsyncEventArgs+<>c.<.cctor>b__179_0(unsigned int32,unsigned int32,value class System.Threading.NativeOverlapped*)",
Module ="System.Net.Sockets.il"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="Program.<Main>() {QuickJitted}",
Module ="Sentry.Samples.Console.Customized"
},
new SentryStackFrame() {
Function ="System.Threading.PortableThreadPool+WorkerThread.WorkerThreadStart()",
Module = "System.Private.CoreLib.il"
}
};
}
|
using System;
using System.Collections.Generic;
namespace AMS.Models
{
public partial class Expenses
{
public long Id { get; set; }
public string Name { get; set; }
public string Details { get; set; }
public decimal Amount { get; set; }
public DateTime Date { get; set; }
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Shipwreck.TypeScriptModels.Declarations;
namespace Shipwreck.TypeScriptModels.Decompiler.Transformations.Members
{
[TestClass]
public class PropertydDeclarationTest
{
private abstract class TestClass
{
public int AutoInt32Property { get; set; }
protected abstract int ReadOnlyInt32Property { get; }
protected abstract int WriteOnlyInt32Property { set; }
internal int AccessibilityInt32Property { get; private set; }
public int ManualInt32Property
{
get { return 0; }
set { }
}
}
[TestMethod]
public void PropertydDeclaration_AutoInt32PropertyTest()
{
var t = new TypeTranslationContext<TestClass>();
var f = t.GetField(nameof(TestClass.AutoInt32Property));
Assert.AreEqual(AccessibilityModifier.Public, f.Accessibility);
Assert.AreEqual(PredefinedType.Number, f.FieldType);
}
[TestMethod]
public void PropertydDeclaration_ReadOnlyInt32PropertyTest()
{
var t = new TypeTranslationContext<TestClass>();
var f = t.GetField("__ReadOnlyInt32Property");
Assert.AreEqual(AccessibilityModifier.Private, f.Accessibility);
Assert.AreEqual(PredefinedType.Number, f.FieldType);
var g = t.GetGetAccessor("ReadOnlyInt32Property");
Assert.AreEqual(AccessibilityModifier.Protected, g.Accessibility);
Assert.AreEqual(PredefinedType.Number, g.PropertyType);
var s = t.GetSetAccessor("ReadOnlyInt32Property");
Assert.IsNull(s);
}
[TestMethod]
public void PropertydDeclaration_WriteOnlyInt32PropertyTest()
{
var t = new TypeTranslationContext<TestClass>();
var f = t.GetField("__WriteOnlyInt32Property");
Assert.AreEqual(AccessibilityModifier.Private, f.Accessibility);
Assert.AreEqual(PredefinedType.Number, f.FieldType);
var g = t.GetGetAccessor("WriteOnlyInt32Property");
Assert.IsNull(g);
var s = t.GetSetAccessor("WriteOnlyInt32Property");
Assert.AreEqual(AccessibilityModifier.Protected, s.Accessibility);
Assert.AreEqual(PredefinedType.Number, s.PropertyType);
Assert.AreEqual("value", s.ParameterName);
}
[TestMethod]
public void PropertydDeclaration_AccessibilityInt32PropertyTest()
{
var t = new TypeTranslationContext<TestClass>();
var f = t.GetField("__" + nameof(TestClass.AccessibilityInt32Property));
Assert.AreEqual(AccessibilityModifier.Private, f.Accessibility);
Assert.AreEqual(PredefinedType.Number, f.FieldType);
var g = t.GetGetAccessor(nameof(TestClass.AccessibilityInt32Property));
Assert.AreEqual(AccessibilityModifier.Public, g.Accessibility);
Assert.AreEqual(PredefinedType.Number, g.PropertyType);
var s = t.GetSetAccessor(nameof(TestClass.AccessibilityInt32Property));
Assert.AreEqual(AccessibilityModifier.Private, s.Accessibility);
Assert.AreEqual(PredefinedType.Number, s.PropertyType);
Assert.AreEqual("value", s.ParameterName);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace _10._Student_Groups
{
public class Town
{
public string Name { get; set; }
public int SeatsCount { get; set; }
public List<Student> Students { get; set; }
public Town(string name, int seats)
{
this.Name = name;
this.SeatsCount = seats;
this.Students = new List<Student>();
}
}
}
|
using LogicaNegocio;
using ProyectoLP2;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Formularios
{
public partial class GestionUsuarios : Form
{
UsuarioBL usuarioBL;
public GestionUsuarios()
{
InitializeComponent();
cmbBusqUsuarioRol.SelectedIndex = -1;
cargarUsuarios();
}
private void btnAddUsuario_Click(object sender, EventArgs e)
{
AgregarUsuario ausuario = new AgregarUsuario();
ausuario.FormClosed += new System.Windows.Forms.FormClosedEventHandler(AgregarUsuario_FormClosed);
if (ausuario.ShowDialog() == DialogResult.OK)
{
}
}
private void AgregarUsuario_FormClosed(object sender, FormClosedEventArgs e)
{
cargarUsuarios();
}
private void btncancelar_Click(object sender, EventArgs e)
{
this.Dispose();
}
private void rbtnDNI_CheckedChanged(object sender, EventArgs e)
{
if (rbtnDNI.Checked)
{
rbtRol.Checked = false;
txtBusqUsuarioDNI.Enabled = true;
cmbBusqUsuarioRol.SelectedIndex = -1;
cmbBusqUsuarioRol.Enabled = false;
}
}
private void rbtRol_CheckedChanged(object sender, EventArgs e)
{
if (rbtRol.Checked)
{
rbtnDNI.Checked = false;
cmbBusqUsuarioRol.Enabled = true;
txtBusqUsuarioDNI.Text = "";
txtBusqUsuarioDNI.Enabled = false;
}
}
private void btnBusquedaPedido_Click(object sender, EventArgs e)
{
string rol = "";
string dni = txtBusqUsuarioDNI.Text;
if (cmbBusqUsuarioRol.SelectedIndex==-1 & dni == "") cargarUsuarios();
else
{
rol = cmbBusqUsuarioRol.Text;
usuarioBL = new UsuarioBL();
BindingList<Persona> usuarios = new BindingList<Persona>();
usuarios = usuarioBL.listarUsuarios(dni,rol);
dgvUsuarios.AutoGenerateColumns = false;
dgvUsuarios.DataSource = usuarios;
}
}
private void cargarUsuarios()
{
usuarioBL = new UsuarioBL();
BindingList<Persona> usuarios = new BindingList<Persona>();
usuarios = usuarioBL.listarUsuarios();
dgvUsuarios.AutoGenerateColumns = false;
dgvUsuarios.DataSource = usuarios;
}
private void btnModCliente_Click(object sender, EventArgs e)
{
Persona usuario = null;
usuario=(Persona)dgvUsuarios.CurrentRow.DataBoundItem;
ModificarUsuario fga = new ModificarUsuario(usuario);
fga.FormClosed += new System.Windows.Forms.FormClosedEventHandler(ModificarUsuario_FormClosed);
fga.ShowDialog();
}
private void ModificarUsuario_FormClosed(object sender, FormClosedEventArgs e)
{
cargarUsuarios();
}
private void btnElimCliente_Click(object sender, EventArgs e)
{
string dni = "";
//}
if (MessageBox.Show("Esta seguro que desea eliminar el Usuario", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
dni = dgvUsuarios.Rows[dgvUsuarios.CurrentRow.Index].Cells[0].Value.ToString();
if (usuarioBL.eliminarUsuario(dni))
{
MessageBox.Show("Se elimino el Usuario satisfactoriamente");
cargarUsuarios();
}
else
{
MessageBox.Show("No se pudo eliminar el Usuario");
}
// user clicked yes
}
else
{
// user clicked no
}
}
}
}
|
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace BasicSecurity
{
/// <summary>
/// Interaction logic for SteganografieUitlezen.xaml
/// </summary>
public partial class SteganografieUitlezen : Window
{
private Bitmap bmp = null;
public SteganografieUitlezen()
{
InitializeComponent();
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
uitgelezenTextBox.ScrollToEnd();
}
private void bladerenButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog open_dialog = new OpenFileDialog();
open_dialog.Filter = "Bitmap Image Files (*.bmp)|*.bmp";
open_dialog.InitialDirectory = MainWindow.documentsPathStegano;
Nullable<bool> result = open_dialog.ShowDialog();
if (result == true)
{
try
{
afbeeldingImage.Source = new BitmapImage(new Uri(open_dialog.FileName));
bmp = new Bitmap(open_dialog.FileName);
uitlezenButton.IsEnabled = true;
}
catch (Exception ex)
{
uitgelezenTextBox.AppendText("\nERROR\nKan geen bitmap afbeelding maken van het gekozen bestand: " + ex.Message);
}
}
}
private void annuleerButton_Click(object sender, RoutedEventArgs e)
{
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
this.Close();
}
private void uitlezenButton_Click(object sender, RoutedEventArgs e)
{
string extractedText = SteganographyHelper.extractText(bmp);
uitgelezenTextBox.Text = extractedText;
uitgelezenTextBox.AppendText("\n\n----------------------------------\nUitlezen voltooid");
}
}
}
|
using CurrencyLibs.Interfaces;
using System.Collections.Generic;
namespace CurrencyMVCApp.ViewModels
{
public class RepoViewModel
{
public ICurrencyRepo repo;
public RepoViewModel(ICurrencyRepo repo)
{
this.repo = repo;
}
public double TotalValue
{
get { return repo.TotalValue(); }
}
public void MakeChange(double Amount)
{
var newRepo = repo.MakeChange(Amount);
this.repo.Coins = newRepo.Coins;
}
public List<ICoin> Coins
{
get { return repo.Coins; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Infrastructure;
using ServerApi.Services.Devices;
[assembly: OwinStartup(typeof(ServerApi.Startup))]
// https://dotnetcodr.com/2015/11/23/wiring-up-a-custom-authentication-method-with-owin-in-web-api-part-3-the-components/
// https://msdn.microsoft.com/en-us/library/ff359101.aspx
namespace ServerApi.OwinMiddleware.Authentication
{
public class DeviceGuidAuthenticationHandler : AuthenticationHandler<DeviceGuidTokenAuthenticationOptions>
{
private readonly GetDevicesService _getDevicesService = new GetDevicesService();
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
{
var authResult = await Authenticate(Request.Headers);
if (!authResult.Success)
{
return null;
}
var authProps = new AuthenticationProperties();
authProps.IssuedUtc = DateTimeOffset.UtcNow;
authProps.ExpiresUtc = DateTimeOffset.UtcNow.AddMonths(1);
authProps.AllowRefresh = true;
authProps.IsPersistent = true;
var claims = new List<Claim>
{
new Claim("UserId", authResult.UserId.ToString(), ClaimValueTypes.Integer, "RegisteredUsersDB"),
new Claim("DeviceId", Request.Headers["DeviceGuid"], "Guid", "Client"),
new Claim(ClaimTypes.Role, nameof(Roles.RegisteredUser), ClaimValueTypes.String, "RegisteredUsersDB"),
};
var claimsIdentity = new ClaimsIdentity(claims, "DeviceGuidTokenAuth");
return new AuthenticationTicket(claimsIdentity, authProps);
}
private async Task<AuthenticationResult> Authenticate(IHeaderDictionary requestHeaders)
{
// Check if request has DeviceGuid header
if (!requestHeaders.ContainsKey("DeviceGuid"))
{
return AuthenticationResult.Fail;
}
// Check if DeviceGuid has correct format
if (Guid.TryParse(requestHeaders.Get("DeviceGuid"), out var deviceGuid))
{
Request.Set("DeviceGuid", deviceGuid);
}
else
{
return AuthenticationResult.Fail;
}
// Check if this device GUID is registered to a user and retrieve that userId
int? userId = await _getDevicesService.GetUserIdByDeviceIdAsync(deviceGuid);
if (userId == null)
{
return AuthenticationResult.Fail;
}
// Request.Set("UserId", userId.Value);
return new AuthenticationResult(true, userId.Value);
}
private class AuthenticationResult
{
public bool Success { get; }
public int UserId { get; }
public static readonly AuthenticationResult Fail = new AuthenticationResult(false, -1);
public AuthenticationResult(bool success, int userId)
{
Success = success;
UserId = userId;
}
}
}
}
|
using System;
using System.Text;
using System.Collections;
using System.Xml;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Resources;
using System.Reflection;
using System.Globalization;
using System.Threading;
using Telerik.WebControls;
using UFSoft.UBF.UI.WebControls;
using UFSoft.UBF.UI.Controls;
using UFSoft.UBF.Util.Log;
using UFSoft.UBF.Util.Globalization;
using UFSoft.UBF.UI.IView;
using UFSoft.UBF.UI.Engine;
using UFSoft.UBF.UI.MD.Runtime;
using UFSoft.UBF.UI.ActionProcess;
using UFSoft.UBF.UI.WebControls.ClientCallBack;
using HBH.DoNet.DevPlatform.EntityMapping;
/***********************************************************************************************
* Form ID:
* UIFactory Auto Generator
***********************************************************************************************/
namespace VouchersLineRef
{
public partial class VouchersLineRefWebPart
{
#region Custome eventBind
//FindButton_Click...
private void FindButton_Click_Extend(object sender, EventArgs e)
{
//调用模版提供的默认实现.--默认实现可能会调用相应的Action.
FindButton_Click_DefaultImpl(sender,e);
}
//QryButton_Click...
private void QryButton_Click_Extend(object sender, EventArgs e)
{
//调用模版提供的默认实现.--默认实现可能会调用相应的Action.
QryButton_Click_DefaultImpl(sender,e);
}
//DDLCase_TextChanged...
private void DDLCase_TextChanged_Extend(object sender, EventArgs e)
{
//调用模版提供的默认实现.--默认实现可能会调用相应的Action.
DDLCase_TextChanged_DefaultImpl(sender,e);
}
//ConfirmButton_Click...
private void ConfirmButton_Click_Extend(object sender, EventArgs e)
{
//调用模版提供的默认实现.--默认实现可能会调用相应的Action.
ConfirmButton_Click_DefaultImpl(sender,e);
}
//CancelButton_Click...
private void CancelButton_Click_Extend(object sender, EventArgs e)
{
//调用模版提供的默认实现.--默认实现可能会调用相应的Action.
CancelButton_Click_DefaultImpl(sender,e);
}
//DataGrid_GridRowDbClicked...
private void DataGrid_GridRowDbClicked_Extend(object sender, GridDBClickEventArgs e)
{
//调用模版提供的默认实现.--默认实现可能会调用相应的Action.
DataGrid_GridRowDbClicked_DefaultImpl(sender,e);
}
#endregion
#region 自定义数据初始化加载和数据收集
private void OnLoadData_Extend(object sender)
{
//@VouchersType
string strTypes = PubClass.GetString(this.NameValues["VouchersType"]);
if (PubClass.IsNull(strTypes))
{
strTypes = "-1";
}
this.Model.cRef.CurrentFilter.OPath = string.Format("(IsUsed is null or IsUsed = 0) and VouchersType in (select attr.DefaultValue from UFIDA::UBF::MD::Business::Attribute attr where attr.ID in ({0}) )"
, strTypes
);
OnLoadData_DefaultImpl(sender);
}
private void OnDataCollect_Extend(object sender)
{
OnDataCollect_DefaultImpl(sender);
}
#endregion
#region 自己扩展 Extended Event handler
public void AfterOnLoad()
{
}
public void AfterCreateChildControls()
{
}
public void AfterEventBind()
{
}
public void BeforeUIModelBinding()
{
}
public void AfterUIModelBinding()
{
this.DataGrid.Columns["Money"].Point = 0;
//this.DataGrid.Columns["EffectiveDate"].DisplayFormat = "yyyy-MM-dd";
//this.DataGrid.Columns["DisabledDate"].DisplayFormat = "yyyy-MM-dd";
//this.DataGrid.Columns["EffectiveDate"].DataType = (int)DataType.DATATYPE_DATE;
//((IUFDatePickerColumn)column).DateTimeType = DateTimeType.DateTime;
//((IUFDatePickerColumn)column).DateTimeFormat = CurrentState._I18N._DateTimeFormatInfo;
((UFSoft.UBF.UI.ControlModel.IUFDatePickerColumn)this.DataGrid.Columns["EffectiveDate"]).DateTimeType = DateTimeType.Date;
((UFSoft.UBF.UI.ControlModel.IUFDatePickerColumn)this.DataGrid.Columns["DisabledDate"]).DateTimeType = DateTimeType.Date;
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Assistenza.BufDalsi.Web.Models.SensoreViewModels
{
public class UpdateSensoreViewModel
{
public int ipt_Id { get; set; }
public int clt_id { get; set; }
public int ssr_Id { get; set; }
public string ssr_Nome { get; set; }
public string ssr_Modello { get; set; }
public string ssr_Marca { get; set; }
public string ssr_Serie { get; set; }
[DataType(DataType.Date)]
public DateTime ssr_UltimaInstallazione { get; set; }
public int ssr_Vasca { get; set; }
public UpdateSensoreViewModel()
{
ssr_UltimaInstallazione = new DateTime(1900, 01, 01);
}
public UpdateSensoreViewModel(int id, string Nome, string Modello, string Marca, string Serie, DateTime uInst, int vsc)
{
ssr_Id = id;
ssr_Nome = Nome;
ssr_Modello = Modello;
ssr_Marca = Marca;
ssr_Serie = Serie;
ssr_UltimaInstallazione = uInst;
ssr_Vasca = vsc;
}
}
}
|
using System;
using System.Windows;
using System.Diagnostics;
using NLog;
namespace RAM.Classes
{
internal class StartProgram
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public void Start(string comp)
{
try
{
var pr = new Process();
var rp = new ProcessStartInfo();
if (comp != null)
{
pr.StartInfo.FileName = "msra.exe";
pr.StartInfo.Arguments = "/offerra " + comp;
pr.Start();
Logger.Info ("Запуск подключения к {0}", comp);
}
}
catch (Exception e)
{
Logger.Error(e, "Ошибка запуска программы");
MessageBox.Show("Произошла ошибка:" + Environment.NewLine + e.Message);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GFW;
namespace CodeX
{
public class MapManager : ManagerModule
{
private const uint LogicWidth = 100u;
private const uint LogicHeight = 100u;
private Dictionary<uint, Map> mapCacher = new Dictionary<uint, Map>();
public bool MapLoaded = false;
public uint currentMapId;
public void LoadMap(uint mapId, TextAsset txt)
{
this.currentMapId = mapId;
this.LoadOtherMap(mapId, txt);
}
public void LoadOtherMap(uint mapId, TextAsset txt)
{
if (!this.mapCacher.ContainsKey(mapId))
{
Map map = new Map(LogicWidth, LogicHeight);
map.LoadData(txt);
this.mapCacher.Add(mapId, map);
}
}
public Map CurMap()
{
return this.mapCacher[this.currentMapId];
}
public Map MapByScene(uint sceneId)
{
return this.mapCacher[sceneId];
}
public void ClearMap(uint mapId)
{
if (this.mapCacher.ContainsKey(mapId))
{
this.mapCacher.Remove(mapId);
}
}
}
}
|
using System;
using System.Globalization;
using Framework.Core.Common;
using Tests.Data.Van.Input;
using NUnit.Framework;
using OpenQA.Selenium;
namespace Tests.Pages.Van.Main.Events.EventWizardNewPageTabs
{
public class ShiftsTab : EventWizardNewPageTab
{
#region Element Declarations
public new IWebElement TabLabel { get { return TabLabel("Shifts"); } }
protected override IWebElement TabLink { get { return TabLabel.FindElement(By.XPath("ancestor::a[contains(@class,rtsLink)]")); } }
public IWebElement NumberOfShiftsDropdown { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemShiftCount_VANInputItemDetailsItemShiftCount_ShiftCount")); } }
public new IWebElement PrevButton { get { return PrevButton("Shifts"); } }
public new IWebElement NextButton { get { return NextButton("Shifts"); } }
public new IWebElement FinishButton { get { return FinishButton("Shifts"); } }
#endregion
public ShiftsTab(Driver driver) : base(driver) { }
public override void SetFields(Event ev)
{
if (ev.NumberOfShifts == 1)
{
Console.WriteLine("Number of Shifts for Event = 1, so test will not enter Shift Times");
return;
}
if (ev.NumberOfShifts < 1)
Assert.Fail(
"The Number of Shifts in Event to test is less than 1. Please make sure the test data is configured properly. Failing Test.");
if (ev.NumberOfShifts > 9)
Assert.Fail(
"The Number of Shifts in Event to test is greater than 9. Please make sure the test data is configured properly. Failing Test.");
if (ev.ShiftStartTimeList.Count != ev.ShiftEndTimeList.Count)
Assert.Fail(
"The number of Shift Start Times in Event to test is not equal to the number of Shift End Times listed. Please make sure the test data is configured properly. Failing Test.");
if (ev.NumberOfShifts != ev.ShiftStartTimeList.Count)
Assert.Fail(
"The Number of Shifts for the Event to test is not equal to the number of Shift Times listed in the Event to test. Please make sure the test data is configured properly. Failing Test.");
_driver.SelectOptionByText(NumberOfShiftsDropdown, ev.NumberOfShifts.ToString(CultureInfo.InvariantCulture));
for (var i = 1; i <= ev.NumberOfShifts; i++)
{
var startTimeFieldId =
String.Format(
"ctl00_ContentPlaceHolderVANPage_ShiftStartLabel_{0}_ShiftStart_{0}_tc_ShiftStart_{0}_tc_ShiftStart_{0}_timeText_tb_tc_ShiftStart_{0}_timeText",
i);
var endTimeFieldId =
String.Format(
"ctl00_ContentPlaceHolderVANPage_ShiftEndLabel_{0}_ShiftEnd_{0}_tc_ShiftEnd_{0}_tc_ShiftEnd_{0}_timeText_tb_tc_ShiftEnd_{0}_timeText",
i);
var startTimeField = _driver.FindElement(By.Id(startTimeFieldId));
var endTimeField = _driver.FindElement(By.Id(endTimeFieldId));
_driver.ClearAndSendKeys(startTimeField, ev.ShiftStartTimeList[i - 1]);
_driver.ClearAndSendKeys(endTimeField, ev.ShiftEndTimeList[i - 1]);
}
}
public override void WaitForTabToRender()
{
WaitForTabToRender("Shifts");
}
public override bool Enabled()
{
return Enabled(TabLink);
}
}
}
|
using LuckyMasale.BAL.Managers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
namespace LuckyMasale.WebApi.Controllers
{
public class DistributorController : ApiController
{
#region Properties
private Lazy<IDistributorManager> distributorManager;
#endregion
#region Constructors
public DistributorController(Lazy<IDistributorManager> distributorManager)
{
this.distributorManager = distributorManager;
}
#endregion
}
} |
using System.Collections.Generic;
namespace NumericProblems.Problems
{
public static class Sets
{
private static readonly Dictionary<int, bool> _memo;
private static readonly Dictionary<int, KeyValuePair<int, int>> _prev;
static Sets()
{
_memo = new Dictionary<int, bool>();
_prev = new Dictionary<int, KeyValuePair<int, int>>();
}
/// <summary>
/// Generates subsets with indexes from original set
/// </summary>
public static int[][] GenerateSubsetIndexes<T>(T[] list)
{
var subsetsNum = 1 << list.Length; // number of subsets (2^n)
var array = new int[subsetsNum][]; //array with subsets as elements
for (var idx = 0; idx < array.Length; idx++)
{
array[idx] = new int[list.Length];
}
for (var i = 0; i < subsetsNum; i++) // filling "result"
{
for (var j = 0; j < list.Length; j++)
{
var t = 1 << j;
if ((i & t) != 0)
{
array[i][j] = 1;
}
}
}
return array;
}
public static T[][] GenerateSubset<T>(T[] list)
{
var subsetsNum = 1 << list.Length; // number of subsets (2^n)
var array = new T[subsetsNum][]; //array with subsets as elements
for (var idx = 0; idx < array.Length; idx++)
{
array[idx] = new T[list.Length];
}
for (var i = 0; i < subsetsNum; i++) // filling "result"
{
for (var j = 0; j < list.Length; j++)
{
var t = 1 << j;
if ((i & t) != 0)
{
array[i][j] = list[j];
}
}
}
return array;
}
public static List<T[]> CreateSubsets<T>(T[] originalArray)
{
var subsets = new List<T[]>();
foreach (var item in originalArray)
{
var subsetCount = subsets.Count;
subsets.Add(new[] {item});
for (var j = 0; j < subsetCount; j++)
{
var newSubset = new T[subsets[j].Length + 1];
subsets[j].CopyTo(newSubset, 0);
newSubset[newSubset.Length - 1] = item;
subsets.Add(newSubset);
}
}
return subsets;
}
/// <summary>
/// Dynamic programming approach to check if a set contains a subset sum equal to target number.
/// </summary>
/// <param name="inputArray"> Input array. </param>
/// <param name="sum"> Target sum. </param>
/// <returns> </returns>
public static bool Find(int[] inputArray, int sum)
{
_memo.Clear();
_prev.Clear();
_memo[0] = true;
_prev[0] = new KeyValuePair<int, int>(-1, 0);
for (var i = 0; i < inputArray.Length; ++i)
{
var num = inputArray[i];
for (var s = sum; s >= num; --s)
{
if (_memo.ContainsKey(s - num) && _memo[s - num])
{
_memo[s] = true;
if (!_prev.ContainsKey(s))
{
_prev[s] = new KeyValuePair<int, int>(i, num);
}
}
}
}
return _memo.ContainsKey(sum) && _memo[sum];
}
public static IEnumerable<int> GetLastResult(int sum)
{
while (_prev[sum].Key != -1)
{
yield return _prev[sum].Key;
sum -= _prev[sum].Value;
}
}
}
} |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class SecretUI : MonoBehaviour {
public static SecretUI instance;
[System.Runtime.InteropServices.DllImport("__Internal")]
extern static public void LaunchShareWidget(int score, bool isHighScore);
public GameObject inputs;
public InputField levelInputField;
public InputField debugFlagsInputField;
public GameObject button;
public void ResetPreferences() {
PersistentStorage.instance.ClearAll ();
}
public void ResetAchievements() {
GameCenterHelper.instance.ClearAchievements();
}
void Awake() {
instance = this;
if (!Debug.isDebugBuild) {
button.SetActive(false);
}
}
void UpdateInputs() {
int debugFlags = DebugConfig.instance.GetDebugFlags ();
debugFlagsInputField.text = "" + debugFlags;
}
void Start() {
levelInputField.onEndEdit.AddListener(delegate{ApplyLevelInput();});
debugFlagsInputField.onEndEdit.AddListener(delegate{ApplyDebugFlags();});
}
void ApplyLevelInput() {
int suggestedLevel = Utilities.ParseIntWithDefault (levelInputField.text, 0);
if (suggestedLevel > 0) {
GameLevelState.instance.SetGameLevel (suggestedLevel);
}
}
public void ToggleVisibility() {
if (!Debug.isDebugBuild) {
return;
}
if (inputs.activeSelf) {
inputs.SetActive (false);
} else {
inputs.SetActive (true);
UpdateInputs();
}
}
void ApplyDebugFlags() {
int debugFlags = Utilities.ParseIntWithDefault (debugFlagsInputField.text, -1);
if (debugFlags >= 0) {
DebugConfig.instance.SetDebugFlags(debugFlags);
}
}
public void DebugShowSharing() {
LaunchShareWidget (100, true);
}
public void DebugTwitter() {
SAMobileSocialHelper.instance.ShareScoreOnTwitter (123);
}
public void DebugInterstitialAds() {
GoogleAdController.instance.DebugInterstitialAds ();
}
public void DebugLeaderBoard() {
GameCenterHelper.instance.ShowLeaderBoard();
}
public void DebugStore() {
StoreController.instance.BuyUpgrade();
}
} |
using Alabo.Domains.Entities;
using Alabo.Extensions;
using Alabo.Framework.Core.WebApis.Controller;
using Alabo.Framework.Core.WebApis.Filter;
using Alabo.Framework.Reports.Domain.Entities;
using Alabo.Framework.Reports.Domain.Services;
using Alabo.UI.Design.AutoReports;
using Alabo.UI.Design.AutoReports.Dtos;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using ZKCloud.Open.ApiBase.Models;
namespace Alabo.Framework.Reports.Controllers {
/// <summary>
/// 报表
/// </summary>
[ApiExceptionFilter]
[Route("Api/Report/[action]")]
public class ApiReportController : ApiBaseController<Report, ObjectId> {
/// <summary>
/// 报表 构造
/// </summary>
public ApiReportController() {
BaseService = Resolve<IReportService>();
}
#region 单条数据
/// <summary>
/// 根据配置统计单一数字 ok
/// </summary>
/// <param name="singleReportInput"></param>
/// <returns></returns>
[HttpPost]
[Display(Description = "统计单一数字")]
public ApiResult<decimal> GetSingleReport([FromBody] SingleReportInput singleReportInput) {
if (!this.IsFormValid()) {
return ApiResult.Failure<decimal>(this.FormInvalidReason());
}
var result = Resolve<IAutoReportService>().GetSingleData(singleReportInput);
return ToResult(result);
}
#endregion 单条数据
#region 过期方法,仅供参考
/// <summary>
/// 按天统计数据-线型
/// </summary>
/// <param name="reportInput"></param>
/// <returns></returns>
[HttpGet]
[Display(Description = "按天统计数据")]
public ApiResult<List<AutoReport>> GetCountReport2([FromQuery] CountReportInput reportInput) {
var result = Resolve<IAutoReportService>().GetCountReport2(reportInput);
return ToResult(result);
}
/// <summary>
/// 按天统计实体增加数据,输出表格形式
/// </summary>
/// <param name="reportInput"></param>
/// <returns></returns>
[HttpGet]
[Display(Description = "按天统计实体增加数据,输出表格形式")]
public ApiResult<PagedList<CountReportTable>> GetCountTable2([FromQuery] CountReportInput reportInput) {
var result = Resolve<IAutoReportService>().GetDayCountTable2(reportInput);
return ToResult(result);
}
/// <summary>
/// 根据字段状态,输出报表表格形式
/// </summary>
/// <param name="reportInput"></param>
/// <returns></returns>
[HttpGet]
[Display(Description = "根据字段状态,输出报表表格形式")]
public ApiResult<PagedList<CountReportTable>> GetDayCountTableByField(CountReportInput reportInput) {
var result = Resolve<IAutoReportService>().GetDayCountTableByField(reportInput);
return ToResult(result);
}
#region 求和 报表与表格 sql
/// <summary>
/// 按查询条件,求和统计
/// </summary>
[HttpGet]
[Display(Description = "按查询条件,求和统计")]
public ApiResult<List<AutoReport>> GetSumReport2([FromQuery] SumTableInput reportInput) {
var result = Resolve<IAutoReportService>().GetSumReport2(reportInput);
return ToResult(result);
}
/// <summary>
/// 按天统计实体增加数据,输出表格形式
/// </summary>
/// <param name="reportInput"></param>
/// <returns></returns>
[HttpGet]
[Display(Description = "按天统计实体增加数据,输出表格形式")]
public ApiResult<PagedList<SumReportTable>> GetSumTable2([FromQuery] SumTableInput reportInput) {
var result = Resolve<IAutoReportService>().GetCountSumTable2(null);
return ToResult(result);
}
#endregion 求和 报表与表格 sql
#endregion 过期方法,仅供参考
#region 数量统计
/// <summary>
/// 按天统计数据-线型
/// </summary>
/// <param name="reportInput"></param>
/// <returns></returns>
[HttpPost]
[Display(Description = "按天统计数据")]
public ApiResult<List<AutoReport>> GetCountReport([FromBody] CountReportInput reportInput) {
if (!this.IsFormValid()) {
return ApiResult.Failure<List<AutoReport>>(this.FormInvalidReason());
}
var result = Resolve<IAutoReportService>().GetDayCountReport(reportInput);
return ToResult(result);
}
/// <summary>
/// 按天统计实体增加数据,输出表格形式
/// </summary>
/// <param name="reportInput"></param>
/// <returns></returns>
[HttpPost]
[Display(Description = "按天统计实体增加数据,输出表格形式")]
public ApiResult<PagedList<CountReportTable>> GetCountTable([FromBody] CountReportInput reportInput) {
if (!this.IsFormValid()) {
return ApiResult.Failure<PagedList<CountReportTable>>(this.FormInvalidReason());
}
var result = Resolve<IAutoReportService>().GetDayCountTable(reportInput);
return ToResult(result);
}
#endregion 数量统计
#region 求和统计
/// <summary>
/// 按查询条件,求和统计
/// </summary>
[HttpPost]
[Display(Description = "按查询条件,求和统计")]
public ApiResult<List<AutoReport>> GetSumReport([FromBody] SumReportInput reportInput) {
if (!this.IsFormValid()) {
return ApiResult.Failure<List<AutoReport>>(this.FormInvalidReason());
}
var result = Resolve<IAutoReportService>().GetSumReport(reportInput);
return ToResult(result);
}
/// <summary>
/// 按天统计实体增加数据,输出表格形式
/// </summary>
/// <param name="reportInput"></param>
/// <returns></returns>
[HttpPost]
[Display(Description = "按天统计实体增加数据,输出表格形式")]
public ApiResult<PagedList<SumReportTable>> GetSumTable([FromBody] SumReportInput reportInput) {
if (!this.IsFormValid()) {
return ApiResult.Failure<PagedList<SumReportTable>>(this.FormInvalidReason());
}
var result = Resolve<IAutoReportService>().GetCountSumTable(reportInput);
return ToResult(result);
}
#endregion 求和统计
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SQLite;
namespace OCR_project
{
public partial class Form5 : Form
{
string name;
public Form5(string name)
{
InitializeComponent();
this.name = name;
}
private void Form5_Load(object sender, EventArgs e)
{
using (SQLiteConnection conn = new SQLiteConnection("data source=database.db"))
{
using (SQLiteCommand sqliteCommand = new SQLiteCommand(conn))
{
conn.Open();
sqliteCommand.CommandText = "SELECT * from "+name;
using (SQLiteDataReader sqliteReader = sqliteCommand.ExecuteReader())
{
while (sqliteReader.Read())
{
}
}
SQLiteDataAdapter dataadapter = new SQLiteDataAdapter("SELECT * from "+name,conn);
DataSet ds = new System.Data.DataSet();
dataadapter.Fill(ds,"Info");
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
}
}
private void button1_Click(object sender, EventArgs e)
{
using (SQLiteConnection conn = new SQLiteConnection("data source=database.db"))
{
using (SQLiteCommand sqliteCommand = new SQLiteCommand(conn))
{
conn.Open();
sqliteCommand.CommandText = "SELECT * from " + name;
using (SQLiteDataReader sqliteReader = sqliteCommand.ExecuteReader())
{
while (sqliteReader.Read())
{
}
}
SQLiteDataAdapter dataadapter = new SQLiteDataAdapter("SELECT * from " + name, conn);
DataSet ds = new System.Data.DataSet();
dataadapter.Fill(ds, "Info");
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
}
}
}
}
|
using Acr.XamForms.Mobile.IO;
using GalaSoft.MvvmLight.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ALFC_SOAP.ViewModel
{
public class FileSystemViewModel
{
private readonly IFileSystem fileSystem;
public FileSystemViewModel(IFileSystem fileSystem)
{
this.fileSystem = fileSystem;
}
public string AppDataDirectory
{
get { return this.fileSystem.AppData.FullName; }
}
public string CacheDirectory
{
get { return this.fileSystem.Cache.FullName; }
}
public string PublicDirectory
{
get { return this.fileSystem.Public.FullName; }
}
public string TempDirectory
{
get { return this.fileSystem.Temp.FullName; }
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[System.Serializable]
public class SoundLibraryVO
{
// public const string ASSET_
private List<SoundVO> pool = new List<SoundVO>();
SoundLibraryVO() {}
// public static SoundVO GetSoundByAsset(string a)
// {
// foreach(SoundVO s in pool)
// {
// if (s.asset == a)
// return s;
// }
// return null;
// }
public static List<SoundVO> CatClaws()
{
List<SoundVO> list = new List<SoundVO>();
SoundVO activate = new SoundVO(100, "Whip Sound 3", SoundVO.ASSET_ACTIVATE_MELEE_SWING);
SoundVO hit = new SoundVO(101, "Laser Impact Light 1", SoundVO.ASSET_IMPACT_BULLET_8);
SoundVO block_shield_physical = new SoundVO(102, "Shield Block Physical", SoundVO.ASSET_ACTIVATE_BLOCK_SHIELD_PHYSICAL);
list.Add(activate);
list.Add(hit);
list.Add(block_shield_physical);
return list;
}
public static SoundVO GetCrit(int crewType)
{
if (crewType == CharacterVO.CREW_TYPE_DEFENDER)
{
// yes!
int rng = UnityEngine.Random.Range(0, 3);
Debug.Log("<color=purple>*** " + rng + "</color>");
switch(rng)
{
case 0: return new SoundVO(1000, "Crit!", "BarbarianVP_YesHard");
case 1: return new SoundVO(1000, "Crit!", "BarbarianVP_YesHard");
case 2: return new SoundVO(1001, "Crit2!", "BarbarianVP_NoMercySoft");
}
}
else
{
// no!
int rng = UnityEngine.Random.Range(0, 3);
Debug.Log("*** " + rng);
switch (rng)
{
case 0: return new SoundVO(1002, "No!", "BarbarianVP_No(Long)Medium");
case 1: return new SoundVO(1003, "No2!", "BarbarianVP_NoHard2");
case 2: return new SoundVO(1005, "Ahh!", "BarbarianVP_AaahHard");
}
}
return null;
}
public static SoundVO GetBleed(int crewType)
{
if (crewType == CharacterVO.CREW_TYPE_DEFENDER)
{
// yes!
int rng = UnityEngine.Random.Range(0, 3);
switch (rng)
{
case 0: return new SoundVO(1000, "Bleed Soft", "BarbarianVP_BleedSoft");
case 1: return new SoundVO(1000, "Bleed Soft", "BarbarianVP_BleedSoft");
case 2: return new SoundVO(1001, "Bleed Medium", "BarbarianVP_BleedMedium");
}
}
else
{
// no!
int rng = UnityEngine.Random.Range(0, 4);
// Debug.Log("*** " + rng);
switch (rng)
{
case 0: return new SoundVO(1000, "Bleed Soft", "BarbarianVP_BleedSoft");
case 1: return new SoundVO(1000, "Bleed Soft", "BarbarianVP_BleedSoft");
case 2: return new SoundVO(1004, "Help Me", "BarbarianVP_HelpMeSoft");
case 3: return new SoundVO(1005, "Help Me", "Undead_Dialogue_Vocal_Help_Me");
}
}
return null;
}
public static SoundVO GetBurn(int crewType)
{
if (crewType == CharacterVO.CREW_TYPE_DEFENDER)
{
// yes!
int rng = UnityEngine.Random.Range(0, 3);
switch (rng)
{
case 0: return new SoundVO(1000, "Burn Soft", "BarbarianVP_BurnSoft");
case 1: return new SoundVO(1000, "Burn Soft", "BarbarianVP_BurnSoft");
case 2: return new SoundVO(1001, "Burn Hard", "BarbarianVP_BurnHard");
}
}
else
{
// no!
int rng = UnityEngine.Random.Range(0, 3);
Debug.Log("*** " + rng);
switch (rng)
{
case 0: return new SoundVO(1000, "Burn Soft", "BarbarianVP_BurnSoft");
case 1: return new SoundVO(1001, "Burn Soft", "BarbarianVP_BurnSoft");
case 2: return new SoundVO(1004, "Help Me", "BarbarianVP_HelpMeSoft");
}
}
return null;
}
public static SoundVO GetMusic()
{
return new SoundVO(1002, "Vengeance", "Vengeance (Loop)");
}
public static SoundVO GetUIFX(string type)
{
switch(type)
{
case "attack-increase": return new SoundVO(1000, "Attack Increase", SoundVO.ASSET_UI_ATTACK_INCREASE);
case "defense-increase": return new SoundVO(1001, "Defense Increase", SoundVO.ASSET_UI_DEFENSE_INCREASE);
// case "attack-decrease": return new SoundVO(1002, "Attack Decrease", )
}
return null;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CaveiraMinion : MonoBehaviour
{
public GameObject projetil;
public Transform ondeNasco;
Transform target;
public float tempoDeEspera = 5;
public float tempoAtual;
public float tempo = 1;
[SerializeField] GameObject nossoMestre;
[SerializeField] Pooling pooling;
// Start is called before the first frame update
void Start()
{
target = GameObject.FindWithTag("player").transform;
pooling = GameObject.FindWithTag("PoolingArrow").GetComponent<Pooling>();
nossoMestre = GameObject.Find("chefaocaveira_low").gameObject;
}
// Update is called once per frame
void Update()
{
if(target.gameObject == null && Pause.pausado)
{
return;
}
if (BossCaveira.contagemCaveira >= 4 || tempoAtual >= 3 || (!nossoMestre.activeInHierarchy)) /*!GameObject.FindWithTag("BossCaveira").gameObject.activeInHierarchy)*/
{
gameObject.SetActive(false);
}
OlhandoProPlayer();
transform.LookAt(target);
tempoAtual += tempo * Time.deltaTime;
if (tempoAtual >= tempoDeEspera)
{
GameObject aux = pooling.GetPooledObject();
if(aux != null)
{
aux.SetActive(true);
//print("Oi");
aux.transform.position = ondeNasco.position;
aux.transform.rotation = ondeNasco.rotation;
}
tempo = 1;
tempoAtual = 0;
}
}
void OlhandoProPlayer()
{
Vector3 targetPos = new Vector3(target.position.x, transform.position.y, target.position.z);
transform.LookAt(targetPos);
}
}
|
using Alabo.Web.Mvc.Attributes;
using System.ComponentModel.DataAnnotations;
namespace Alabo.Framework.Core.Enums.Enum {
[ClassProperty(Name = "货品类型")]
public enum MarketEnum {
/// <summary>
/// 女装男装
/// </summary>
[Display(Name = "女装男装", Description = "blue")]
[LabelCssClass(BadgeColorCalss.Metal)]
[Field(IsDefault = true, GuidId = "E97CCD1E-1478-49BD-BFC7-E73A5D699000")]
Nznz = 0,
/// <summary>
/// 鞋类箱包
/// </summary>
[Display(Name = "鞋类箱包", Description = "blue")]
[LabelCssClass(BadgeColorCalss.Metal)]
[Field(IsDefault = true, GuidId = "E97CCD1E-1478-49BD-BFC7-E73A5D699001")]
Xlxb = 1,
/// <summary>
/// 母婴用品
/// </summary>
[Display(Name = "母婴用品", Description = "blue")]
[LabelCssClass(BadgeColorCalss.Metal)]
[Field(IsDefault = true, GuidId = "E97CCD1E-1478-49BD-BFC7-E73A5D699002")]
Myyp = 2,
/// <summary>
/// 护肤彩妆
/// </summary>
[Display(Name = "护肤彩妆", Description = "blue")]
[LabelCssClass(BadgeColorCalss.Metal)]
[Field(IsDefault = true, GuidId = "E97CCD1E-1478-49BD-BFC7-E73A5D699003")]
Fhcz = 3,
/// <summary>
/// 汇吃美食
/// </summary>
[Display(Name = "汇吃美食", Description = "blue")]
[LabelCssClass(BadgeColorCalss.Metal)]
[Field(IsDefault = true, GuidId = "E97CCD1E-1478-49BD-BFC7-E73A5D699004")]
Hcms = 4,
/// <summary>
/// 家装建材
/// </summary>
[Display(Name = "家装建材", Description = "blue")]
[LabelCssClass(BadgeColorCalss.Metal)]
[Field(IsDefault = true, GuidId = "E97CCD1E-1478-49BD-BFC7-E73A5D699005")]
Jzjc = 5,
/// <summary>
/// 珠宝配饰
/// </summary>
[Display(Name = "珠宝配饰", Description = "blue")]
[LabelCssClass(BadgeColorCalss.Metal)]
[Field(IsDefault = true, GuidId = "E97CCD1E-1478-49BD-BFC7-E73A5D699006")]
Zbps = 6,
/// <summary>
/// 家居家纺
/// </summary>
[Display(Name = "家居家纺", Description = "blue")]
[LabelCssClass(BadgeColorCalss.Metal)]
[Field(IsDefault = true, GuidId = "E97CCD1E-1478-49BD-BFC7-E73A5D699007")]
Jjjf = 7,
/// <summary>
/// 百货市场
/// </summary>
[Display(Name = "百货市场", Description = "blue")]
[LabelCssClass(BadgeColorCalss.Metal)]
[Field(IsDefault = true, GuidId = "E97CCD1E-1478-49BD-BFC7-E73A5D699008")]
Bhsc = 8,
/// <summary>
/// 汽车用品
/// </summary>
[Display(Name = "汽车用品", Description = "blue")]
[LabelCssClass(BadgeColorCalss.Metal)]
[Field(IsDefault = true, GuidId = "E97CCD1E-1478-49BD-BFC7-E73A5D699009")]
Qcyp = 9,
/// <summary>
/// 手机数码
/// </summary>
[Display(Name = "手机数码", Description = "blue")]
[LabelCssClass(BadgeColorCalss.Metal)]
[Field(IsDefault = true, GuidId = "E97CCD1E-1478-49BD-BFC7-E73A5D699010")]
Sjsm = 10,
/// <summary>
/// 家电办公
/// </summary>
[Display(Name = "家电办公", Description = "blue")]
[LabelCssClass(BadgeColorCalss.Metal)]
[Field(IsDefault = true, GuidId = "E97CCD1E-1478-49BD-BFC7-E73A5D699011")]
Jdbg = 11,
/// <summary>
/// 更多服务
/// </summary>
[Display(Name = "更多服务", Description = "blue")]
[LabelCssClass(BadgeColorCalss.Metal)]
[Field(IsDefault = true, GuidId = "E97CCD1E-1478-49BD-BFC7-E73A5D699012")]
Gdff = 12,
/// <summary>
/// 生活服务
/// </summary>
[Display(Name = "生活服务", Description = "blue")]
[LabelCssClass(BadgeColorCalss.Metal)]
[Field(IsDefault = true, GuidId = "E97CCD1E-1478-49BD-BFC7-E73A5D699013")]
Shfw = 13,
/// <summary>
/// 运动户外
/// </summary>
[Display(Name = "运动户外", Description = "blue")]
[LabelCssClass(BadgeColorCalss.Metal)]
[Field(IsDefault = true, GuidId = "E97CCD1E-1478-49BD-BFC7-E73A5D699014")]
Ydhw = 14,
/// <summary>
/// 花鸟文娱
/// </summary>
[Display(Name = "花鸟文娱", Description = "blue")]
[LabelCssClass(BadgeColorCalss.Metal)]
[Field(IsDefault = true, GuidId = "E97CCD1E-1478-49BD-BFC7-E73A5D699015")]
Hnwy = 15,
/// <summary>
/// 农资采购
/// </summary>
[Display(Name = "农资采购", Description = "blue")]
[LabelCssClass(BadgeColorCalss.Metal)]
[Field(IsDefault = true, GuidId = "E97CCD1E-1478-49BD-BFC7-E73A5D699016")]
Nzcg = 16,
/// <summary>
/// 自定义
/// 适用于不使用真实货币交易的系统
/// </summary>
[Display(Name = "自定义")]
[LabelCssClass(BadgeColorCalss.Metal)]
Custom = -1
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Classes
{
public static class Messages
{
public const string cSuccessfull = "عملیات انتقال با موفقیت انجام پذیرفت" + "\n" + ";-)";
public const string cErr = "خطا";
public const string cDbConnFailed = "عدم برقراری ارتباط با دیتابیس";
public const string cFormTypeNotSelected = "لطفا فرم مربوطه را از فهرست انتخاب نمایید";
public const string cFormTypeExistsInDB2 = "شماره فرم انتخابی در دیتابیس 2 وجود دارد";
public const string cCreateNewFormTypeIDInDB2 = "آیا فرم با شماره رایانه ای جدید ایجاد شود ؟";
public const string cRemoveCurrentFormTypeIDInDB2 = "در صورتی که میخواهید دقیقا فرم مبدا با شماره رایانه ای فعلی در دیتابیس مقصد ایجاد شود، فرم با شماره رایانه ای فعلی را از دیتابیس مقصد حذف کنید" + "\n\n" +
"لطفا قبل از حذف ، حتما از دیتابیس مقصد پشتیبان تهیه فرمائید";
public const string cFormCopyConfirmation = "جهت ایجاد فرم انتخابی در دیتابیس مقصد مطمئن هستید ؟";
public const string cErrorOccured = "خطایی به وقوع پیوسته است" + "\n\n";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Data;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod()]
public static string AjaxMethodar(List<string> olist)
{
string sb = "(";
foreach (var item in olist)
{
sb = sb + "\"" + item + "\",";
}
sb = sb + "\""+DateTime.Now+"\"";
sb = sb + ")";
MySqlConnection _sqlConnect;//Mysql连接对象
MySqlCommand _sqlCommand;//Mysql命令对象
string _strConnectString;//连接字符串
_strConnectString = System.Configuration.ConfigurationManager.ConnectionStrings["sqljiuye"].ToString();//!!!数据库名需要修改!!
_sqlConnect = new MySqlConnection(_strConnectString);
_sqlCommand = new MySqlCommand("", _sqlConnect);
_sqlConnect.Open();
_sqlCommand.CommandText = "insert into `sub-area_data` values " + sb.ToString();
if (_sqlCommand.Connection == null)
{
_sqlCommand.Connection = _sqlConnect;
}
try
{
_sqlCommand.ExecuteScalar();
}
catch
{
_sqlConnect.Close();
return "0";
}
_sqlConnect.Close();
return "1";
}
[System.Web.Services.WebMethod()]
public static string AjaxMethod1()
{
//List<string> olist = new List<string>();
String str = "{\"olist\":[";
MySqlConnection _sqlConnect;//Mysql连接对象
MySqlCommand _sqlCommand;//Mysql命令对象
string _strConnectString;//连接字符串
_strConnectString = System.Configuration.ConfigurationManager.ConnectionStrings["sqljiuye"].ToString();//!!!数据库名需要修改
_sqlConnect = new MySqlConnection(_strConnectString);
_sqlCommand = new MySqlCommand("", _sqlConnect);
_sqlConnect.Open();
_sqlCommand.CommandText = "select distinct company from operatingconditions";
if (_sqlCommand.Connection == null)
{
_sqlCommand.Connection = _sqlConnect;
}
MySqlDataReader reader = _sqlCommand.ExecuteReader();
try
{
while (reader.Read())
{
str = str + "\"" + reader.GetString(0) + "\",";
}
str = str.Substring(0, str.Length - 1) + "]}";
reader.Close();
reader.Dispose();
}
catch
{
_sqlConnect.Close();
_sqlConnect.Dispose();
return "{\"olist\":[\"error \"]}"; ;
}
_sqlConnect.Close();
_sqlConnect.Dispose();
return str;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.