content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
//
// This file has been generated automatically by MonoDevelop to store outlets and
// actions made in the Xcode designer. If it is removed, they will be lost.
// Manual changes to this file may not be handled correctly.
//
using Foundation;
namespace FLAnimatedImage.Sample
{
[Register("ViewController")]
partial class ViewController
{
void ReleaseDesignerOutlets()
{
}
}
}
| 23.222222 | 81 | 0.691388 | [
"MIT"
] | Wenfengcheng/FLAnimatedImage_Xamarin | FLAnimatedImage/FLAnimatedImage.Sample/ViewController.designer.cs | 420 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the transfer-2018-11-05.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Transfer.Model
{
/// <summary>
/// Describes the properties of a user that was specified.
/// </summary>
public partial class DescribedUser
{
private string _arn;
private string _homeDirectory;
private List<HomeDirectoryMapEntry> _homeDirectoryMappings = new List<HomeDirectoryMapEntry>();
private HomeDirectoryType _homeDirectoryType;
private string _policy;
private PosixProfile _posixProfile;
private string _role;
private List<SshPublicKey> _sshPublicKeys = new List<SshPublicKey>();
private List<Tag> _tags = new List<Tag>();
private string _userName;
/// <summary>
/// Gets and sets the property Arn.
/// <para>
/// Specifies the unique Amazon Resource Name (ARN) for the user that was requested to
/// be described.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=20, Max=1600)]
public string Arn
{
get { return this._arn; }
set { this._arn = value; }
}
// Check to see if Arn property is set
internal bool IsSetArn()
{
return this._arn != null;
}
/// <summary>
/// Gets and sets the property HomeDirectory.
/// <para>
/// Specifies the landing directory (or folder), which is the location that files are
/// written to or read from in an Amazon S3 bucket, for the described user. An example
/// is <i> <code>your-Amazon-S3-bucket-name>/home/username</code> </i>.
/// </para>
/// </summary>
[AWSProperty(Max=1024)]
public string HomeDirectory
{
get { return this._homeDirectory; }
set { this._homeDirectory = value; }
}
// Check to see if HomeDirectory property is set
internal bool IsSetHomeDirectory()
{
return this._homeDirectory != null;
}
/// <summary>
/// Gets and sets the property HomeDirectoryMappings.
/// <para>
/// Specifies the logical directory mappings that specify what Amazon S3 paths and keys
/// should be visible to your user and how you want to make them visible. You will need
/// to specify the "<code>Entry</code>" and "<code>Target</code>" pair, where <code>Entry</code>
/// shows how the path is made visible and <code>Target</code> is the actual Amazon S3
/// path. If you only specify a target, it will be displayed as is. You will need to also
/// make sure that your AWS Identity and Access Management (IAM) role provides access
/// to paths in <code>Target</code>.
/// </para>
///
/// <para>
/// In most cases, you can use this value instead of the scope-down policy to lock your
/// user down to the designated home directory ("chroot"). To do this, you can set <code>Entry</code>
/// to '/' and set <code>Target</code> to the HomeDirectory parameter value.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=50)]
public List<HomeDirectoryMapEntry> HomeDirectoryMappings
{
get { return this._homeDirectoryMappings; }
set { this._homeDirectoryMappings = value; }
}
// Check to see if HomeDirectoryMappings property is set
internal bool IsSetHomeDirectoryMappings()
{
return this._homeDirectoryMappings != null && this._homeDirectoryMappings.Count > 0;
}
/// <summary>
/// Gets and sets the property HomeDirectoryType.
/// <para>
/// Specifies the type of landing directory (folder) you mapped for your users to see
/// when they log into the file transfer protocol-enabled server. If you set it to <code>PATH</code>,
/// the user will see the absolute Amazon S3 bucket paths as is in their file transfer
/// protocol clients. If you set it <code>LOGICAL</code>, you will need to provide mappings
/// in the <code>HomeDirectoryMappings</code> for how you want to make Amazon S3 paths
/// visible to your users.
/// </para>
/// </summary>
public HomeDirectoryType HomeDirectoryType
{
get { return this._homeDirectoryType; }
set { this._homeDirectoryType = value; }
}
// Check to see if HomeDirectoryType property is set
internal bool IsSetHomeDirectoryType()
{
return this._homeDirectoryType != null;
}
/// <summary>
/// Gets and sets the property Policy.
/// <para>
/// Specifies the name of the policy in use for the described user.
/// </para>
/// </summary>
[AWSProperty(Max=2048)]
public string Policy
{
get { return this._policy; }
set { this._policy = value; }
}
// Check to see if Policy property is set
internal bool IsSetPolicy()
{
return this._policy != null;
}
/// <summary>
/// Gets and sets the property PosixProfile.
/// </summary>
public PosixProfile PosixProfile
{
get { return this._posixProfile; }
set { this._posixProfile = value; }
}
// Check to see if PosixProfile property is set
internal bool IsSetPosixProfile()
{
return this._posixProfile != null;
}
/// <summary>
/// Gets and sets the property Role.
/// <para>
/// Specifies the IAM role that controls your users' access to your Amazon S3 bucket.
/// The policies attached to this role will determine the level of access you want to
/// provide your users when transferring files into and out of your Amazon S3 bucket or
/// buckets. The IAM role should also contain a trust relationship that allows a server
/// to access your resources when servicing your users' transfer requests.
/// </para>
/// </summary>
[AWSProperty(Min=20, Max=2048)]
public string Role
{
get { return this._role; }
set { this._role = value; }
}
// Check to see if Role property is set
internal bool IsSetRole()
{
return this._role != null;
}
/// <summary>
/// Gets and sets the property SshPublicKeys.
/// <para>
/// Specifies the public key portion of the Secure Shell (SSH) keys stored for the described
/// user.
/// </para>
/// </summary>
[AWSProperty(Max=5)]
public List<SshPublicKey> SshPublicKeys
{
get { return this._sshPublicKeys; }
set { this._sshPublicKeys = value; }
}
// Check to see if SshPublicKeys property is set
internal bool IsSetSshPublicKeys()
{
return this._sshPublicKeys != null && this._sshPublicKeys.Count > 0;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// Specifies the key-value pairs for the user requested. Tag can be used to search for
/// and group users for a variety of purposes.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=50)]
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property UserName.
/// <para>
/// Specifies the name of the user that was requested to be described. User names are
/// used for authentication purposes. This is the string that will be used by your user
/// when they log in to your server.
/// </para>
/// </summary>
[AWSProperty(Min=3, Max=100)]
public string UserName
{
get { return this._userName; }
set { this._userName = value; }
}
// Check to see if UserName property is set
internal bool IsSetUserName()
{
return this._userName != null;
}
}
} | 35.762452 | 109 | 0.585065 | [
"Apache-2.0"
] | KenHundley/aws-sdk-net | sdk/src/Services/Transfer/Generated/Model/DescribedUser.cs | 9,334 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options
{
[System.ComponentModel.DesignerCategory("code")] // this must be fully qualified
public abstract class AbstractOptionPageControl : UserControl
{
internal readonly OptionStore OptionStore;
private readonly List<BindingExpressionBase> _bindingExpressions = new List<BindingExpressionBase>();
public AbstractOptionPageControl(OptionStore optionStore)
{
InitializeStyles();
if (DesignerProperties.GetIsInDesignMode(this))
{
return;
}
this.OptionStore = optionStore;
}
private void InitializeStyles()
{
var groupBoxStyle = new System.Windows.Style(typeof(GroupBox));
groupBoxStyle.Setters.Add(new Setter(GroupBox.PaddingProperty, new Thickness() { Left = 7, Right = 7, Top = 7 }));
groupBoxStyle.Setters.Add(new Setter(GroupBox.MarginProperty, new Thickness() { Bottom = 3 }));
groupBoxStyle.Setters.Add(new Setter(GroupBox.ForegroundProperty, new DynamicResourceExtension(SystemColors.WindowTextBrushKey)));
Resources.Add(typeof(GroupBox), groupBoxStyle);
var checkBoxStyle = new System.Windows.Style(typeof(CheckBox));
checkBoxStyle.Setters.Add(new Setter(CheckBox.MarginProperty, new Thickness() { Bottom = 7 }));
checkBoxStyle.Setters.Add(new Setter(CheckBox.ForegroundProperty, new DynamicResourceExtension(SystemColors.WindowTextBrushKey)));
Resources.Add(typeof(CheckBox), checkBoxStyle);
var textBoxStyle = new System.Windows.Style(typeof(TextBox));
textBoxStyle.Setters.Add(new Setter(TextBox.MarginProperty, new Thickness() { Left = 7, Right = 7 }));
textBoxStyle.Setters.Add(new Setter(TextBox.ForegroundProperty, new DynamicResourceExtension(SystemColors.WindowTextBrushKey)));
Resources.Add(typeof(TextBox), textBoxStyle);
var radioButtonStyle = new System.Windows.Style(typeof(RadioButton));
radioButtonStyle.Setters.Add(new Setter(RadioButton.MarginProperty, new Thickness() { Bottom = 7 }));
radioButtonStyle.Setters.Add(new Setter(RadioButton.ForegroundProperty, new DynamicResourceExtension(SystemColors.WindowTextBrushKey)));
Resources.Add(typeof(RadioButton), radioButtonStyle);
}
protected void BindToOption(CheckBox checkbox, Option<bool> optionKey)
{
var binding = new Binding()
{
Source = new OptionBinding<bool>(OptionStore, optionKey),
Path = new PropertyPath("Value"),
UpdateSourceTrigger = UpdateSourceTrigger.Default
};
var bindingExpression = checkbox.SetBinding(CheckBox.IsCheckedProperty, binding);
_bindingExpressions.Add(bindingExpression);
}
protected void BindToOption(CheckBox checkbox, Option<int> optionKey)
{
var binding = new Binding()
{
Source = new OptionBinding<int>(OptionStore, optionKey),
Path = new PropertyPath("Value"),
UpdateSourceTrigger = UpdateSourceTrigger.Default,
Converter = new CheckBoxCheckedToIntConverter(),
};
var bindingExpression = checkbox.SetBinding(CheckBox.IsCheckedProperty, binding);
_bindingExpressions.Add(bindingExpression);
}
protected void BindToOption(CheckBox checkbox, PerLanguageOption<bool> optionKey, string languageName)
{
var binding = new Binding()
{
Source = new PerLanguageOptionBinding<bool>(OptionStore, optionKey, languageName),
Path = new PropertyPath("Value"),
UpdateSourceTrigger = UpdateSourceTrigger.Default
};
var bindingExpression = checkbox.SetBinding(CheckBox.IsCheckedProperty, binding);
_bindingExpressions.Add(bindingExpression);
}
protected void BindToOption(TextBox textBox, Option<int> optionKey)
{
var binding = new Binding()
{
Source = new OptionBinding<int>(OptionStore, optionKey),
Path = new PropertyPath("Value"),
UpdateSourceTrigger = UpdateSourceTrigger.Default
};
var bindingExpression = textBox.SetBinding(TextBox.TextProperty, binding);
_bindingExpressions.Add(bindingExpression);
}
protected void BindToOption(TextBox textBox, PerLanguageOption<int> optionKey, string languageName)
{
var binding = new Binding()
{
Source = new PerLanguageOptionBinding<int>(OptionStore, optionKey, languageName),
Path = new PropertyPath("Value"),
UpdateSourceTrigger = UpdateSourceTrigger.Default
};
var bindingExpression = textBox.SetBinding(TextBox.TextProperty, binding);
_bindingExpressions.Add(bindingExpression);
}
protected void BindToOption<T>(RadioButton radiobutton, PerLanguageOption<T> optionKey, T optionValue, string languageName)
{
var binding = new Binding()
{
Source = new PerLanguageOptionBinding<T>(OptionStore, optionKey, languageName),
Path = new PropertyPath("Value"),
UpdateSourceTrigger = UpdateSourceTrigger.Default,
Converter = new RadioButtonCheckedConverter(),
ConverterParameter = optionValue
};
var bindingExpression = radiobutton.SetBinding(RadioButton.IsCheckedProperty, binding);
_bindingExpressions.Add(bindingExpression);
}
internal virtual void OnLoad()
{
foreach (var bindingExpression in _bindingExpressions)
{
bindingExpression.UpdateTarget();
}
}
internal virtual void OnSave()
{
}
internal virtual void Close()
{
}
}
public class RadioButtonCheckedConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return value.Equals(parameter);
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return value.Equals(true) ? parameter : Binding.DoNothing;
}
}
public class CheckBoxCheckedToIntConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return !value.Equals(-1);
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return value.Equals(true) ? 1 : -1;
}
}
}
| 40.684492 | 148 | 0.64511 | [
"Apache-2.0"
] | Sliptory/roslyn | src/VisualStudio/Core/Impl/Options/AbstractOptionPageControl.cs | 7,610 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Xamarin.Forms.Platform.Android;
using MyDataPick.Droid.Renderers;
using Xamarin.Forms;
using MyDataPick.Droid.Handler;
using MyDataPick.Droid.Helpers;
using Android.Graphics;
using Android.Icu.Util;
using Android.Text;
[assembly: ExportRenderer(typeof(MyDataPick.Views.ScrollMonthDateView), typeof(ScrollMonthDateViewRenderer))]
namespace MyDataPick.Droid.Renderers
{
public class ScrollMonthDateViewRenderer : ViewRenderer<MyDataPick.Views.ScrollMonthDateView, Android.Views.View>, IDisposable
{
protected int NUM_COLUMNS = 7;
protected int NUM_ROWS = 6;
protected Paint paint;
//protected IDayTheme theme;
//private IMonthLisener monthLisener;
//private IDateClick dateClick;
protected int currYear, currMonth, currDay;
protected int selYear, selMonth, selDay;
private int leftYear, leftMonth, leftDay;
private int rightYear, rightMonth, rightDay;
private int[,] daysString;
protected float columnSize, rowSize, baseRowSize;
private int mTouchSlop;
protected float density;
private int indexMonth;
private int width;
//protected List<CalendarInfo> calendarInfos = new ArrayList<CalendarInfo>();
private int downX = 0, downY = 0;
private Scroller mScroller;
private int smoothMode;
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
density = Resources.DisplayMetrics.Density;// getResources().getDisplayMetrics().density;
mScroller = new Scroller(this.Context);
mTouchSlop = ViewConfiguration.Get(this.Context).ScaledDoubleTapSlop;//.GetScaledTouchSlop();
Calendar calendar = Calendar.Instance;//.GetInstance();
currYear = calendar.Get(Calendar.Year);
currMonth = calendar.Get(Calendar.Month);
currDay = calendar.Get(Calendar.Date);
paint = new Paint(PaintFlags.AntiAlias);
SetSelectDate(currYear, currMonth, currDay);
SetLeftDate();
SetRightDate();
//createTheme();
baseRowSize = rowSize = 70;// theme == null ? 70 : theme.dateHeight();
smoothMode = 0;// theme == null ? 0 : theme.smoothMode();
}
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int widthSize = MeasureSpec.GetSize(widthMeasureSpec);
MeasureSpecMode widthMode = MeasureSpec.GetMode(widthMeasureSpec);
if (widthMode == MeasureSpecMode.AtMost)
{
widthSize = (int)(300 * density);
}
width = widthSize;
NUM_ROWS = 6; //本来是想根据每月的行数,动态改变控件高度,现在为了使滑动的左右两边效果相同,不适用getMonthRowNumber();
int heightSize = (int)(NUM_ROWS * baseRowSize);
SetMeasuredDimension(widthSize, heightSize);
}
protected override void OnDraw(Canvas canvas)
{
//canvas.DrawColor(Android.Graphics.Color.YellowGreen);
if (smoothMode == 1)
{
DrawDate(canvas, selYear, selMonth, indexMonth * width, 0);
return;
}
//绘制上一月份
DrawDate(canvas, leftYear, leftMonth, (indexMonth - 1) * width, 0);
//绘制下一月份
DrawDate(canvas, rightYear, rightMonth, (indexMonth + 1) * width, 0);
//绘制当前月份
DrawDate(canvas, selYear, selMonth, indexMonth * width, 0);
}
private void DrawDate(Canvas canvas, int year, int month, int startX, int startY)
{
canvas.Save();
canvas.Translate(startX, startY);
NUM_ROWS = GetMonthRowNumber(year, month);
columnSize = Width * 1.0F / NUM_COLUMNS;
rowSize = Height * 1.0F / NUM_ROWS;
daysString = new int[6, 7];
int mMonthDays = DateUtils.getMonthDays(year, month);
int weekNumber = DateUtils.getFirstDayWeek(year, month);
int column, row;
DrawLines(canvas, NUM_ROWS);
for (int day = 0; day < mMonthDays; day++)
{
column = (day + weekNumber - 1) % 7;
row = (day + weekNumber - 1) / 7;
daysString[row, column] = day + 1;
DrawBG(canvas, column, row, daysString[row, column]);
DrawDecor(canvas, column, row, year, month, daysString[row, column]);
DrawRest(canvas, column, row, year, month, daysString[row, column]);
DrawText(canvas, column, row, year, month, daysString[row, column]);
}
canvas.Restore();//.restore();
}
protected void DrawLines(Canvas canvas, int rowsCount)
{
int rightX = Width;
Path path;
float startX = 0;
float endX = rightX;
paint.SetStyle(Paint.Style.Stroke);
paint.Color = Android.Graphics.Color.Black;
for (int row = 1; row <= rowsCount; row++)
{
float startY = row * rowSize;
path = new Path();
path.MoveTo(startX, startY);
path.LineTo(endX, startY);
canvas.DrawPath(path, paint);
}
}
protected void DrawBG(Canvas canvas, int column, int row, int day)
{
float startRecX = columnSize * column + 1;
float startRecY = rowSize * row + 1;
float endRecX = startRecX + columnSize - 2 * 1;
float endRecY = startRecY + rowSize - 2 * 1;
float cx = (startRecX + endRecX) / 2;
float cy = (startRecY + endRecY) / 2;
float radius = columnSize < (rowSize * 0.6) ? columnSize / 2 : (float)(rowSize * 0.6) / 2;
paint.Color = Android.Graphics.Color.Red;
if (day == selDay)
{ //绘制背景色圆形
paint.SetStyle(Paint.Style.Fill);
canvas.DrawCircle(cx, cy, radius, paint);
}
if (day == currDay && currDay != selDay && currMonth == selMonth)
{//今日绘制圆环
paint.SetStyle(Paint.Style.Stroke);
canvas.DrawCircle(cx, cy, radius, paint);
}
}
protected void DrawDecor(Canvas canvas, int column, int row, int year, int month, int day)
{
//if (calendarInfos != null && calendarInfos.size() > 0)
//{
// if (TextUtils.isEmpty(iscalendarInfo(year, month, day))) return;
// paint.setColor(theme.colorDecor());
// paint.setStyle(Paint.Style.FILL);
// float circleX = (float)(columnSize * column + columnSize * 0.5);
// float circleY = (float)(rowSize * row + rowSize * 0.25);
// if (day == selDay)
// {//选中日期无事务
// circleY = (float)(rowSize * row + rowSize * 0.1);
// }
// canvas.drawCircle(circleX, circleY, theme.sizeDecor(), paint);
//}
}
protected void DrawRest(Canvas canvas, int column, int row, int year, int month, int day)
{
//if (calendarInfos != null && calendarInfos.size() > 0)
//{
// float radius = columnSize < (rowSize * 0.6) ? columnSize / 2 : (float)(rowSize * 0.6) / 2;
// for (CalendarInfo calendarInfo : calendarInfos)
// {
// if (calendarInfo.day == day && calendarInfo.year == year && calendarInfo.month == month + 1)
// {
// float restX = columnSize * column + (columnSize + paint.measureText(day + "")) / 2;
// float restY = rowSize * row + rowSize / 2 - (paint.ascent() + paint.descent()) / 2;
// if (day == selDay)
// {
// restX = columnSize * column + columnSize / 2 + radius;
// }
// paint.setStyle(Paint.Style.FILL);
// if (calendarInfo.rest == 2)
// {//班
// paint.setColor(theme.colorWork());
// paint.setTextSize(theme.sizeDesc());
// paint.measureText("班");
// canvas.drawText("班", restX, restY, paint);
// }
// else if (calendarInfo.rest == 1)
// {//休息
// paint.setColor(theme.colorRest());
// paint.setTextSize(theme.sizeDesc());
// canvas.drawText("休", restX, restY, paint);
// }
// }
// }
//}
}
protected void DrawText(Canvas canvas, int column, int row, int year, int month, int day)
{
paint.TextSize = 30;//.SetTextSize(theme.sizeDay());
float startX = columnSize * column + (columnSize - paint.MeasureText(day + "")) / 2;
float startY = rowSize * row + rowSize / 2 - (paint.Ascent() + paint.Descent()) / 2;
paint.SetStyle(Paint.Style.Stroke);
string des = IscalendarInfo(year, month, day);
if (day == selDay)
{//日期为选中的日期
if (!TextUtils.IsEmpty(des))
{//desc不为空的时候
int dateY = (int)startY;
paint.Color = Android.Graphics.Color.SeaGreen;//.setColor(theme.colorSelectDay());
canvas.DrawText(day + "", startX, dateY, paint);
paint.Color = Android.Graphics.Color.Black;//.setColor(theme.colorWeekday());
paint.TextSize = 18;//.SetTextSize(theme.sizeDesc());
int desX = (int)(columnSize * column + (columnSize - paint.MeasureText(des)) / 2);
int desY = (int)(rowSize * row + rowSize * 0.9 - (paint.Ascent() + paint.Descent()) / 2);
canvas.DrawText(des, desX, desY, paint);
}
else
{//des为空的时候
paint.Color = Android.Graphics.Color.Orange;//.setColor(theme.colorSelectDay());
canvas.DrawText(day + "", startX, startY, paint);
}
}
else if (day == currDay && currDay != selDay && currMonth == selMonth)
{//今日的颜色,不是选中的时候
//正常月,选中其他日期,则今日为红色
paint.Color = Android.Graphics.Color.Red;//.setColor(theme.colorToday());
canvas.DrawText(day + "", startX, startY, paint);
}
else
{
if (!TextUtils.IsEmpty(des))
{//没选中,但是desc不为空
int dateY = (int)startY;
paint.Color = Android.Graphics.Color.Black;//.setColor(theme.colorWeekday());
canvas.DrawText(day + "", startX, dateY, paint);
paint.TextSize = 18;//.setTextSize(theme.sizeDesc());
paint.Color = Android.Graphics.Color.Red;//.setColor(theme.colorDesc());
int desX = (int)(columnSize * column + Math.Abs((columnSize - paint.MeasureText(des)) / 2));
int desY = (int)(startY + 20);
canvas.DrawText(des, desX, desY, paint);
}
else
{//des为空
paint.Color = Android.Graphics.Color.LawnGreen;//.SetColor(theme.colorWeekday());
canvas.DrawText(day + "", startX, startY, paint);
}
}
}
/**
* 判断是否为事务天数,通过获取desc来辨别
* @param day
* @return
*/
protected string IscalendarInfo(int year, int month, int day)
{
//if (CalendarInfos == null || calendarInfos.size() == 0) return "";
//for (CalendarInfo calendarInfo : calendarInfos)
//{
// if (calendarInfo.day == day && calendarInfo.month == month + 1 && calendarInfo.year == year)
// {
// return calendarInfo.des;
// }
//}
return "";
}
//protected abstract void DrawLines(Canvas canvas, int rowsCount);
//protected abstract void DrawBG(Canvas canvas, int column, int row, int day);
//protected abstract void DrawDecor(Canvas canvas, int column, int row, int year, int month, int day);
//protected abstract void DrawRest(Canvas canvas, int column, int row, int year, int month, int day);
//protected abstract void DrawText(Canvas canvas, int column, int row, int year, int month, int day);
private int lastMoveX;
public override bool OnTouchEvent(MotionEvent e)
{
MotionEventActions eventCode = e.Action;//.getAction();
switch (eventCode)
{
case MotionEventActions.Down:
downX = (int)e.GetX();// GetX();
downY = (int)e.GetY();
break;
case MotionEventActions.Move:
if (smoothMode == 1) break;
float dxx = downX - e.GetX();
int dx = (int)(downX - e.GetX());
if (Math.Abs(dx) > mTouchSlop)
{
int moveX = dx + lastMoveX;
SmoothScrollTo(moveX, 0);
}
break;
case MotionEventActions.Up:
int upX = (int)e.GetX();
int upY = (int)e.GetY();
if (upX - downX > 0 && Math.Abs(upX - downX) > mTouchSlop)
{//左滑
if (smoothMode == 0)
{
SetLeftDate();
indexMonth--;
}
else
{
//onLeftClick();
}
}
else if (upX - downX < 0 && Math.Abs(upX - downX) > mTouchSlop)
{//右滑
if (smoothMode == 0)
{
SetRightDate();
indexMonth++;
}
else
{
//onRightClick();
}
}
else if (Math.Abs(upX - downX) < 10 && Math.Abs(upY - downY) < 10)
{//点击事件
//performClick();
//doClickAction((upX + downX)/2,(upY + downY)/2);
}
if (smoothMode == 0)
{
lastMoveX = indexMonth * width;
SmoothScrollTo(width * indexMonth, 0);
}
break;
}
return true;
}
//调用此方法滚动到目标位置
public void SmoothScrollTo(int fx, int fy)
{
int dx = fx - mScroller.FinalX;//.getFinalX();
int dy = fy - mScroller.FinalY;//.getFinalY();
SmoothScrollBy(dx, dy);
}
//调用此方法设置滚动的相对偏移
public void SmoothScrollBy(int dx, int dy)
{
//设置mScroller的滚动偏移量
mScroller.StartScroll(mScroller.FinalX, mScroller.FinalY, dx, dy, 500);
Invalidate();//这里必须调用invalidate()才能保证computeScroll()会被调用,否则不一定会刷新界面,看不到滚动效果
}
public override void ComputeScroll()
{
if (mScroller.ComputeScrollOffset())
{
ScrollTo(mScroller.CurrX, mScroller.CurrY);
Invalidate();
}
//base.ComputeScroll();
}
/**
* 设置选中的月份
* @param year
* @param month
*/
protected void SetSelectDate(int year, int month, int day)
{
selYear = year;
selMonth = month;
selDay = day;
}
private void SetRightDate()
{
int year = selYear;
int month = selMonth;
int day = selDay;
if (month == 11)
{//若果是12月份,则变成1月份
year = selYear + 1;
month = 0;
}
else if (DateUtils.getMonthDays(year, month + 1) < day)
{//向右滑动,当前月天数小于左边的
//如果当前日期为该月最后一点,当向前推的时候,就需要改变选中的日期
month = month + 1;
day = DateUtils.getMonthDays(year, month);
}
else
{
month = month + 1;
}
SetSelectDate(year, month, day);
computeDate();
}
private void SetLeftDate()
{
int year = selYear;
int month = selMonth;
int day = selDay;
if (month == 0)
{//若果是1月份,则变成12月份
year = selYear - 1;
month = 11;
}
else if (DateUtils.getMonthDays(year, month - 1) < day)
{//向左滑动,当前月天数小于左边的
//如果当前日期为该月最后一点,当向前推的时候,就需要改变选中的日期
month = month - 1;
day = DateUtils.getMonthDays(year, month);
}
else
{
month = month - 1;
}
SetSelectDate(year, month, day);
computeDate();
}
private void computeDate()
{
if (selMonth == 0)
{
leftYear = selYear - 1;
leftMonth = 11;
rightYear = selYear;
rightMonth = selMonth + 1;
}
else if (selMonth == 11)
{
leftYear = selYear;
leftMonth = selMonth - 1;
rightYear = selYear + 1;
rightMonth = 0;
}
else
{
leftYear = selYear;
leftMonth = selMonth - 1;
rightYear = selYear;
rightMonth = selMonth + 1;
}
//if (monthLisener != null)
//{
// monthLisener.setTextMonth();
//}
}
protected int GetMonthRowNumber(int year, int month)
{
int monthDays = DateUtils.getMonthDays(year, month);
int weekNumber = DateUtils.getFirstDayWeek(year, month);
return (monthDays + weekNumber - 1) % 7 == 0 ? (monthDays + weekNumber - 1) / 7 : (monthDays + weekNumber - 1) / 7 + 1;
}
}
} | 39.765199 | 131 | 0.486345 | [
"Apache-2.0"
] | Ling2048/Xamarin.CustomDatePick | MyDataPick/MyDataPick.Android/Renderers/ScrollMonthDateViewRenderer.cs | 19,688 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class MemoryController : MonoBehaviour {
//recursos
public Object[] fotos;
public Object[] noms;
public Object[] backs;
public Object[] audio_hits;
public Object[] llista_sprites;
public GameObject[] llista_gameobjs;
//ordre
public int[] llista_alumnes;
public int[] llista_cartes;
public bool flipping=false;
// random generator
private System.Random rnd;
float width,height,left_padding, top_padding, card_height;
GameObject cardHolder;
GridLayoutGroup cardholder_glg;
GameObject selected_item=null;
int marcador_hits=0;
int marcador_misses=0;
bool flip_selected=false;
ParticleSystem win_particles;
Text hit_txt;
Text selected_txt;
AudioSource sound;
// Use this for initialization
void Start ()
{
width = Screen.currentResolution.width;
height = Screen.currentResolution.height;
hit_txt = (Text)GameObject.Find("hit").GetComponent(typeof(Text));
selected_txt = (Text)GameObject.Find("selected").GetComponent(typeof(Text));
hit_txt.enabled=Application.isEditor;
selected_txt.enabled=Application.isEditor;
Debug.Log("screen: w" + width + "h" + height);
cardHolder = GameObject.Find("CardHolder");
win_particles = (ParticleSystem)GameObject.Find("win_particles").GetComponent(typeof(ParticleSystem));
sound = (AudioSource)GameObject.Find("sound").GetComponent(typeof(AudioSource));
left_padding = width/3;
top_padding = height/8;
card_height = (height/8)*3;
cardholder_glg = cardHolder.GetComponent<GridLayoutGroup>();
//cardholder_glg.padding.left = (int)left_padding;
//cardholder_glg.padding.top = (int)top_padding;
rnd = new System.Random();
fotos = Resources.LoadAll(path: "Fotos", systemTypeInstance: typeof(Sprite));
noms = Resources.LoadAll(path: "Noms", systemTypeInstance: typeof(Sprite));
backs = Resources.LoadAll(path: "Backs", systemTypeInstance: typeof(Sprite));
audio_hits = Resources.LoadAll(path: "Audios", systemTypeInstance: typeof(AudioClip));
Debug.Log("level#: " + Settings.Level);
Debug.Log("card#: " + Settings.Cards);
Debug.Log("#fotos: " + fotos.Length);
Debug.Log("#noms: " + noms.Length);
Debug.Log("# audio hits: " + this.audio_hits.Length);
this.llista_alumnes = new int[fotos.Length];
for (int i = 0; i < this.llista_alumnes.Length; i++)
{
this.llista_alumnes[i] = i;
}
//desordenar
this.llista_alumnes = Enumerable.Range(0, this.llista_alumnes.Length).OrderBy(r => rnd.Next()).ToArray();
this.llista_cartes = new int[Settings.Cards*2];
this.llista_sprites = new Object[Settings.Cards*2];
this.llista_gameobjs = new GameObject[Settings.Cards*2];
Debug.Log("Settings cartes: "+Settings.Cards);
Debug.Log("total cartes: "+this.llista_cartes.Length);
for (int i = 0; i < Settings.Cards; i++)
{
this.llista_cartes[i] = llista_alumnes[i];
//Debug.Log("carta["+i+"]="+this.llista_cartes[i]);
// afegeix parella a N+i
this.llista_cartes[Settings.Cards+i] = llista_alumnes[i];
//Debug.Log("carta["+(Settings.Cards+i)+"]="+this.llista_cartes[i]);
switch (Settings.Level)
{
case 0:
// facil
Debug.Log("*X facil");
this.llista_sprites[i] = fotos[this.llista_cartes[i]];
Debug.Log("sprite["+i+"]="+this.llista_sprites[i].name);
this.llista_sprites[Settings.Cards+i] = fotos[this.llista_cartes[i]];
Debug.Log("sprite["+(Settings.Cards+i)+"]="+this.llista_sprites[(Settings.Cards+i)].name);
break;
case 1:
//mig
Debug.Log("*X mig");
this.llista_sprites[i] = noms[this.llista_cartes[i]];
this.llista_sprites[Settings.Cards+i] = noms[this.llista_cartes[i]];
Debug.Log((fotos[this.llista_cartes[i]].name));
break;
default:
// dificil
Debug.Log("*X dificil");
this.llista_sprites[i] = fotos[this.llista_cartes[i]];
this.llista_sprites[Settings.Cards+i] = noms[this.llista_cartes[i]];
Debug.Log((fotos[this.llista_cartes[i]].name));
break;
}
}
//Debug.Log("PRE RANDOM - this.llista_sprites: ");
//for (int i = 0; i < this.llista_sprites.Length; i++)
//{
// Debug.Log(i+": "+this.llista_sprites[i].name);
//}
Object mytmpobj;
int mytmpint;
//desordenar cartes escollides - inclou les parelles
for (int i = 0; i < this.llista_sprites.Length; i++)
{
int random_index = rnd.Next(i, this.llista_sprites.Length);
if(random_index==i) continue;
Debug.Log("randomize: "+i+" <-> "+random_index);
Debug.Log("randomize: "+this.llista_sprites[i].name+" <-> "+this.llista_sprites[random_index].name);
mytmpint = this.llista_cartes[i];
mytmpobj = this.llista_sprites[i];
this.llista_cartes[i] = this.llista_cartes[random_index];
this.llista_sprites[i] = this.llista_sprites[random_index];
this.llista_cartes[random_index] = mytmpint;
this.llista_sprites[random_index] = mytmpobj;
}
Debug.Log("this.llista_cartes: ");
for (int i = 0; i < this.llista_cartes.Length; i++)
{
Debug.Log(i+": "+this.llista_cartes[i]);
}
Debug.Log("this.llista_sprites: ");
for (int i = 0; i < this.llista_sprites.Length; i++)
{
Debug.Log(i+": "+this.llista_sprites[i].name);
}
for (int i = 0; i < this.llista_sprites.Length; i++)
{
GameObject item = new GameObject(this.llista_cartes[i]+" "+this.llista_sprites[i].name);
item.AddComponent(typeof(RectTransform));
item.AddComponent(typeof(BoxCollider2D));
item.AddComponent(typeof(FlipController));
item.transform.SetParent(cardholder_glg.transform);
GameObject card_front=new GameObject(this.llista_cartes[i]+" "+this.llista_sprites[i].name+" front");
card_front.AddComponent(typeof(SpriteRenderer));
card_front.AddComponent(typeof(RectTransform));
//newGO.transform.parent = cardholder_glg.transform;
card_front.transform.SetParent(item.transform);
//newGO.transform.localScale = new Vector3( 1, 1, 1 );
//newGO.transform.localPosition = Vector3.zero;
card_front.GetComponent<SpriteRenderer>().sprite = this.llista_sprites[i] as Sprite;
card_front.GetComponent<SpriteRenderer>().drawMode = SpriteDrawMode.Sliced;
//newGO.GetComponent<SpriteRenderer>().size += new Vector2(0.05f, 0.01f);
//newGO.GetComponent<SpriteRenderer>().size = new Vector2(5,6);
item.GetComponent<BoxCollider2D>().size = card_front.GetComponent<SpriteRenderer>().sprite.bounds.size;
GameObject card_back=new GameObject(this.llista_cartes[i]+" "+this.llista_sprites[i].name+" back");
card_back.AddComponent(typeof(SpriteRenderer));
card_back.AddComponent(typeof(RectTransform));
//newGO.transform.parent = cardholder_glg.transform;
card_back.transform.SetParent(item.transform);
//newGO.transform.localScale = new Vector3( 1, 1, 1 );
//newGO.transform.localPosition = Vector3.zero;
card_back.GetComponent<SpriteRenderer>().sprite = this.backs[0] as Sprite;
card_back.GetComponent<SpriteRenderer>().drawMode = SpriteDrawMode.Sliced;
//newGO.GetComponent<SpriteRenderer>().size += new Vector2(0.05f, 0.01f);
//newGO.GetComponent<SpriteRenderer>().size = new Vector2(5,6);
card_back.transform.position = new Vector3(card_back.transform.position.x, card_back.transform.position.y, (float)-0.0001);
this.llista_gameobjs[i]=item;
}
//Un cop tenim l'entorn preparat posem el play
//background_sound.loop=true;
//background_sound.clip = (AudioClip) Resources.Load("Audios/loop_horitzo");
//background_sound.Play();
}
void Update ()
{
FlipController hit_flip_controller;
FlipController selected_flip_controller;
if(Input.GetMouseButton(0) && !flipping)
{
var inputPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D[] touches = Physics2D.RaycastAll(inputPosition, inputPosition, 0.5f);
if (touches.Length > 0)
{
//Debug.Log("touche!");
var hit = touches[0];
if (hit.transform != null)
{
if(selected_item==null)
{
if(!flip_selected)
{
if(!((FlipController)hit.transform.gameObject.GetComponent(typeof(FlipController))).blocked)
{
Debug.Log("seleccionat "+hit.transform.gameObject.name);
selected_item = hit.transform.gameObject;
flip_selected=true;
selected_flip_controller = (FlipController)selected_item.GetComponent(typeof(FlipController));
selected_flip_controller.FlipCard();
selected_txt.text = selected_item.name;
}
}
else Debug.Log("skipped select");
}
else
{
if(hit.transform.position!=selected_item.transform.position && !((FlipController)hit.transform.gameObject.GetComponent(typeof(FlipController))).blocked)
{
Debug.Log(hit.transform.gameObject.name+" <> "+selected_item.name);
Debug.Log(hit.transform.gameObject.transform.position+" <> "+selected_item.transform.position);
hit_txt.text = hit.transform.gameObject.name;
hit_flip_controller = (FlipController)hit.transform.gameObject.GetComponent(typeof(FlipController));
hit_flip_controller.FlipCard();
if(hit.transform.gameObject.name==selected_item.name)
{
Debug.Log("hit");
this.PlayRandomHit();
marcador_hits++;
selected_flip_controller = (FlipController)selected_item.GetComponent(typeof(FlipController));
selected_flip_controller.blocked=true;
hit_flip_controller = (FlipController)hit.transform.gameObject.GetComponent(typeof(FlipController));
hit_flip_controller.blocked=true;
//check win condition
int blocked_counter=0;
for (int i = 0; i < this.llista_gameobjs.Length; i++)
{
if(((FlipController)(llista_gameobjs[i].GetComponent(typeof(FlipController)))).blocked)
blocked_counter++;
}
if(blocked_counter==this.llista_gameobjs.Length)
StartCoroutine(WinMode());
}
else
{
Debug.Log("miss");
marcador_misses++;
//flip back selected & hit
selected_flip_controller = (FlipController)selected_item.GetComponent(typeof(FlipController));
hit_flip_controller = (FlipController)hit.transform.gameObject.GetComponent(typeof(FlipController));
selected_flip_controller.FlipCard();
hit_flip_controller.FlipCard();
}
selected_item=null;
flip_selected=true;
selected_txt.text="NULL";
}
}
}
}
}
else
{
flip_selected=false;
}
}
private void PlayRandomHit()
{
if(this.audio_hits.Length!=0)
{
int random_index = rnd.Next(0, this.audio_hits.Length);
Debug.Log("playing audio "+random_index);
sound.clip = (AudioClip)this.audio_hits[random_index];
sound.Play();
}
else Debug.Log("skipping audio");
}
IEnumerator WinMode()
{
win_particles.Play();
yield return new WaitForSeconds(10.0f);
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
| 32.80057 | 159 | 0.66629 | [
"Apache-2.0"
] | jordiprats/unity3d-memory | Assets/Scripts/MemoryController.cs | 11,515 | C# |
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public class XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapDCETModelC2M_ReloadWrapWrapWrapWrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Type type = typeof(XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapDCETModelC2M_ReloadWrapWrapWrap);
Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0);
Utils.EndObjectRegister(type, L, translator, null, null,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0);
Utils.RegisterFunc(L, Utils.CLS_IDX, "__Register", _m___Register_xlua_st_);
Utils.EndClassRegister(type, L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CreateInstance(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
if(LuaAPI.lua_gettop(L) == 1)
{
XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapDCETModelC2M_ReloadWrapWrapWrap gen_ret = new XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapDCETModelC2M_ReloadWrapWrapWrap();
translator.Push(L, gen_ret);
return 1;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapDCETModelC2M_ReloadWrapWrapWrap constructor!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m___Register_xlua_st_(RealStatePtr L)
{
try {
{
System.IntPtr _L = LuaAPI.lua_touserdata(L, 1);
XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapDCETModelC2M_ReloadWrapWrapWrap.__Register( _L );
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
}
}
| 25.754545 | 185 | 0.593717 | [
"MIT"
] | zxsean/DCET | Unity/Assets/Model/XLua/Gen/XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapDCETModelC2M_ReloadWrapWrapWrapWrap.cs | 2,835 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Azure.ContainerService.Outputs
{
[OutputType]
public sealed class KubernetesClusterAddonProfileAzurePolicy
{
/// <summary>
/// Is the Azure Policy for Kubernetes Add On enabled?
/// </summary>
public readonly bool Enabled;
[OutputConstructor]
private KubernetesClusterAddonProfileAzurePolicy(bool enabled)
{
Enabled = enabled;
}
}
}
| 27.107143 | 88 | 0.679842 | [
"ECL-2.0",
"Apache-2.0"
] | AdminTurnedDevOps/pulumi-azure | sdk/dotnet/ContainerService/Outputs/KubernetesClusterAddonProfileAzurePolicy.cs | 759 | C# |
using System;
using System.Linq;
namespace QuickApp.ViewModels
{
public class PermissionViewModel
{
public string Name { get; set; }
public string Value { get; set; }
public string GroupName { get; set; }
public string Description { get; set; }
}
}
| 18.5625 | 47 | 0.619529 | [
"MIT"
] | yomi7117/Hospital-management-system | src/QuickApp/ViewModels/PermissionViewModel.cs | 299 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Ploeh.SemanticComparison
{
internal class ProxyType
{
private readonly ConstructorInfo constructor;
private readonly IEnumerable<object> parameters;
internal ProxyType(
ConstructorInfo constructor,
params object[] parameters)
{
if (constructor == null)
throw new ArgumentNullException("constructor");
if (parameters == null)
throw new ArgumentNullException("parameters");
this.constructor = constructor;
this.parameters = parameters;
}
internal ConstructorInfo Constructor
{
get { return this.constructor; }
}
internal IEnumerable<object> Parameters
{
get { return this.parameters; }
}
}
}
| 25.368421 | 64 | 0.576763 | [
"MIT"
] | TeaDrivenDev/AutoFixture | Src/SemanticComparison/ProxyType.cs | 966 | C# |
namespace Certes.Acme.Resource
{
/// <summary>
/// Represents status of <see cref="Identifier"/>.
/// </summary>
public static class IdentifierStatus
{
/// <summary>
/// The pending status.
/// </summary>
public const string Pending = "pending";
/// <summary>
/// The processing status.
/// </summary>
public const string Processing = "processing";
/// <summary>
/// The valid status.
/// </summary>
public const string Valid = "valid";
/// <summary>
/// The invalid status.
/// </summary>
public const string Invalid = "invalid";
/// <summary>
/// The revoked status.
/// </summary>
public const string Revoked = "revoked";
}
}
| 24.058824 | 54 | 0.50978 | [
"MIT"
] | AMEST/certes | src/Certes/Acme/Resource/IdentifierStatus.cs | 820 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TSqlStrong.TypeSystem;
using TSqlStrong.Symbols;
namespace TSqlStrong.Ast
{
public class ExpressionResult
{
private readonly ISymbolReference _symbolReference;
private readonly DataType _typeOfExpression;
private readonly RefinementSetCases _refinementCases;
public static readonly ExpressionResult Statement = new ExpressionResult(VoidDataType.Instance);
public ExpressionResult(ISymbolReference symbolReference, DataType typeOfExpression, RefinementSetCases refinementCases)
{
_symbolReference = symbolReference;
_typeOfExpression = typeOfExpression;
_refinementCases = refinementCases;
}
public ExpressionResult(DataType typeOfExpression) : this(Symbols.SymbolReference.None, typeOfExpression, RefinementSetCases.Empty)
{ }
public ExpressionResult(ISymbolReference symbolReference, DataType typeOfExpression) : this(symbolReference, typeOfExpression, RefinementSetCases.Empty)
{ }
public ISymbolReference SymbolReference => _symbolReference;
/// <summary>
/// The type of the expression itself.
/// </summary>
public DataType TypeOfExpression => _typeOfExpression;
/// <summary>
/// Any refinements we can make to symbols based upon this expression (only makes sense if TypeOfExpresison is boolean)
/// </summary>
public RefinementSetCases RefinementCases => _refinementCases;
public ExpressionResult WithNewTypeOfExpression(DataType typeOfExpression)
{
return new ExpressionResult(this.SymbolReference, typeOfExpression, this.RefinementCases);
}
public ExpressionResult WithNewSymbolReferenceAndTypeOfExpression(ISymbolReference symbolReference, DataType typeOfExpressin)
{
return new ExpressionResult(symbolReference, typeOfExpressin, this.RefinementCases);
}
}
}
| 38.290909 | 160 | 0.717949 | [
"MIT"
] | JSuder-xx/TSqlStrong | TSqlStrong/Ast/ExpressionResult.cs | 2,108 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Identity.Client.Core;
namespace Microsoft.Identity.Client.Http
{
/// <remarks>
/// We invoke this class from different threads and they all use the same HttpClient.
/// To prevent race conditions, make sure you do not get / set anything on HttpClient itself,
/// instead rely on HttpRequest objects which are thread specific.
///
/// In particular, do not change any properties on HttpClient such as BaseAddress, buffer sizes and Timeout. You should
/// also not access DefaultRequestHeaders because the getters are not thread safe (use HttpRequestMessage.Headers instead).
/// </remarks>
internal class HttpManager : IHttpManager
{
private readonly IMsalHttpClientFactory _httpClientFactory;
public HttpManager(IMsalHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory ??
throw new ArgumentNullException(nameof(httpClientFactory));
}
protected virtual HttpClient GetHttpClient()
{
return _httpClientFactory.GetHttpClient();
}
public async Task<HttpResponse> SendPostAsync(
Uri endpoint,
IDictionary<string, string> headers,
IDictionary<string, string> bodyParameters,
ICoreLogger logger)
{
HttpContent body = bodyParameters == null ? null : new FormUrlEncodedContent(bodyParameters);
return await SendPostAsync(endpoint, headers, body, logger).ConfigureAwait(false);
}
public async Task<HttpResponse> SendPostAsync(
Uri endpoint,
IDictionary<string, string> headers,
HttpContent body,
ICoreLogger logger)
{
return await ExecuteWithRetryAsync(endpoint, headers, body, HttpMethod.Post, logger).ConfigureAwait(false);
}
public async Task<HttpResponse> SendGetAsync(
Uri endpoint,
IDictionary<string, string> headers,
ICoreLogger logger)
{
return await ExecuteWithRetryAsync(endpoint, headers, null, HttpMethod.Get, logger).ConfigureAwait(false);
}
/// <summary>
/// Performs the POST request just like <see cref="SendPostAsync(Uri, IDictionary{string, string}, HttpContent, ICoreLogger)"/>
/// but does not throw a ServiceUnavailable service exception. Instead, it returns the <see cref="HttpResponse"/> associated
/// with the request.
/// </summary>
public async Task<HttpResponse> SendPostForceResponseAsync(
Uri uri,
Dictionary<string, string> headers,
StringContent body,
ICoreLogger logger)
{
return await ExecuteWithRetryAsync(uri, headers, body, HttpMethod.Post, logger, doNotThrow: true).ConfigureAwait(false);
}
private HttpRequestMessage CreateRequestMessage(Uri endpoint, IDictionary<string, string> headers)
{
HttpRequestMessage requestMessage = new HttpRequestMessage { RequestUri = endpoint };
requestMessage.Headers.Accept.Clear();
if (headers != null)
{
foreach (KeyValuePair<string, string> kvp in headers)
{
requestMessage.Headers.Add(kvp.Key, kvp.Value);
}
}
return requestMessage;
}
private async Task<HttpResponse> ExecuteWithRetryAsync(
Uri endpoint,
IDictionary<string, string> headers,
HttpContent body,
HttpMethod method,
ICoreLogger logger,
bool doNotThrow = false,
bool retry = true)
{
Exception timeoutException = null;
bool isRetryable = false;
bool is5xxError = false;
HttpResponse response = null;
try
{
HttpContent clonedBody = body;
if (body != null)
{
// Since HttpContent would be disposed by underlying client.SendAsync(),
// we duplicate it so that we will have a copy in case we would need to retry
clonedBody = await CloneHttpContentAsync(body).ConfigureAwait(false);
}
response = await ExecuteAsync(endpoint, headers, clonedBody, method).ConfigureAwait(false);
if (response.StatusCode == HttpStatusCode.OK)
{
return response;
}
logger.Info(string.Format(CultureInfo.InvariantCulture,
MsalErrorMessage.HttpRequestUnsuccessful,
(int)response.StatusCode, response.StatusCode));
is5xxError = (int)response.StatusCode >= 500 && (int)response.StatusCode < 600;
isRetryable = is5xxError && !HasRetryAfterHeader(response);
}
catch (TaskCanceledException exception)
{
logger.Error("The HTTP request failed or it was canceled. " + exception.Message);
isRetryable = true;
timeoutException = exception;
}
if (isRetryable && retry)
{
logger.Info("Retrying one more time..");
await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false);
return await ExecuteWithRetryAsync(
endpoint,
headers,
body,
method,
logger,
doNotThrow,
retry: false).ConfigureAwait(false);
}
logger.Warning("Request retry failed.");
if (timeoutException != null)
{
throw new MsalServiceException(
MsalError.RequestTimeout,
"Request to the endpoint timed out.",
timeoutException);
}
if (doNotThrow)
{
return response;
}
if (is5xxError)
{
throw MsalServiceExceptionFactory.FromHttpResponse(
MsalError.ServiceNotAvailable,
"Service is unavailable to process the request",
response);
}
return response;
}
private static bool HasRetryAfterHeader(HttpResponse response)
{
var retryAfter = response?.Headers?.RetryAfter;
return retryAfter != null &&
(retryAfter.Delta.HasValue || retryAfter.Date.HasValue);
}
private async Task<HttpResponse> ExecuteAsync(
Uri endpoint,
IDictionary<string, string> headers,
HttpContent body,
HttpMethod method)
{
HttpClient client = GetHttpClient();
using (HttpRequestMessage requestMessage = CreateRequestMessage(endpoint, headers))
{
requestMessage.Method = method;
requestMessage.Content = body;
using (HttpResponseMessage responseMessage =
await client.SendAsync(requestMessage).ConfigureAwait(false))
{
HttpResponse returnValue = await CreateResponseAsync(responseMessage).ConfigureAwait(false);
returnValue.UserAgent = requestMessage.Headers.UserAgent.ToString();
return returnValue;
}
}
}
internal /* internal for test only */ static async Task<HttpResponse> CreateResponseAsync(HttpResponseMessage response)
{
var body = response.Content == null
? null
: await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return new HttpResponse
{
Headers = response.Headers,
Body = body,
StatusCode = response.StatusCode
};
}
private async Task<HttpContent> CloneHttpContentAsync(HttpContent httpContent)
{
var temp = new MemoryStream();
await httpContent.CopyToAsync(temp).ConfigureAwait(false);
temp.Position = 0;
var clone = new StreamContent(temp);
if (httpContent.Headers != null)
{
foreach (var h in httpContent.Headers)
{
clone.Headers.Add(h.Key, h.Value);
}
}
#if WINDOWS_APP
// WORKAROUND
// On UWP there is a bug in the HTTP stack that causes an exception to be thrown when moving around a stream.
// https://stackoverflow.com/questions/31774058/postasync-throwing-irandomaccessstream-error-when-targeting-windows-10-uwp
// LoadIntoBufferAsync is necessary to buffer content for multiple reads - see https://stackoverflow.com/questions/26942514/multiple-calls-to-httpcontent-readasasync
// Documentation is sparse, but it looks like loading the buffer into memory avoids the bug, without
// replacing the System.Net.HttpClient with Windows.Web.Http.HttpClient, which is not exactly a drop in replacement
await clone.LoadIntoBufferAsync().ConfigureAwait(false);
#endif
return clone;
}
}
}
| 38.630952 | 177 | 0.583873 | [
"MIT"
] | jspuij/microsoft-authentication-library-for-dotnet | src/client/Microsoft.Identity.Client/Http/HttpManager.cs | 9,737 | C# |
using com.hideakin.textsearch.net;
using System;
using System.Net;
namespace com.hideakin.textsearch.exception
{
public class UnrecognizedResponseException : Exception
{
public HttpStatusCode StatusCode { get; }
public string ResponseBody { get; }
public string StandardReasonPhrase => HttpReasonPhrase.Get(StatusCode);
public UnrecognizedResponseException(HttpStatusCode statusCode, string responseBody, string message)
: base(message)
{
StatusCode = statusCode;
ResponseBody = responseBody;
}
}
}
| 27.043478 | 109 | 0.655949 | [
"MIT"
] | hnrt/TextSearch | TextSearchNet/exception/UnrecognizedResponseException.cs | 624 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// O código foi gerado por uma ferramenta.
// Versão de Tempo de Execução:4.0.30319.42000
//
// As alterações ao arquivo poderão causar comportamento incorreto e serão perdidas se
// o código for gerado novamente.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Tuplas")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("Tuplas")]
[assembly: System.Reflection.AssemblyTitleAttribute("Tuplas")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Gerado pela classe WriteCodeFragment do MSBuild.
| 41.916667 | 90 | 0.653082 | [
"MIT"
] | luiscelestino/CSharpMyExamples | Tuplas/obj/Release/netcoreapp2.1/Tuplas.AssemblyInfo.cs | 1,015 | C# |
// ----------------------------------------------------------------------------------------
// COPYRIGHT NOTICE
// ----------------------------------------------------------------------------------------
//
// The Source Code Store LLC
// ACTIVEGANTT SCHEDULER COMPONENT FOR C# - ActiveGanttCSW
// WPF Control
// Copyright (c) 2002-2017 The Source Code Store LLC
//
// All Rights Reserved. No parts of this file may be reproduced, modified or transmitted
// in any form or by any means without the written permission of the author.
//
// ----------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
namespace AGCSW
{
public class ControlTemplateGradient
{
public Color ControlBorderColor = Color.FromArgb(255, 100, 145, 204);
public Color HeadingBorderColor = Color.FromArgb(255, 197, 206, 216);
public Color HeadingForeColor = Color.FromArgb(255, 0, 0, 0);
public Color RowForeColor = Color.FromArgb(255, 0, 0, 0);
public GRE_GRADIENTFILLMODE GradientFillMode = GRE_GRADIENTFILLMODE.GDT_VERTICAL;
public Color StartGradientColor = Color.FromArgb(255, 179, 206, 235);
public Color EndGradientColor = Color.FromArgb(255, 161, 193, 232);
public Color TreeviewColor = Color.FromArgb(255, 100, 145, 204);
public Color RowBorderColor = Color.FromArgb(255, 192, 192, 192);
}
} | 44.941176 | 92 | 0.573953 | [
"MIT"
] | jluzardo1971/ActiveGanttCSW | AGCSW/ControlTemplateGradient.cs | 1,530 | C# |
#region License
// Copyright (c) 2009, ClearCanvas Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of ClearCanvas Inc. nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
// OF SUCH DAMAGE.
#endregion
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: ClearCanvas.Common.Plugin()]
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Broker")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Broker")]
[assembly: AssemblyCopyright("Copyright (c) 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("39ac841c-9e46-4c81-832b-c21bb43652f6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 44.128571 | 87 | 0.733247 | [
"Apache-2.0"
] | econmed/ImageServer20 | Enterprise/Hibernate/Properties/AssemblyInfo.cs | 3,091 | C# |
namespace Senparc.Weixin.WxOpen.AdvancedAPIs.Express
{
/// <summary>
///
/// </summary>
public class RealMockUpdateOrderModel
{
/// <summary>
/// 商家id, 由配送公司分配的appkey
/// </summary>
public string shopid { get; set; }
/// <summary>
/// 唯一标识订单的 ID,由商户生成, 不超过128字节
/// </summary>
public string shop_order_id { get; set; }
/// <summary>
/// 状态变更时间点,Unix秒级时间戳
/// </summary>
public long action_time { get; set; }
/// <summary>
/// 配送状态,枚举值
/// </summary>
public int order_status { get; set; }
/// <summary>
/// 附加信息
/// 非必填
/// </summary>
public string action_msg { get; set; }
/// <summary>
/// 用配送公司提供的appSecret加密的校验串说明
/// </summary>
public string delivery_sign { get; set; }
}
}
| 25.828571 | 53 | 0.490044 | [
"Apache-2.0"
] | 554393109/WeiXinMPSDK | src/Senparc.Weixin.WxOpen/src/Senparc.Weixin.WxOpen/Senparc.Weixin.WxOpen/AdvancedAPIs/Express/ExpressJson/RealMockUpdateOrderModel.cs | 1,052 | C# |
using Exceptionless.Core.Extensions;
using Exceptionless.Core.Utility;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Exceptionless.Core.Configuration;
public class EmailOptions {
public bool EnableDailySummary { get; internal set; }
/// <summary>
/// All emails that do not match the AllowedOutboundAddresses will be sent to this address in QA mode
/// </summary>
public string TestEmailAddress { get; internal set; }
/// <summary>
/// Email addresses that match this comma delimited list of domains and email addresses will be allowed to be sent out in QA mode
/// </summary>
public List<string> AllowedOutboundAddresses { get; internal set; }
public string SmtpFrom { get; internal set; }
public string SmtpHost { get; internal set; }
public int SmtpPort { get; internal set; }
[JsonConverter(typeof(StringEnumConverter))]
public SmtpEncryption SmtpEncryption { get; internal set; }
public string SmtpUser { get; internal set; }
public string SmtpPassword { get; internal set; }
public static EmailOptions ReadFromConfiguration(IConfiguration config, AppOptions appOptions) {
var options = new EmailOptions();
options.EnableDailySummary = config.GetValue(nameof(options.EnableDailySummary), appOptions.AppMode == AppMode.Production);
options.AllowedOutboundAddresses = config.GetValueList(nameof(options.AllowedOutboundAddresses)).Select(v => v.ToLowerInvariant()).ToList();
options.TestEmailAddress = config.GetValue(nameof(options.TestEmailAddress), appOptions.AppMode == AppMode.Development ? "test@localhost" : "");
string emailConnectionString = config.GetConnectionString("Email");
if (!String.IsNullOrEmpty(emailConnectionString)) {
var uri = new SmtpUri(emailConnectionString);
options.SmtpHost = uri.Host;
options.SmtpPort = uri.Port;
options.SmtpUser = uri.User;
options.SmtpPassword = uri.Password;
}
options.SmtpFrom = config.GetValue(nameof(options.SmtpFrom), appOptions.AppMode == AppMode.Development ? "Exceptionless <noreply@localhost>" : "");
options.SmtpEncryption = config.GetValue(nameof(options.SmtpEncryption), GetDefaultSmtpEncryption(options.SmtpPort));
if (String.IsNullOrWhiteSpace(options.SmtpUser) != String.IsNullOrWhiteSpace(options.SmtpPassword))
throw new ArgumentException("Must specify both the SmtpUser and the SmtpPassword, or neither.");
return options;
}
private static SmtpEncryption GetDefaultSmtpEncryption(int port) {
return port switch {
465 => SmtpEncryption.SSL,
587 => SmtpEncryption.StartTLS,
2525 => SmtpEncryption.StartTLS,
_ => SmtpEncryption.None
};
}
}
public enum SmtpEncryption {
None,
StartTLS,
SSL
}
| 39.413333 | 155 | 0.705007 | [
"Apache-2.0"
] | JohnZhaoXiaoHu/Exceptionless | src/Exceptionless.Core/Configuration/EmailOptions.cs | 2,958 | C# |
using System.Collections.Generic;
namespace Gsemac.Collections {
public interface INameValueCollection :
IDictionary<string, string> {
IEnumerable<string> GetValues(string key);
}
} | 17.583333 | 50 | 0.701422 | [
"MIT"
] | gsemac/Gsemac.Common | src/Gsemac.Collections/INameValueCollection.cs | 213 | C# |
using System;
using System.Globalization;
namespace Orckestra.Composer.Cart.Parameters
{
public class UpdateBillingAddressPostalCodeParam
{
public string BaseUrl { get; set; }
public string Scope { get; set; }
public CultureInfo CultureInfo { get; set; }
public Guid CustomerId { get; set; }
public string CartName { get; set; }
public string PostalCode { get; set; }
public string CountryCode { get; set; }
}
}
| 21.217391 | 52 | 0.639344 | [
"MIT"
] | InnaBoitsun/BetterRetailGroceryTest | src/Orckestra.Composer.Cart/Parameters/UpdateBillingAddressPostalCodeParam.cs | 490 | C# |
using Godot;
using System;
public class MainMenu : VBoxContainer
{
public override void _Ready()
{
}
public void MainScene()
{
GetTree().ChangeScene("res://Scenes/MainMenu.tscn");
}
public void Play()
{
GetTree().ChangeScene("res://Scenes/Game.tscn");
}
public void Exit()
{
GetTree().Quit();
}
}
| 14.692308 | 60 | 0.54712 | [
"MIT"
] | mimusangel/Ludunm-Dar-49 | Scripts/MainMenu.cs | 382 | C# |
namespace Dexter.Databases.FunTopics
{
/// <summary>
/// [risk of deprecation] The subtype a topic falls into. Can be of type TOPIC or WOULDYOURATHER.
/// </summary>
public enum TopicType
{
/// <summary>
/// A topic that initiates a random, unprompted conversation, generally by asking an open question.
/// </summary>
Topic,
/// <summary>
/// A topic that initiates a conversation by proposing two options and opening up a binary choice.
/// </summary>
WouldYouRather,
/// <summary>
/// A topic that states some fun, random, or unexpected fact about science, sociology, demography, or any other field of knowledge.
/// </summary>
FunFact,
/// <summary>
/// A topic that contains an introductory statement and a punchline inteded for comedy.
/// </summary>
Joke,
/// <summary>
/// A topic that contains a famous quote.
/// </summary>
Quote
}
}
| 20.568182 | 133 | 0.667403 | [
"MIT"
] | FeroxFoxxo/Dexter | Dexter/Databases/FunTopics/TopicType.cs | 907 | C# |
using Sharpen;
namespace gov.nist.javax.sip.stack
{
[Sharpen.NakedStub]
internal class IOHandler
{
}
}
| 10.8 | 34 | 0.731481 | [
"Apache-2.0"
] | Conceptengineai/XobotOS | android/naked-stubs/gov/nist/javax/sip/stack/IOHandler.cs | 108 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using OpenSim.Region.PhysicsModules.SharedBase;
using OpenMetaverse;
using Nini.Config;
namespace OpenSim.Region.PhysicsModule.BulletS
{
public static class BSParam
{
private static string LogHeader = "[BULLETSIM PARAMETERS]";
// Tuning notes:
// From: http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=6575
// Contact points can be added even if the distance is positive. The constraint solver can deal with
// contacts with positive distances as well as negative (penetration). Contact points are discarded
// if the distance exceeds a certain threshold.
// Bullet has a contact processing threshold and a contact breaking threshold.
// If the distance is larger than the contact breaking threshold, it will be removed after one frame.
// If the distance is larger than the contact processing threshold, the constraint solver will ignore it.
// This is separate/independent from the collision margin. The collision margin increases the object a bit
// to improve collision detection performance and accuracy.
// ===================
// From:
/// <summary>
/// Set whether physics is active or not.
/// </summary>
/// <remarks>
/// Can be enabled and disabled to start and stop physics.
/// </remarks>
public static bool Active { get; private set; }
public static bool UseSeparatePhysicsThread { get; private set; }
public static float PhysicsTimeStep { get; private set; }
// Level of Detail values kept as float because that's what the Meshmerizer wants
public static float MeshLOD { get; private set; }
public static float MeshCircularLOD { get; private set; }
public static float MeshMegaPrimLOD { get; private set; }
public static float MeshMegaPrimThreshold { get; private set; }
public static float SculptLOD { get; private set; }
public static int CrossingFailuresBeforeOutOfBounds { get; private set; }
public static float UpdateVelocityChangeThreshold { get; private set; }
public static float MinimumObjectMass { get; private set; }
public static float MaximumObjectMass { get; private set; }
public static float MaxLinearVelocity { get; private set; }
public static float MaxLinearVelocitySquared { get; private set; }
public static float MaxAngularVelocity { get; private set; }
public static float MaxAngularVelocitySquared { get; private set; }
public static float MaxAddForceMagnitude { get; private set; }
public static float MaxAddForceMagnitudeSquared { get; private set; }
public static float DensityScaleFactor { get; private set; }
public static float LinearDamping { get; private set; }
public static float AngularDamping { get; private set; }
public static float DeactivationTime { get; private set; }
public static float LinearSleepingThreshold { get; private set; }
public static float AngularSleepingThreshold { get; private set; }
public static float CcdMotionThreshold { get; private set; }
public static float CcdSweptSphereRadius { get; private set; }
public static float ContactProcessingThreshold { get; private set; }
public static bool ShouldMeshSculptedPrim { get; private set; } // cause scuplted prims to get meshed
public static bool ShouldForceSimplePrimMeshing { get; private set; } // if a cube or sphere, let Bullet do internal shapes
public static bool ShouldUseHullsForPhysicalObjects { get; private set; } // 'true' if should create hulls for physical objects
public static bool ShouldRemoveZeroWidthTriangles { get; private set; }
public static bool ShouldUseBulletHACD { get; set; }
public static bool ShouldUseSingleConvexHullForPrims { get; set; }
public static bool ShouldUseGImpactShapeForPrims { get; set; }
public static bool ShouldUseAssetHulls { get; set; }
public static float TerrainImplementation { get; set; }
public static int TerrainMeshMagnification { get; private set; }
public static float TerrainGroundPlane { get; private set; }
public static float TerrainFriction { get; private set; }
public static float TerrainHitFraction { get; private set; }
public static float TerrainRestitution { get; private set; }
public static float TerrainContactProcessingThreshold { get; private set; }
public static float TerrainCollisionMargin { get; private set; }
public static float DefaultFriction { get; private set; }
public static float DefaultDensity { get; private set; }
public static float DefaultRestitution { get; private set; }
public static float CollisionMargin { get; private set; }
public static float Gravity { get; private set; }
// Physics Engine operation
public static float MaxPersistantManifoldPoolSize { get; private set; }
public static float MaxCollisionAlgorithmPoolSize { get; private set; }
public static bool ShouldDisableContactPoolDynamicAllocation { get; private set; }
public static bool ShouldForceUpdateAllAabbs { get; private set; }
public static bool ShouldRandomizeSolverOrder { get; private set; }
public static bool ShouldSplitSimulationIslands { get; private set; }
public static bool ShouldEnableFrictionCaching { get; private set; }
public static float NumberOfSolverIterations { get; private set; }
public static bool UseSingleSidedMeshes { get; private set; }
public static float GlobalContactBreakingThreshold { get; private set; }
public static float PhysicsUnmanLoggingFrames { get; private set; }
// Avatar parameters
public static bool AvatarToAvatarCollisionsByDefault { get; private set; }
public static float AvatarFriction { get; private set; }
public static float AvatarStandingFriction { get; private set; }
public static float AvatarWalkVelocityFactor { get; private set; }
public static float AvatarAlwaysRunFactor { get; private set; }
public static float AvatarDensity { get; private set; }
public static float AvatarRestitution { get; private set; }
public static int AvatarShape { get; private set; }
public static float AvatarCapsuleWidth { get; private set; }
public static float AvatarCapsuleDepth { get; private set; }
public static float AvatarCapsuleHeight { get; private set; }
public static bool AvatarUseBefore09SizeComputation { get; private set; }
public static float AvatarHeightLowFudge { get; private set; }
public static float AvatarHeightMidFudge { get; private set; }
public static float AvatarHeightHighFudge { get; private set; }
public static float AvatarFlyingGroundMargin { get; private set; }
public static float AvatarFlyingGroundUpForce { get; private set; }
public static float AvatarTerminalVelocity { get; private set; }
public static float AvatarContactProcessingThreshold { get; private set; }
public static float AvatarAddForcePushFactor { get; private set; }
public static float AvatarStopZeroThreshold { get; private set; }
public static float AvatarStopZeroThresholdSquared { get; private set; }
public static int AvatarJumpFrames { get; private set; }
public static float AvatarBelowGroundUpCorrectionMeters { get; private set; }
public static float AvatarStepHeight { get; private set; }
public static float AvatarStepAngle { get; private set; }
public static float AvatarStepGroundFudge { get; private set; }
public static float AvatarStepApproachFactor { get; private set; }
public static float AvatarStepForceFactor { get; private set; }
public static float AvatarStepUpCorrectionFactor { get; private set; }
public static int AvatarStepSmoothingSteps { get; private set; }
// Vehicle parameters
public static float VehicleMaxLinearVelocity { get; private set; }
public static float VehicleMaxLinearVelocitySquared { get; private set; }
public static float VehicleMinLinearVelocity { get; private set; }
public static float VehicleMinLinearVelocitySquared { get; private set; }
public static float VehicleMaxAngularVelocity { get; private set; }
public static float VehicleMaxAngularVelocitySq { get; private set; }
public static float VehicleAngularDamping { get; private set; }
public static float VehicleFriction { get; private set; }
public static float VehicleRestitution { get; private set; }
public static Vector3 VehicleLinearFactor { get; private set; }
public static Vector3 VehicleAngularFactor { get; private set; }
public static Vector3 VehicleInertiaFactor { get; private set; }
public static float VehicleGroundGravityFudge { get; private set; }
public static float VehicleAngularBankingTimescaleFudge { get; private set; }
public static bool VehicleEnableLinearDeflection { get; private set; }
public static bool VehicleLinearDeflectionNotCollidingNoZ { get; private set; }
public static bool VehicleEnableAngularVerticalAttraction { get; private set; }
public static int VehicleAngularVerticalAttractionAlgorithm { get; private set; }
public static bool VehicleEnableAngularDeflection { get; private set; }
public static bool VehicleEnableAngularBanking { get; private set; }
// Convex Hulls
// Parameters for convex hull routine that ships with Bullet
public static int CSHullMaxDepthSplit { get; private set; }
public static int CSHullMaxDepthSplitForSimpleShapes { get; private set; }
public static float CSHullConcavityThresholdPercent { get; private set; }
public static float CSHullVolumeConservationThresholdPercent { get; private set; }
public static int CSHullMaxVertices { get; private set; }
public static float CSHullMaxSkinWidth { get; private set; }
public static float BHullMaxVerticesPerHull { get; private set; } // 100
public static float BHullMinClusters { get; private set; } // 2
public static float BHullCompacityWeight { get; private set; } // 0.1
public static float BHullVolumeWeight { get; private set; } // 0.0
public static float BHullConcavity { get; private set; } // 100
public static bool BHullAddExtraDistPoints { get; private set; } // false
public static bool BHullAddNeighboursDistPoints { get; private set; } // false
public static bool BHullAddFacesPoints { get; private set; } // false
public static bool BHullShouldAdjustCollisionMargin { get; private set; } // false
public static float WhichHACD { get; private set; } // zero if Bullet HACD, non-zero says VHACD
// Parameters for VHACD 2.0: http://code.google.com/p/v-hacd
// To enable, set both ShouldUseBulletHACD=true and WhichHACD=1
// http://kmamou.blogspot.ca/2014/12/v-hacd-20-parameters-description.html
public static float VHACDresolution { get; private set; } // 100,000 max number of voxels generated during voxelization stage
public static float VHACDdepth { get; private set; } // 20 max number of clipping stages
public static float VHACDconcavity { get; private set; } // 0.0025 maximum concavity
public static float VHACDplaneDownsampling { get; private set; } // 4 granularity of search for best clipping plane
public static float VHACDconvexHullDownsampling { get; private set; } // 4 precision of hull gen process
public static float VHACDalpha { get; private set; } // 0.05 bias toward clipping along symmetry planes
public static float VHACDbeta { get; private set; } // 0.05 bias toward clipping along revolution axis
public static float VHACDgamma { get; private set; } // 0.00125 max concavity when merging
public static float VHACDpca { get; private set; } // 0 on/off normalizing mesh before decomp
public static float VHACDmode { get; private set; } // 0 0:voxel based, 1: tetrahedron based
public static float VHACDmaxNumVerticesPerCH { get; private set; } // 64 max triangles per convex hull
public static float VHACDminVolumePerCH { get; private set; } // 0.0001 sampling of generated convex hulls
// Linkset implementation parameters
public static float LinksetImplementation { get; private set; }
public static bool LinksetOffsetCenterOfMass { get; private set; }
public static bool LinkConstraintUseFrameOffset { get; private set; }
public static bool LinkConstraintEnableTransMotor { get; private set; }
public static float LinkConstraintTransMotorMaxVel { get; private set; }
public static float LinkConstraintTransMotorMaxForce { get; private set; }
public static float LinkConstraintERP { get; private set; }
public static float LinkConstraintCFM { get; private set; }
public static float LinkConstraintSolverIterations { get; private set; }
public static bool UseBulletRaycast { get; private set; }
public static float PID_D { get; private set; } // derivative
public static float PID_P { get; private set; } // proportional
public static float DebugNumber { get; private set; } // A console setable number used for debugging
// Various constants that come from that other virtual world that shall not be named.
public const float MinGravityZ = -1f;
public const float MaxGravityZ = 28f;
public const float MinFriction = 0f;
public const float MaxFriction = 255f;
public const float MinDensity = 0.01f;
public const float MaxDensity = 22587f;
public const float MinRestitution = 0f;
public const float MaxRestitution = 1f;
// =====================================================================================
// =====================================================================================
// Base parameter definition that gets and sets parameter values via a string
public abstract class ParameterDefnBase
{
public string name; // string name of the parameter
public string desc; // a short description of what the parameter means
public ParameterDefnBase(string pName, string pDesc)
{
name = pName;
desc = pDesc;
}
// Set the parameter value to the default
public abstract void AssignDefault(BSScene s);
// Get the value as a string
public abstract string GetValue(BSScene s);
// Set the value to this string value
public abstract void SetValue(BSScene s, string valAsString);
// set the value on a particular object (usually sets in physics engine)
public abstract void SetOnObject(BSScene s, BSPhysObject obj);
public abstract bool HasSetOnObject { get; }
}
// Specific parameter definition for a parameter of a specific type.
public delegate T PGetValue<T>(BSScene s);
public delegate void PSetValue<T>(BSScene s, T val);
public delegate void PSetOnObject<T>(BSScene scene, BSPhysObject obj);
public sealed class ParameterDefn<T> : ParameterDefnBase
{
private T defaultValue;
private PSetValue<T> setter;
private PGetValue<T> getter;
private PSetOnObject<T> objectSet;
public ParameterDefn(string pName, string pDesc, T pDefault, PGetValue<T> pGetter, PSetValue<T> pSetter)
: base(pName, pDesc)
{
defaultValue = pDefault;
setter = pSetter;
getter = pGetter;
objectSet = null;
}
public ParameterDefn(string pName, string pDesc, T pDefault, PGetValue<T> pGetter, PSetValue<T> pSetter, PSetOnObject<T> pObjSetter)
: base(pName, pDesc)
{
defaultValue = pDefault;
setter = pSetter;
getter = pGetter;
objectSet = pObjSetter;
}
// Simple parameter variable where property name is the same as the INI file name
// and the value is only a simple get and set.
public ParameterDefn(string pName, string pDesc, T pDefault)
: base(pName, pDesc)
{
defaultValue = pDefault;
setter = (s, v) => { SetValueByName(s, name, v); };
getter = (s) => { return GetValueByName(s, name); };
objectSet = null;
}
// Use reflection to find the property named 'pName' in BSParam and assign 'val' to same.
private void SetValueByName(BSScene s, string pName, T val)
{
PropertyInfo prop = typeof(BSParam).GetProperty(pName, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
if (prop == null)
{
// This should only be output when someone adds a new INI parameter and misspells the name.
s.Logger.ErrorFormat("{0} SetValueByName: did not find '{1}'. Verify specified property name is the same as the given INI parameters name.", LogHeader, pName);
}
else
{
prop.SetValue(null, val, null);
}
}
// Use reflection to find the property named 'pName' in BSParam and return the value in same.
private T GetValueByName(BSScene s, string pName)
{
PropertyInfo prop = typeof(BSParam).GetProperty(pName, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
if (prop == null)
{
// This should only be output when someone adds a new INI parameter and misspells the name.
s.Logger.ErrorFormat("{0} GetValueByName: did not find '{1}'. Verify specified property name is the same as the given INI parameter name.", LogHeader, pName);
}
return (T)prop.GetValue(null, null);
}
public override void AssignDefault(BSScene s)
{
setter(s, defaultValue);
}
public override string GetValue(BSScene s)
{
return getter(s).ToString();
}
public override void SetValue(BSScene s, string valAsString)
{
// Get the generic type of the setter
Type genericType = setter.GetType().GetGenericArguments()[0];
// Find the 'Parse' method on that type
System.Reflection.MethodInfo parser = null;
try
{
parser = genericType.GetMethod("Parse", new Type[] { typeof(String) } );
}
catch (Exception e)
{
s.Logger.ErrorFormat("{0} Exception getting parser for type '{1}': {2}", LogHeader, genericType, e);
parser = null;
}
if (parser != null)
{
// Parse the input string
try
{
T setValue = (T)parser.Invoke(genericType, new Object[] { valAsString });
// Store the parsed value
setter(s, setValue);
// s.Logger.DebugFormat("{0} Parameter {1} = {2}", LogHeader, name, setValue);
}
catch
{
s.Logger.ErrorFormat("{0} Failed parsing parameter value '{1}' as type '{2}'", LogHeader, valAsString, genericType);
}
}
else
{
s.Logger.ErrorFormat("{0} Could not find parameter parser for type '{1}'", LogHeader, genericType);
}
}
public override bool HasSetOnObject
{
get { return objectSet != null; }
}
public override void SetOnObject(BSScene s, BSPhysObject obj)
{
if (objectSet != null)
objectSet(s, obj);
}
}
// List of all of the externally visible parameters.
// For each parameter, this table maps a text name to getter and setters.
// To add a new externally referencable/settable parameter, add the paramter storage
// location somewhere in the program and make an entry in this table with the
// getters and setters.
// It is easiest to find an existing definition and copy it.
//
// A ParameterDefn<T>() takes the following parameters:
// -- the text name of the parameter. This is used for console input and ini file.
// -- a short text description of the parameter. This shows up in the console listing.
// -- a default value
// -- a delegate for getting the value
// -- a delegate for setting the value
// -- an optional delegate to update the value in the world. Most often used to
// push the new value to an in-world object.
//
// The single letter parameters for the delegates are:
// s = BSScene
// o = BSPhysObject
// v = value (appropriate type)
private static ParameterDefnBase[] ParameterDefinitions =
{
new ParameterDefn<bool>("Active", "If 'true', false then physics is not active",
false ),
new ParameterDefn<bool>("UseSeparatePhysicsThread", "If 'true', the physics engine runs independent from the simulator heartbeat",
false ),
new ParameterDefn<float>("PhysicsTimeStep", "If separate thread, seconds to simulate each interval",
0.089f ),
new ParameterDefn<bool>("MeshSculptedPrim", "Whether to create meshes for sculpties",
true,
(s) => { return ShouldMeshSculptedPrim; },
(s,v) => { ShouldMeshSculptedPrim = v; } ),
new ParameterDefn<bool>("ForceSimplePrimMeshing", "If true, only use primitive meshes for objects",
false,
(s) => { return ShouldForceSimplePrimMeshing; },
(s,v) => { ShouldForceSimplePrimMeshing = v; } ),
new ParameterDefn<bool>("UseHullsForPhysicalObjects", "If true, create hulls for physical objects",
true,
(s) => { return ShouldUseHullsForPhysicalObjects; },
(s,v) => { ShouldUseHullsForPhysicalObjects = v; } ),
new ParameterDefn<bool>("ShouldRemoveZeroWidthTriangles", "If true, remove degenerate triangles from meshes",
true ),
new ParameterDefn<bool>("ShouldUseBulletHACD", "If true, use the Bullet version of HACD",
false ),
new ParameterDefn<bool>("ShouldUseSingleConvexHullForPrims", "If true, use a single convex hull shape for physical prims",
true ),
new ParameterDefn<bool>("ShouldUseGImpactShapeForPrims", "If true, use a GImpact shape for prims with cuts and twists",
false ),
new ParameterDefn<bool>("ShouldUseAssetHulls", "If true, use hull if specified in the mesh asset info",
true ),
new ParameterDefn<int>("CrossingFailuresBeforeOutOfBounds", "How forgiving we are about getting into adjactent regions",
5 ),
new ParameterDefn<float>("UpdateVelocityChangeThreshold", "Change in updated velocity required before reporting change to simulator",
0.1f ),
new ParameterDefn<float>("MeshLevelOfDetail", "Level of detail to render meshes (32, 16, 8 or 4. 32=most detailed)",
32f,
(s) => { return MeshLOD; },
(s,v) => { MeshLOD = v; } ),
new ParameterDefn<float>("MeshLevelOfDetailCircular", "Level of detail for prims with circular cuts or shapes",
32f,
(s) => { return MeshCircularLOD; },
(s,v) => { MeshCircularLOD = v; } ),
new ParameterDefn<float>("MeshLevelOfDetailMegaPrimThreshold", "Size (in meters) of a mesh before using MeshMegaPrimLOD",
10f,
(s) => { return MeshMegaPrimThreshold; },
(s,v) => { MeshMegaPrimThreshold = v; } ),
new ParameterDefn<float>("MeshLevelOfDetailMegaPrim", "Level of detail to render meshes larger than threshold meters",
32f,
(s) => { return MeshMegaPrimLOD; },
(s,v) => { MeshMegaPrimLOD = v; } ),
new ParameterDefn<float>("SculptLevelOfDetail", "Level of detail to render sculpties (32, 16, 8 or 4. 32=most detailed)",
32f,
(s) => { return SculptLOD; },
(s,v) => { SculptLOD = v; } ),
new ParameterDefn<int>("MaxSubStep", "In simulation step, maximum number of substeps",
10,
(s) => { return s.m_maxSubSteps; },
(s,v) => { s.m_maxSubSteps = (int)v; } ),
new ParameterDefn<float>("FixedTimeStep", "In simulation step, seconds of one substep (1/60)",
1f / 60f,
(s) => { return s.m_fixedTimeStep; },
(s,v) => { s.m_fixedTimeStep = v; } ),
new ParameterDefn<float>("NominalFrameRate", "The base frame rate we claim",
55f,
(s) => { return s.NominalFrameRate; },
(s,v) => { s.NominalFrameRate = (int)v; } ),
new ParameterDefn<int>("MaxCollisionsPerFrame", "Max collisions returned at end of each frame",
2048,
(s) => { return s.m_maxCollisionsPerFrame; },
(s,v) => { s.m_maxCollisionsPerFrame = (int)v; } ),
new ParameterDefn<int>("MaxUpdatesPerFrame", "Max updates returned at end of each frame",
8000,
(s) => { return s.m_maxUpdatesPerFrame; },
(s,v) => { s.m_maxUpdatesPerFrame = (int)v; } ),
new ParameterDefn<float>("MinObjectMass", "Minimum object mass (0.0001)",
0.0001f,
(s) => { return MinimumObjectMass; },
(s,v) => { MinimumObjectMass = v; } ),
new ParameterDefn<float>("MaxObjectMass", "Maximum object mass (10000.01)",
10000.01f,
(s) => { return MaximumObjectMass; },
(s,v) => { MaximumObjectMass = v; } ),
new ParameterDefn<float>("MaxLinearVelocity", "Maximum velocity magnitude that can be assigned to an object",
1000.0f,
(s) => { return MaxLinearVelocity; },
(s,v) => { MaxLinearVelocity = v; MaxLinearVelocitySquared = v * v; } ),
new ParameterDefn<float>("MaxAngularVelocity", "Maximum rotational velocity magnitude that can be assigned to an object",
1000.0f,
(s) => { return MaxAngularVelocity; },
(s,v) => { MaxAngularVelocity = v; MaxAngularVelocitySquared = v * v; } ),
// LL documentation says thie number should be 20f for llApplyImpulse and 200f for llRezObject
new ParameterDefn<float>("MaxAddForceMagnitude", "Maximum force that can be applied by llApplyImpulse (SL says 20f)",
20000.0f,
(s) => { return MaxAddForceMagnitude; },
(s,v) => { MaxAddForceMagnitude = v; MaxAddForceMagnitudeSquared = v * v; } ),
// Density is passed around as 100kg/m3. This scales that to 1kg/m3.
// Reduce by power of 100 because Bullet doesn't seem to handle objects with large mass very well
new ParameterDefn<float>("DensityScaleFactor", "Conversion for simulator/viewer density (100kg/m3) to physical density (1kg/m3)",
0.01f ),
new ParameterDefn<float>("PID_D", "Derivitive factor for motion smoothing",
2200f ),
new ParameterDefn<float>("PID_P", "Parameteric factor for motion smoothing",
900f ),
new ParameterDefn<float>("DefaultFriction", "Friction factor used on new objects",
0.2f,
(s) => { return DefaultFriction; },
(s,v) => { DefaultFriction = v; s.UnmanagedParams[0].defaultFriction = v; } ),
// For historical reasons, the viewer and simulator multiply the density by 100
new ParameterDefn<float>("DefaultDensity", "Density for new objects" ,
1000.0006836f, // Aluminum g/cm3 * 100
(s) => { return DefaultDensity; },
(s,v) => { DefaultDensity = v; s.UnmanagedParams[0].defaultDensity = v; } ),
new ParameterDefn<float>("DefaultRestitution", "Bouncyness of an object" ,
0f,
(s) => { return DefaultRestitution; },
(s,v) => { DefaultRestitution = v; s.UnmanagedParams[0].defaultRestitution = v; } ),
new ParameterDefn<float>("CollisionMargin", "Margin around objects before collisions are calculated (must be zero!)",
0.04f,
(s) => { return CollisionMargin; },
(s,v) => { CollisionMargin = v; s.UnmanagedParams[0].collisionMargin = v; } ),
new ParameterDefn<float>("Gravity", "Vertical force of gravity (negative means down)",
-9.80665f,
(s) => { return Gravity; },
(s,v) => { Gravity = v; s.UnmanagedParams[0].gravity = v; },
(s,o) => { s.PE.SetGravity(o.PhysBody, new Vector3(0f,0f,Gravity)); } ),
new ParameterDefn<float>("LinearDamping", "Factor to damp linear movement per second (0.0 - 1.0)",
0f,
(s) => { return LinearDamping; },
(s,v) => { LinearDamping = v; },
(s,o) => { s.PE.SetDamping(o.PhysBody, LinearDamping, AngularDamping); } ),
new ParameterDefn<float>("AngularDamping", "Factor to damp angular movement per second (0.0 - 1.0)",
0f,
(s) => { return AngularDamping; },
(s,v) => { AngularDamping = v; },
(s,o) => { s.PE.SetDamping(o.PhysBody, LinearDamping, AngularDamping); } ),
new ParameterDefn<float>("DeactivationTime", "Seconds before considering an object potentially static",
0.2f,
(s) => { return DeactivationTime; },
(s,v) => { DeactivationTime = v; },
(s,o) => { s.PE.SetDeactivationTime(o.PhysBody, DeactivationTime); } ),
new ParameterDefn<float>("LinearSleepingThreshold", "Seconds to measure linear movement before considering static",
0.8f,
(s) => { return LinearSleepingThreshold; },
(s,v) => { LinearSleepingThreshold = v;},
(s,o) => { s.PE.SetSleepingThresholds(o.PhysBody, LinearSleepingThreshold, AngularSleepingThreshold); } ),
new ParameterDefn<float>("AngularSleepingThreshold", "Seconds to measure angular movement before considering static",
1.0f,
(s) => { return AngularSleepingThreshold; },
(s,v) => { AngularSleepingThreshold = v;},
(s,o) => { s.PE.SetSleepingThresholds(o.PhysBody, LinearSleepingThreshold, AngularSleepingThreshold); } ),
new ParameterDefn<float>("CcdMotionThreshold", "Continuious collision detection threshold (0 means no CCD)" ,
0.0f, // set to zero to disable
(s) => { return CcdMotionThreshold; },
(s,v) => { CcdMotionThreshold = v;},
(s,o) => { s.PE.SetCcdMotionThreshold(o.PhysBody, CcdMotionThreshold); } ),
new ParameterDefn<float>("CcdSweptSphereRadius", "Continuious collision detection test radius" ,
0.2f,
(s) => { return CcdSweptSphereRadius; },
(s,v) => { CcdSweptSphereRadius = v;},
(s,o) => { s.PE.SetCcdSweptSphereRadius(o.PhysBody, CcdSweptSphereRadius); } ),
new ParameterDefn<float>("ContactProcessingThreshold", "Distance above which contacts can be discarded (0 means no discard)" ,
0.0f,
(s) => { return ContactProcessingThreshold; },
(s,v) => { ContactProcessingThreshold = v;},
(s,o) => { s.PE.SetContactProcessingThreshold(o.PhysBody, ContactProcessingThreshold); } ),
new ParameterDefn<float>("TerrainImplementation", "Type of shape to use for terrain (0=heightmap, 1=mesh)",
(float)BSTerrainPhys.TerrainImplementation.Heightmap ),
new ParameterDefn<int>("TerrainMeshMagnification", "Number of times the 256x256 heightmap is multiplied to create the terrain mesh" ,
2 ),
new ParameterDefn<float>("TerrainGroundPlane", "Altitude of ground plane used to keep things from falling to infinity" ,
-500.0f ),
new ParameterDefn<float>("TerrainFriction", "Factor to reduce movement against terrain surface" ,
0.3f ),
new ParameterDefn<float>("TerrainHitFraction", "Distance to measure hit collisions" ,
0.8f ),
new ParameterDefn<float>("TerrainRestitution", "Bouncyness" ,
0f ),
new ParameterDefn<float>("TerrainContactProcessingThreshold", "Distance from terrain to stop processing collisions" ,
0.0f ),
new ParameterDefn<float>("TerrainCollisionMargin", "Margin where collision checking starts" ,
0.04f ),
new ParameterDefn<bool>("AvatarToAvatarCollisionsByDefault", "Should avatars collide with other avatars by default?",
true),
new ParameterDefn<float>("AvatarFriction", "Factor to reduce movement against an avatar. Changed on avatar recreation.",
0.2f ),
new ParameterDefn<float>("AvatarStandingFriction", "Avatar friction when standing. Changed on avatar recreation.",
0.95f ),
new ParameterDefn<float>("AvatarWalkVelocityFactor", "Speed multiplier if avatar is walking",
1.0f ),
new ParameterDefn<float>("AvatarAlwaysRunFactor", "Speed multiplier if avatar is set to always run",
1.3f ),
// For historical reasons, density is reported * 100
new ParameterDefn<float>("AvatarDensity", "Density of an avatar. Changed on avatar recreation. Scaled times 100.",
350f) , // 3.5 * 100
new ParameterDefn<float>("AvatarRestitution", "Bouncyness. Changed on avatar recreation.",
0f ),
new ParameterDefn<int>("AvatarShape", "Code for avatar physical shape: 0:capsule, 1:cube, 2:ovoid, 2:mesh",
BSShapeCollection.AvatarShapeCube ) ,
new ParameterDefn<float>("AvatarCapsuleWidth", "The distance between the sides of the avatar capsule",
0.6f ) ,
new ParameterDefn<float>("AvatarCapsuleDepth", "The distance between the front and back of the avatar capsule",
0.45f ),
new ParameterDefn<float>("AvatarCapsuleHeight", "Default height of space around avatar",
1.5f ),
new ParameterDefn<bool>("AvatarUseBefore09SizeComputation", "Use the old fudge method of computing avatar capsule size",
true ),
new ParameterDefn<float>("AvatarHeightLowFudge", "A fudge factor to make small avatars stand on the ground",
0f ),
new ParameterDefn<float>("AvatarHeightMidFudge", "A fudge distance to adjust average sized avatars to be standing on ground",
0f ),
new ParameterDefn<float>("AvatarHeightHighFudge", "A fudge factor to make tall avatars stand on the ground",
0f ),
new ParameterDefn<float>("AvatarFlyingGroundMargin", "Meters avatar is kept above the ground when flying",
5f ),
new ParameterDefn<float>("AvatarFlyingGroundUpForce", "Upward force applied to the avatar to keep it at flying ground margin",
2.0f ),
new ParameterDefn<float>("AvatarTerminalVelocity", "Terminal Velocity of falling avatar",
-54.0f ),
new ParameterDefn<float>("AvatarContactProcessingThreshold", "Distance from capsule to check for collisions",
0.1f ),
new ParameterDefn<float>("AvatarAddForcePushFactor", "BSCharacter.AddForce is multiplied by this and mass to be like other physics engines",
0.315f ),
new ParameterDefn<float>("AvatarStopZeroThreshold", "Movement velocity below which avatar is assumed to be stopped",
0.45f,
(s) => { return (float)AvatarStopZeroThreshold; },
(s,v) => { AvatarStopZeroThreshold = v; AvatarStopZeroThresholdSquared = v * v; } ),
new ParameterDefn<float>("AvatarBelowGroundUpCorrectionMeters", "Meters to move avatar up if it seems to be below ground",
1.0f ),
new ParameterDefn<int>("AvatarJumpFrames", "Number of frames to allow jump forces. Changes jump height.",
4 ),
new ParameterDefn<float>("AvatarStepHeight", "Height of a step obstacle to consider step correction",
0.999f ) ,
new ParameterDefn<float>("AvatarStepAngle", "The angle (in radians) for a vertical surface to be considered a step",
0.3f ) ,
new ParameterDefn<float>("AvatarStepGroundFudge", "Fudge factor subtracted from avatar base when comparing collision height",
0.1f ) ,
new ParameterDefn<float>("AvatarStepApproachFactor", "Factor to control angle of approach to step (0=straight on)",
2f ),
new ParameterDefn<float>("AvatarStepForceFactor", "Controls the amount of force up applied to step up onto a step",
0f ),
new ParameterDefn<float>("AvatarStepUpCorrectionFactor", "Multiplied by height of step collision to create up movement at step",
0.8f ),
new ParameterDefn<int>("AvatarStepSmoothingSteps", "Number of frames after a step collision that we continue walking up stairs",
1 ),
new ParameterDefn<float>("VehicleMaxLinearVelocity", "Maximum velocity magnitude that can be assigned to a vehicle",
1000.0f,
(s) => { return (float)VehicleMaxLinearVelocity; },
(s,v) => { VehicleMaxLinearVelocity = v; VehicleMaxLinearVelocitySquared = v * v; } ),
new ParameterDefn<float>("VehicleMinLinearVelocity", "Maximum velocity magnitude that can be assigned to a vehicle",
0.001f,
(s) => { return (float)VehicleMinLinearVelocity; },
(s,v) => { VehicleMinLinearVelocity = v; VehicleMinLinearVelocitySquared = v * v; } ),
new ParameterDefn<float>("VehicleMaxAngularVelocity", "Maximum rotational velocity magnitude that can be assigned to a vehicle",
12.0f,
(s) => { return (float)VehicleMaxAngularVelocity; },
(s,v) => { VehicleMaxAngularVelocity = v; VehicleMaxAngularVelocitySq = v * v; } ),
new ParameterDefn<float>("VehicleAngularDamping", "Factor to damp vehicle angular movement per second (0.0 - 1.0)",
0.0f ),
new ParameterDefn<Vector3>("VehicleLinearFactor", "Fraction of physical linear changes applied to vehicle (<0,0,0> to <1,1,1>)",
new Vector3(1f, 1f, 1f) ),
new ParameterDefn<Vector3>("VehicleAngularFactor", "Fraction of physical angular changes applied to vehicle (<0,0,0> to <1,1,1>)",
new Vector3(1f, 1f, 1f) ),
new ParameterDefn<Vector3>("VehicleInertiaFactor", "Fraction of physical inertia applied (<0,0,0> to <1,1,1>)",
new Vector3(1f, 1f, 1f) ),
new ParameterDefn<float>("VehicleFriction", "Friction of vehicle on the ground (0.0 - 1.0)",
0.0f ),
new ParameterDefn<float>("VehicleRestitution", "Bouncyness factor for vehicles (0.0 - 1.0)",
0.0f ),
new ParameterDefn<float>("VehicleGroundGravityFudge", "Factor to multiply gravity if a ground vehicle is probably on the ground (0.0 - 1.0)",
0.2f ),
new ParameterDefn<float>("VehicleAngularBankingTimescaleFudge", "Factor to multiple angular banking timescale. Tune to increase realism.",
60.0f ),
new ParameterDefn<bool>("VehicleEnableLinearDeflection", "Turn on/off vehicle linear deflection effect",
true ),
new ParameterDefn<bool>("VehicleLinearDeflectionNotCollidingNoZ", "Turn on/off linear deflection Z effect on non-colliding vehicles",
true ),
new ParameterDefn<bool>("VehicleEnableAngularVerticalAttraction", "Turn on/off vehicle angular vertical attraction effect",
true ),
new ParameterDefn<int>("VehicleAngularVerticalAttractionAlgorithm", "Select vertical attraction algo. You need to look at the source.",
0 ),
new ParameterDefn<bool>("VehicleEnableAngularDeflection", "Turn on/off vehicle angular deflection effect",
true ),
new ParameterDefn<bool>("VehicleEnableAngularBanking", "Turn on/off vehicle angular banking effect",
true ),
new ParameterDefn<float>("MaxPersistantManifoldPoolSize", "Number of manifolds pooled (0 means default of 4096)",
0f,
(s) => { return MaxPersistantManifoldPoolSize; },
(s,v) => { MaxPersistantManifoldPoolSize = v; s.UnmanagedParams[0].maxPersistantManifoldPoolSize = v; } ),
new ParameterDefn<float>("MaxCollisionAlgorithmPoolSize", "Number of collisions pooled (0 means default of 4096)",
0f,
(s) => { return MaxCollisionAlgorithmPoolSize; },
(s,v) => { MaxCollisionAlgorithmPoolSize = v; s.UnmanagedParams[0].maxCollisionAlgorithmPoolSize = v; } ),
new ParameterDefn<bool>("ShouldDisableContactPoolDynamicAllocation", "Enable to allow large changes in object count",
false,
(s) => { return ShouldDisableContactPoolDynamicAllocation; },
(s,v) => { ShouldDisableContactPoolDynamicAllocation = v;
s.UnmanagedParams[0].shouldDisableContactPoolDynamicAllocation = NumericBool(v); } ),
new ParameterDefn<bool>("ShouldForceUpdateAllAabbs", "Enable to recomputer AABBs every simulator step",
false,
(s) => { return ShouldForceUpdateAllAabbs; },
(s,v) => { ShouldForceUpdateAllAabbs = v; s.UnmanagedParams[0].shouldForceUpdateAllAabbs = NumericBool(v); } ),
new ParameterDefn<bool>("ShouldRandomizeSolverOrder", "Enable for slightly better stacking interaction",
true,
(s) => { return ShouldRandomizeSolverOrder; },
(s,v) => { ShouldRandomizeSolverOrder = v; s.UnmanagedParams[0].shouldRandomizeSolverOrder = NumericBool(v); } ),
new ParameterDefn<bool>("ShouldSplitSimulationIslands", "Enable splitting active object scanning islands",
true,
(s) => { return ShouldSplitSimulationIslands; },
(s,v) => { ShouldSplitSimulationIslands = v; s.UnmanagedParams[0].shouldSplitSimulationIslands = NumericBool(v); } ),
new ParameterDefn<bool>("ShouldEnableFrictionCaching", "Enable friction computation caching",
true,
(s) => { return ShouldEnableFrictionCaching; },
(s,v) => { ShouldEnableFrictionCaching = v; s.UnmanagedParams[0].shouldEnableFrictionCaching = NumericBool(v); } ),
new ParameterDefn<float>("NumberOfSolverIterations", "Number of internal iterations (0 means default)",
0f, // zero says use Bullet default
(s) => { return NumberOfSolverIterations; },
(s,v) => { NumberOfSolverIterations = v; s.UnmanagedParams[0].numberOfSolverIterations = v; } ),
new ParameterDefn<bool>("UseSingleSidedMeshes", "Whether to compute collisions based on single sided meshes.",
true,
(s) => { return UseSingleSidedMeshes; },
(s,v) => { UseSingleSidedMeshes = v; s.UnmanagedParams[0].useSingleSidedMeshes = NumericBool(v); } ),
new ParameterDefn<float>("GlobalContactBreakingThreshold", "Amount of shape radius before breaking a collision contact (0 says Bullet default (0.2))",
0f,
(s) => { return GlobalContactBreakingThreshold; },
(s,v) => { GlobalContactBreakingThreshold = v; s.UnmanagedParams[0].globalContactBreakingThreshold = v; } ),
new ParameterDefn<float>("PhysicsUnmanLoggingFrames", "If non-zero, frames between output of detailed unmanaged physics statistics",
0f,
(s) => { return PhysicsUnmanLoggingFrames; },
(s,v) => { PhysicsUnmanLoggingFrames = v; s.UnmanagedParams[0].physicsLoggingFrames = v; } ),
new ParameterDefn<int>("CSHullMaxDepthSplit", "CS impl: max depth to split for hull. 1-10 but > 7 is iffy",
7 ),
new ParameterDefn<int>("CSHullMaxDepthSplitForSimpleShapes", "CS impl: max depth setting for simple prim shapes",
2 ),
new ParameterDefn<float>("CSHullConcavityThresholdPercent", "CS impl: concavity threshold percent (0-20)",
5f ),
new ParameterDefn<float>("CSHullVolumeConservationThresholdPercent", "percent volume conservation to collapse hulls (0-30)",
5f ),
new ParameterDefn<int>("CSHullMaxVertices", "CS impl: maximum number of vertices in output hulls. Keep < 50.",
32 ),
new ParameterDefn<float>("CSHullMaxSkinWidth", "CS impl: skin width to apply to output hulls.",
0f ),
new ParameterDefn<float>("BHullMaxVerticesPerHull", "Bullet impl: max number of vertices per created hull",
200f ),
new ParameterDefn<float>("BHullMinClusters", "Bullet impl: minimum number of hulls to create per mesh",
10f ),
new ParameterDefn<float>("BHullCompacityWeight", "Bullet impl: weight factor for how compact to make hulls",
20f ),
new ParameterDefn<float>("BHullVolumeWeight", "Bullet impl: weight factor for volume in created hull",
0.1f ),
new ParameterDefn<float>("BHullConcavity", "Bullet impl: weight factor for how convex a created hull can be",
10f ),
new ParameterDefn<bool>("BHullAddExtraDistPoints", "Bullet impl: whether to add extra vertices for long distance vectors",
true ),
new ParameterDefn<bool>("BHullAddNeighboursDistPoints", "Bullet impl: whether to add extra vertices between neighbor hulls",
true ),
new ParameterDefn<bool>("BHullAddFacesPoints", "Bullet impl: whether to add extra vertices to break up hull faces",
true ),
new ParameterDefn<bool>("BHullShouldAdjustCollisionMargin", "Bullet impl: whether to shrink resulting hulls to account for collision margin",
false ),
new ParameterDefn<float>("WhichHACD", "zero if Bullet HACD, non-zero says VHACD",
0f ),
new ParameterDefn<float>("VHACDresolution", "max number of voxels generated during voxelization stage",
100000f ),
new ParameterDefn<float>("VHACDdepth", "max number of clipping stages",
20f ),
new ParameterDefn<float>("VHACDconcavity", "maximum concavity",
0.0025f ),
new ParameterDefn<float>("VHACDplaneDownsampling", "granularity of search for best clipping plane",
4f ),
new ParameterDefn<float>("VHACDconvexHullDownsampling", "precision of hull gen process",
4f ),
new ParameterDefn<float>("VHACDalpha", "bias toward clipping along symmetry planes",
0.05f ),
new ParameterDefn<float>("VHACDbeta", "bias toward clipping along revolution axis",
0.05f ),
new ParameterDefn<float>("VHACDgamma", "max concavity when merging",
0.00125f ),
new ParameterDefn<float>("VHACDpca", "on/off normalizing mesh before decomp",
0f ),
new ParameterDefn<float>("VHACDmode", "0:voxel based, 1: tetrahedron based",
0f ),
new ParameterDefn<float>("VHACDmaxNumVerticesPerCH", "max triangles per convex hull",
64f ),
new ParameterDefn<float>("VHACDminVolumePerCH", "sampling of generated convex hulls",
0.0001f ),
new ParameterDefn<float>("LinksetImplementation", "Type of linkset implementation (0=Constraint, 1=Compound, 2=Manual)",
(float)BSLinkset.LinksetImplementation.Compound ),
new ParameterDefn<bool>("LinksetOffsetCenterOfMass", "If 'true', compute linkset center-of-mass and offset linkset position to account for same",
true ),
new ParameterDefn<bool>("LinkConstraintUseFrameOffset", "For linksets built with constraints, enable frame offsetFor linksets built with constraints, enable frame offset.",
false ),
new ParameterDefn<bool>("LinkConstraintEnableTransMotor", "Whether to enable translational motor on linkset constraints",
true ),
new ParameterDefn<float>("LinkConstraintTransMotorMaxVel", "Maximum velocity to be applied by translational motor in linkset constraints",
5.0f ),
new ParameterDefn<float>("LinkConstraintTransMotorMaxForce", "Maximum force to be applied by translational motor in linkset constraints",
0.1f ),
new ParameterDefn<float>("LinkConstraintCFM", "Amount constraint can be violated. 0=no violation, 1=infinite. Default=0.1",
0.1f ),
new ParameterDefn<float>("LinkConstraintERP", "Amount constraint is corrected each tick. 0=none, 1=all. Default = 0.2",
0.1f ),
new ParameterDefn<float>("LinkConstraintSolverIterations", "Number of solver iterations when computing constraint. (0 = Bullet default)",
40 ),
new ParameterDefn<bool>("UseBulletRaycast", "If 'true', use the raycast function of the Bullet physics engine",
true ),
new ParameterDefn<float>("DebugNumber", "A console setable number sometimes used for debugging",
1.0f ),
new ParameterDefn<int>("PhysicsMetricFrames", "Frames between outputting detailed phys metrics. (0 is off)",
0,
(s) => { return s.PhysicsMetricDumpFrames; },
(s,v) => { s.PhysicsMetricDumpFrames = v; } ),
new ParameterDefn<float>("ResetBroadphasePool", "Setting this is any value resets the broadphase collision pool",
0f,
(s) => { return 0f; },
(s,v) => { BSParam.ResetBroadphasePoolTainted(s, v); } ),
new ParameterDefn<float>("ResetConstraintSolver", "Setting this is any value resets the constraint solver",
0f,
(s) => { return 0f; },
(s,v) => { BSParam.ResetConstraintSolverTainted(s, v); } ),
};
// Convert a boolean to our numeric true and false values
public static float NumericBool(bool b)
{
return (b ? ConfigurationParameters.numericTrue : ConfigurationParameters.numericFalse);
}
// Convert numeric true and false values to a boolean
public static bool BoolNumeric(float b)
{
return (b == ConfigurationParameters.numericTrue ? true : false);
}
// Search through the parameter definitions and return the matching
// ParameterDefn structure.
// Case does not matter as names are compared after converting to lower case.
// Returns 'false' if the parameter is not found.
internal static bool TryGetParameter(string paramName, out ParameterDefnBase defn)
{
bool ret = false;
ParameterDefnBase foundDefn = null;
string pName = paramName.ToLower();
foreach (ParameterDefnBase parm in ParameterDefinitions)
{
if (pName == parm.name.ToLower())
{
foundDefn = parm;
ret = true;
break;
}
}
defn = foundDefn;
return ret;
}
// Pass through the settable parameters and set the default values
internal static void SetParameterDefaultValues(BSScene physicsScene)
{
foreach (ParameterDefnBase parm in ParameterDefinitions)
{
parm.AssignDefault(physicsScene);
}
}
// Get user set values out of the ini file.
internal static void SetParameterConfigurationValues(BSScene physicsScene, IConfig cfg)
{
foreach (ParameterDefnBase parm in ParameterDefinitions)
{
parm.SetValue(physicsScene, cfg.GetString(parm.name, parm.GetValue(physicsScene)));
}
}
internal static PhysParameterEntry[] SettableParameters = new PhysParameterEntry[1];
// This creates an array in the correct format for returning the list of
// parameters. This is used by the 'list' option of the 'physics' command.
internal static void BuildParameterTable()
{
if (SettableParameters.Length < ParameterDefinitions.Length)
{
List<PhysParameterEntry> entries = new List<PhysParameterEntry>();
for (int ii = 0; ii < ParameterDefinitions.Length; ii++)
{
ParameterDefnBase pd = ParameterDefinitions[ii];
entries.Add(new PhysParameterEntry(pd.name, pd.desc));
}
// make the list alphabetical for ease of finding anything
entries.Sort((ppe1, ppe2) => { return ppe1.name.CompareTo(ppe2.name); });
SettableParameters = entries.ToArray();
}
}
// =====================================================================
// =====================================================================
// There are parameters that, when set, cause things to happen in the physics engine.
// This causes the broadphase collision cache to be cleared.
private static void ResetBroadphasePoolTainted(BSScene pPhysScene, float v)
{
BSScene physScene = pPhysScene;
physScene.TaintedObject(BSScene.DetailLogZero, "BSParam.ResetBroadphasePoolTainted", delegate()
{
physScene.PE.ResetBroadphasePool(physScene.World);
});
}
// This causes the constraint solver cache to be cleared and reset.
private static void ResetConstraintSolverTainted(BSScene pPhysScene, float v)
{
BSScene physScene = pPhysScene;
physScene.TaintedObject(BSScene.DetailLogZero, "BSParam.ResetConstraintSolver", delegate()
{
physScene.PE.ResetConstraintSolver(physScene.World);
});
}
}
}
| 57.946316 | 180 | 0.655362 | [
"BSD-3-Clause"
] | UbitUmarov/OpenSim | OpenSim/Region/PhysicsModules/BulletS/BSParam.cs | 55,049 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class animAnimStateTransitionCondition_Timed : animIAnimStateTransitionCondition
{
[Ordinal(0)] [RED("timeToFireTransition")] public CFloat TimeToFireTransition { get; set; }
public animAnimStateTransitionCondition_Timed(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 29.5 | 125 | 0.760593 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/animAnimStateTransitionCondition_Timed.cs | 457 | C# |
namespace Silver
{
public class Expenditure : Entity
{
private string name;
public string Name
{
get => name;
set
{
if (value == name) return;
name = value;
OnPropertyChanged();
}
}
}
}
| 17.210526 | 42 | 0.394495 | [
"MIT"
] | liveinmegacity/Silver | Silver/Models/Expenditure.cs | 327 | C# |
//
// ITagCollection.cs
//
// Author:
// Tomona Nanase <nanase@users.noreply.github.com>
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tomona Nanase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Collections.Generic;
namespace Sharp98
{
/// <summary>
/// タグを保持するためのインタフェースです。
/// </summary>
public interface ITagCollection : IDictionary<string, string>, IExportable, IBufferExportable
{
}
}
| 36.8 | 97 | 0.738451 | [
"MIT"
] | nanase/Sharp98 | Sharp98/Interface/ITagCollection.cs | 1,514 | C# |
using EasyManager.Domain.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace EasyManager.Infra.Data.Mapping
{
public class PurchaseMap : IEntityTypeConfiguration<Purchase>
{
public void Configure(EntityTypeBuilder<Purchase> builder)
{
builder.Property(c => c.Id)
.HasColumnName("Id");
}
}
} | 27.533333 | 66 | 0.690073 | [
"Apache-2.0"
] | fahelmoreira/EasyManagerERP | src/EasyManager.Infra.Data/Mapping/PurchaseMap.cs | 413 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) 2015 Microsoft Corporation
//
// 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.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.OneDrive.Sdk
{
/// <summary>
/// The type PermissionsCollectionPage.
/// </summary>
public partial class PermissionsCollectionPage : CollectionPage<Permission>, IPermissionsCollectionPage
{
/// <summary>
/// Gets the next page <see cref="IPermissionsCollectionRequest"/> instance.
/// </summary>
public IPermissionsCollectionRequest NextPageRequest { get; private set; }
/// <summary>
/// Initializes the NextPageRequest property.
/// </summary>
public void InitializeNextPageRequest(IOneDriveClient oneDriveClient, string nextPageLinkString)
{
if (!string.IsNullOrEmpty(nextPageLinkString))
{
this.NextPageRequest = new PermissionsCollectionRequest(
nextPageLinkString,
oneDriveClient,
null);
}
}
}
}
| 44.711538 | 107 | 0.64043 | [
"MIT"
] | jbatonnet/SmartSync | SmartSync.OneDrive/OneDriveSdk/Requests/Generated/PermissionsCollectionPage.cs | 2,325 | C# |
using System;
namespace react_redux_cs
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
}
| 19.375 | 70 | 0.577419 | [
"Unlicense"
] | SeptBlast/opensource_group14 | react_projects_cs/react-redux-cs/WeatherForecast.cs | 310 | C# |
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
namespace ICSharpCode.Decompiler.TypeSystem
{
/// <summary>
/// Represents a property or indexer.
/// </summary>
public interface IProperty : IParameterizedMember
{
bool CanGet { get; }
bool CanSet { get; }
IMethod Getter { get; }
IMethod Setter { get; }
bool IsIndexer { get; }
}
}
| 41.371429 | 93 | 0.746547 | [
"MIT"
] | 164306530/ILSpy | ICSharpCode.Decompiler/TypeSystem/IProperty.cs | 1,450 | C# |
using ElmSharp;
namespace Tizen.UIExtensions.ElmSharp
{
public class Tabs : Toolbar, ITabs
{
TabsType _type;
public Tabs(EvasObject parent) :base(parent)
{
Style = ThemeConstants.Toolbar.Styles.Material;
SelectionMode = ToolbarSelectionMode.Always;
}
public TabsType Scrollable
{
get => _type;
set
{
switch (value)
{
case TabsType.Fixed:
this.ShrinkMode = ToolbarShrinkMode.Expand;
break;
case TabsType.Scrollable:
this.ShrinkMode = ToolbarShrinkMode.Scroll;
break;
}
_type = value;
}
}
}
}
| 24.558824 | 67 | 0.456287 | [
"Apache-2.0"
] | Samsung/Tizen.UIExtensions | src/Tizen.UIExtensions.ElmSharp/Tabs.cs | 837 | C# |
/*
* SendinBlue API
*
* SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails and SMS - and much more... You can download our wrappers at https://github.com/orgs/sendinblue **Possible responses** | Code | Message | | :- -- -- -- -- -- --: | - -- -- -- -- -- -- | | 200 | OK. Successful Request | | 201 | OK. Successful Creation | | 202 | OK. Request accepted | | 204 | OK. Successful Update/Deletion | | 400 | Error. Bad Request | | 401 | Error. Authentication Needed | | 402 | Error. Not enough credit, plan upgrade needed | | 403 | Error. Permission denied | | 404 | Error. Object does not exist | | 405 | Error. Method not allowed | | 406 | Error. Not Acceptable |
*
* OpenAPI spec version: 3.0.0
* Contact: contact@sendinblue.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using SwaggerDateConverter = sib_api_v3_sdk.Client.SwaggerDateConverter;
namespace sib_api_v3_sdk.Model
{
/// <summary>
/// GetChildrenList
/// </summary>
[DataContract]
public partial class GetChildrenList : IEquatable<GetChildrenList>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetChildrenList" /> class.
/// </summary>
/// <param name="children">Your children's account information.</param>
/// <param name="count">Number of child accounts.</param>
public GetChildrenList(List<Object> children = default(List<Object>), long? count = default(long?))
{
this.Children = children;
this.Count = count;
}
/// <summary>
/// Your children's account information
/// </summary>
/// <value>Your children's account information</value>
[DataMember(Name="children", EmitDefaultValue=false)]
public List<Object> Children { get; set; }
/// <summary>
/// Number of child accounts
/// </summary>
/// <value>Number of child accounts</value>
[DataMember(Name="count", EmitDefaultValue=false)]
public long? Count { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class GetChildrenList {\n");
sb.Append(" Children: ").Append(Children).Append("\n");
sb.Append(" Count: ").Append(Count).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as GetChildrenList);
}
/// <summary>
/// Returns true if GetChildrenList instances are equal
/// </summary>
/// <param name="input">Instance of GetChildrenList to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(GetChildrenList input)
{
if (input == null)
return false;
return
(
this.Children == input.Children ||
this.Children != null &&
this.Children.SequenceEqual(input.Children)
) &&
(
this.Count == input.Count ||
(this.Count != null &&
this.Count.Equals(input.Count))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Children != null)
hashCode = hashCode * 59 + this.Children.GetHashCode();
if (this.Count != null)
hashCode = hashCode * 59 + this.Count.GetHashCode();
return hashCode;
}
}
}
}
| 38.473282 | 853 | 0.561706 | [
"MIT"
] | ajbeaven/APIv3-csharp-library | src/sib_api_v3_sdk/Model/GetChildrenList.cs | 5,040 | C# |
/*
* Copyright (c) 2016, Will Strohl
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of Will Strohl, nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using DotNetNuke.Entities.Controllers;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using WillStrohl.Modules.CodeCamp.Components;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Scheduling;
namespace WillStrohl.Modules.CodeCamp
{
/// <summary>
/// A base class for all module views to use
/// </summary>
public class CodeCampModuleBase : PortalModuleBase
{
#region Localization
/// <summary>
/// GetLocalizedString - A shortcut to localizing a string object
/// </summary>
/// <param name="localizationKey">a unique string key representing the localization value</param>
/// <returns></returns>
protected string GetLocalizedString(string localizationKey)
{
if (!string.IsNullOrEmpty(localizationKey))
{
return Localization.GetString(localizationKey, this.LocalResourceFile);
}
else
{
return string.Empty;
}
}
/// <summary>
/// GetLocalizedString - A shortcut to localizing a string object
/// </summary>
/// <param name="localizationKey">a unique string key representing the localization value</param>
/// <param name="localResourceFilePath">the path to the localization file</param>
/// <returns></returns>
protected string GetLocalizedString(string localizationKey, string localResourceFilePath)
{
if (!string.IsNullOrEmpty(localizationKey))
{
return Localization.GetString(localizationKey, localResourceFilePath);
}
else
{
return string.Empty;
}
}
#endregion
}
} | 39.709302 | 105 | 0.687848 | [
"MIT"
] | hismightiness/dnnextensions | Modules/CodeCamp/Components/CodeCampModuleBase.cs | 3,415 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// MIT License
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Xml.XPath;
using Microsoft.HealthVault.Helpers;
namespace Microsoft.HealthVault.Thing
{
/// <summary>
/// Provides online and offline access permissions to persons for a health
/// record item type (<see cref="ThingTypeDefinition"/>) in a
/// health record in the context of an application.
/// </summary>
///
public class ThingTypePermission
{
/// <summary>
/// Creates an instance of
/// <see cref="ThingTypePermission"/> from XML.
/// </summary>
///
/// <param name="navigator">
/// The XML containing the <see cref="ThingTypePermission"/>
/// information.
/// </param>
///
/// <returns>
/// A new instance of <see cref="ThingTypePermission"/>
/// populated with the information in the XML.
/// </returns>
///
/// <exception cref="ArgumentNullException">
/// The XPathNavigator intended to contain the XML information is <b>null</b>.
/// </exception>
///
public static ThingTypePermission CreateFromXml(
XPathNavigator navigator)
{
Validator.ThrowIfNavigatorNull(navigator);
ThingTypePermission permissions
= new ThingTypePermission();
permissions.ParseXml(navigator);
return permissions;
}
/// <summary>
/// Gets or sets the unique identifier of the thing
/// type associated with the permissions.
/// </summary>
///
/// <returns>
/// The GUID of the thing type.
/// </returns>
///
public Guid TypeId { get; set; }
/// <summary>
/// Gets or sets the permissions for online access for the person, for the
/// thing type in the health record in the context of
/// the application.
/// </summary>
///
/// <returns>
/// The <see cref="ThingPermissions"/> for online access.
/// </returns>
///
public ThingPermissions OnlineAccessPermissions { get; set; }
/// <summary>
/// Gets or sets the permissions for offline access for the person, for the
/// thing type in the health record in the context of
/// the application.
/// </summary>
///
/// <returns>
/// The <see cref="ThingPermissions"/> for offline access.
/// </returns>
///
public ThingPermissions OfflineAccessPermissions { get; set; }
internal void ParseXml(XPathNavigator navigator)
{
TypeId = new Guid(navigator.SelectSingleNode(
"thing-type-id").Value);
XPathNavigator onlinePermissions
= navigator.SelectSingleNode("online-access-permissions");
OnlineAccessPermissions = ThingPermissions.None;
if (onlinePermissions != null)
{
XPathNodeIterator nodes
= onlinePermissions.Select("permission");
try
{
foreach (XPathNavigator navPerms in nodes)
{
OnlineAccessPermissions
|= (ThingPermissions)Enum.Parse(
typeof(ThingPermissions),
navPerms.Value);
}
}
catch (ArgumentException)
{
OnlineAccessPermissions
= ThingPermissions.None;
}
}
XPathNavigator offlinePermissions
= navigator.SelectSingleNode("offline-access-permissions");
OfflineAccessPermissions = ThingPermissions.None;
if (offlinePermissions != null)
{
XPathNodeIterator nodes
= offlinePermissions.Select("permission");
try
{
foreach (XPathNavigator navPerms in nodes)
{
OfflineAccessPermissions
|= (ThingPermissions)Enum.Parse(
typeof(ThingPermissions),
navPerms.Value);
}
}
catch (ArgumentException)
{
OfflineAccessPermissions
= ThingPermissions.None;
}
}
}
}
}
| 39.143836 | 463 | 0.55783 | [
"MIT"
] | Bhaskers-Blu-Org2/healthvault-dotnetstandard-sdk | Microsoft.HealthVault/Thing/ThingTypePermission.cs | 5,715 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using aceryansoft.codeflow.model.Config;
using aceryansoft.codeflow.model.Delegates;
namespace aceryansoft.codeflow.core.Containers
{
internal class SwitchCaseContainerFlow : SequenceContainerFlow
{
private readonly Func<ICodeFlowContext, object[], object> _switchExpression;
private List<Func<object, object[], bool>> _switchSelectors = new List<Func<object, object[], bool>>();
internal SwitchCaseContainerFlow(Func<ICodeFlowContext, object[], object> switchExpression)
{
_switchExpression = switchExpression;
}
public void Case(Func<object, object[], bool> switchSelector)
{
var caseContainer = new SwitchCaseSelectorContainerFlow(switchSelector, _switchExpression);
if (!IsAllContainerClosed()) // close previous case statements
{
CloseContainer();
}
_switchSelectors.Add(switchSelector);
AddContainer(caseContainer);
}
public void Default()
{
var defaultContainer = new SwitchCaseDefaultContainerFlow(_switchSelectors, _switchExpression);
if (!IsAllContainerClosed()) // close previous case statements
{
CloseContainer();
}
AddContainer(defaultContainer);
}
}
internal class SwitchCaseSelectorContainerFlow : SequenceContainerFlow
{
private readonly Func<object, object[], bool> _switchSelector;
private readonly Func<ICodeFlowContext, object[], object> _switchExpression;
public SwitchCaseSelectorContainerFlow(Func<object, object[], bool> switchSelector, Func<ICodeFlowContext, object[], object> switchExpression)
{
_switchSelector = switchSelector;
_switchExpression = switchExpression;
}
public override IExecutionContext Execute(ICodeFlowContext context, Func<ActivityDelegate, ActivityDelegate> activityFilter, params object[] inputs)
{
var childResults = new List<IExecutionContext>();
int lastErrorCode = 0;
var switchRes = _switchExpression(context, inputs);
if (_switchSelector(switchRes, inputs))
{
return base.Execute(context, activityFilter, inputs);
}
return ExecutionContext.GetCombinedSequenceResult(childResults, lastErrorCode);
}
}
internal class SwitchCaseDefaultContainerFlow : SequenceContainerFlow
{
private readonly List<Func<object, object[], bool>> _switchSelectors;
private readonly Func<ICodeFlowContext, object[], object> _switchExpression;
public SwitchCaseDefaultContainerFlow(List<Func<object, object[], bool>> switchSelectors, Func<ICodeFlowContext, object[], object> switchExpression)
{
_switchSelectors = switchSelectors;
_switchExpression = switchExpression;
}
public override IExecutionContext Execute(ICodeFlowContext context, Func<ActivityDelegate, ActivityDelegate> activityFilter, params object[] inputs)
{
var childResults = new List<IExecutionContext>();
int lastErrorCode = 0;
var switchRes = _switchExpression(context, inputs);
if (_switchSelectors.All(x => x(switchRes, inputs) == false))
{
return base.Execute(context, activityFilter, inputs);
}
return ExecutionContext.GetCombinedSequenceResult(childResults, lastErrorCode);
}
}
} | 41 | 156 | 0.660729 | [
"Apache-2.0"
] | aceryan-consulting/aceryansoft.codeflow | src/aceryansoft.codeflow.core/Containers/SwitchCaseContainerFlow.cs | 3,651 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using AM1;
public class TitleManager : MonoBehaviour {
private void Start()
{
Time.timeScale = 1f;
SoundController.PlayBGM(SoundController.BGM.TITLE);
// ゲーム開始時に、新規ゲームとして初期化するフラグを設定
GameSystem.IsGameStart = true;
}
private void OnMouseDown()
{
if (!GameSystem.IsRankingShowing && GameSystem.IsControllerable)
{
SoundController.Play(SoundController.SE.CLICK);
SoundController.StopBGM(true);
LevelChanger.ChangeScene("Game");
}
}
}
| 23.37037 | 73 | 0.646593 | [
"MIT"
] | am1tanaka/OpenFrameworkMini | Assets/AM1Framework/Scripts/TitleManager.cs | 687 | C# |
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using GroupDocs.Viewer.Converter.Options;
using GroupDocs.Viewer.Domain;
using GroupDocs.Viewer.Domain.Containers;
using GroupDocs.Viewer.Domain.Html;
using GroupDocs.Viewer.Handler;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http.Results;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using ViewerModernWebPart.Helpers;
namespace ViewerModernWebPart.Layouts.ViewerModernWebPart
{
public partial class GetAttachmentHtml : LayoutsPageBase
{
public void Page_Load(object sender, EventArgs e)
{
var file = GetValueFromQueryString("file");
var page = Convert.ToInt32(GetValueFromQueryString("page"));
var attachment = GetValueFromQueryString("attachment");
string watermarkText = GetValueFromQueryString("watermarkText");
int? watermarkColor = Convert.ToInt32(GetValueFromQueryString("watermarkColor"));
WatermarkPosition watermarkPosition = (WatermarkPosition)Enum.Parse(typeof(WatermarkPosition), GetValueFromQueryString("watermarkPosition"), true);
string widthFromQuery = GetValueFromQueryString("watermarkWidth");
int? watermarkWidth = GetValueFromQueryString("watermarkWidth") == "null" ? null : (int?)Convert.ToInt32(GetValueFromQueryString("watermarkWidth"));
byte watermarkOpacity = Convert.ToByte(GetValueFromQueryString("watermarkOpacity"));
ViewerHtmlHandler handler = Utils.CreateViewerHtmlHandler();
List<int> pageNumberstoRender = new List<int>();
pageNumberstoRender.Add(page);
HtmlOptions o = new HtmlOptions();
o.PageNumbersToRender = pageNumberstoRender;
o.PageNumber = page;
o.CountPagesToRender = 1;
o.HtmlResourcePrefix = (String.Format(
"/page/resource?file=%s&page=%d&resource=",
file,
page
));
if (watermarkText != "")
o.Watermark = Utils.GetWatermark(watermarkText, watermarkColor, watermarkPosition, watermarkWidth, watermarkOpacity);
var docInfo = handler.GetDocumentInfo(file);
List<PageHtml> list = Utils.LoadPageHtmlList(handler, file, o);
string fullHtml = "";
foreach (AttachmentBase attachmentBase in docInfo.Attachments.Where(x => x.Name == attachment))
{
// Get attachment document html representation
List<PageHtml> pages = handler.GetPages(attachmentBase, o);
foreach (PageHtml pageHtml in pages.Where(x => x.PageNumber == page)) { fullHtml += pageHtml.HtmlContent; };
}
HttpContext.Current.Response.ContentType = "text/html";
HttpContext.Current.Response.Write(fullHtml);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
private String GetValueFromQueryString(String value)
{
try
{
return Request.QueryString[value].ToString();
}
catch (System.Exception exp)
{
return String.Empty;
}
}
}
}
| 40.77907 | 160 | 0.656687 | [
"MIT"
] | aliahmedgroupdocs/GroupDocs.Viewer-for-.NET | Plugins/GroupDocs_Viewer_Modern_WebPart/ViewerModernWebPart/Layouts/ViewerModernWebPart/GetAttachmentHtml.aspx.cs | 3,509 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.ML;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.Data;
using Microsoft.ML.Runtime.PipelineInference;
using Microsoft.ML.Runtime.MLTesting.Inference;
namespace Microsoft.ML.Runtime.RunTests
{
using Xunit;
using Xunit.Abstractions;
public sealed class TestDatasetInference : BaseTestBaseline
{
public TestDatasetInference(ITestOutputHelper helper)
: base(helper)
{
}
[Fact(Skip="Disabled")]
public void DatasetInferenceTest()
{
var datasets = new[]
{
GetDataPath(@"..\UCI\adult.train"),
GetDataPath(@"..\UCI\adult.test"),
GetDataPath(@"..\UnitTest\breast-cancer.txt"),
};
using (var env = new TlcEnvironment())
{
var h = env.Register("InferDatasetFeatures", seed: 0, verbose: false);
using (var ch = h.Start("InferDatasetFeatures"))
{
for (int i = 0; i < datasets.Length; i++)
{
var sample = TextFileSample.CreateFromFullFile(h, datasets[i]);
var splitResult = TextFileContents.TrySplitColumns(h, sample, TextFileContents.DefaultSeparators);
if (!splitResult.IsSuccess)
throw ch.ExceptDecode("Couldn't detect separator.");
var typeInfResult = ColumnTypeInference.InferTextFileColumnTypes(Env, sample,
new ColumnTypeInference.Arguments
{
Separator = splitResult.Separator,
AllowSparse = splitResult.AllowSparse,
AllowQuote = splitResult.AllowQuote,
ColumnCount = splitResult.ColumnCount
});
if (!typeInfResult.IsSuccess)
return;
ColumnGroupingInference.GroupingColumn[] columns = null;
bool hasHeader = false;
columns = InferenceUtils.InferColumnPurposes(ch, h, sample, splitResult, out hasHeader);
Guid id = new Guid("60C77F4E-DB62-4351-8311-9B392A12968E");
var commandArgs = new DatasetFeatureInference.Arguments(typeInfResult.Data,
columns.Select(
col =>
new DatasetFeatureInference.Column(col.SuggestedName, col.Purpose, col.ItemKind,
col.ColumnRangeSelector)).ToArray(), sample.FullFileSize, sample.ApproximateRowCount,
false, id, true);
string jsonString = DatasetFeatureInference.InferDatasetFeatures(env, commandArgs);
var outFile = string.Format("dataset-inference-result-{0:00}.txt", i);
string dataPath = GetOutputPath(@"..\Common\Inference", outFile);
using (var sw = new StreamWriter(File.Create(dataPath)))
sw.WriteLine(jsonString);
CheckEquality(@"..\Common\Inference", outFile);
}
}
}
Done();
}
[Fact]
public void InferSchemaCommandTest()
{
var datasets = new[]
{
GetDataPath(Path.Combine("..", "data", "wikipedia-detox-250-line-data.tsv"))
};
using (var env = new TlcEnvironment())
{
var h = env.Register("InferSchemaCommandTest", seed: 0, verbose: false);
using (var ch = h.Start("InferSchemaCommandTest"))
{
for (int i = 0; i < datasets.Length; i++)
{
var outFile = string.Format("dataset-infer-schema-result-{0:00}.txt", i);
string dataPath = GetOutputPath(Path.Combine("..", "Common", "Inference"), outFile);
var args = new InferSchemaCommand.Arguments()
{
DataFile = datasets[i],
OutputFile = dataPath,
};
var cmd = new InferSchemaCommand(Env, args);
cmd.Run();
CheckEquality(Path.Combine("..", "Common", "Inference"), outFile);
}
}
}
Done();
}
[Fact]
public void InferRecipesCommandTest()
{
var datasets = new Tuple<string, string>[]
{
Tuple.Create(
GetDataPath(Path.Combine("..", "data", "wikipedia-detox-250-line-data.tsv")),
GetDataPath(Path.Combine("..", "data", "wikipedia-detox-250-line-data-schema.txt")))
};
using (var env = new TlcEnvironment())
{
var h = env.Register("InferRecipesCommandTest", seed: 0, verbose: false);
using (var ch = h.Start("InferRecipesCommandTest"))
{
for (int i = 0; i < datasets.Length; i++)
{
var outFile = string.Format("dataset-infer-recipe-result-{0:00}.txt", i);
string dataPath = GetOutputPath(Path.Combine("..", "Common", "Inference"), outFile);
var args = new InferRecipesCommand.Arguments()
{
DataFile = datasets[i].Item1,
SchemaDefinitionFile = datasets[i].Item2,
RspOutputFile = dataPath
};
var cmd = new InferRecipesCommand(Env, args);
cmd.Run();
CheckEquality(Path.Combine("..", "Common", "Inference"), outFile);
}
}
}
Done();
}
}
}
| 41.401274 | 125 | 0.489385 | [
"MIT"
] | ChangweiZhang/machinelearning | test/Microsoft.ML.Predictor.Tests/TestDatasetInference.cs | 6,500 | C# |
using System;
using System.ComponentModel.DataAnnotations;
namespace FileUpload.Models.Request
{
public class PeopleUpdateRequest : PeopleAddRequest
{
[Range(1,1000000000, ErrorMessage = "Id out of Range.")]
public int Id { get; set; }
}
}
| 22.5 | 64 | 0.688889 | [
"MIT"
] | eddiedozier/ReactFileUpload | FileUpload.Models/Request/PeopleUpdateRequest.cs | 272 | C# |
using IniParser.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RWS
{
public partial class attachments : Form
{
public attachments()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
Close();
}
private void button1_Click(object sender, EventArgs e)
{
List<Control> txt = Controls.OfType<TextBox>().Cast<Control>().ToList();
List<Control> cb = Controls.OfType<ComboBox>().Cast<Control>().ToList();
List<CheckBox> ch = Controls.OfType<CheckBox>().Cast<CheckBox>().ToList();
string[] sss = Directory.GetFiles(New_edit.path, "*.ini");
var parser = new IniParser.FileIniDataParser();
IniData data = parser.ReadFile(sss[0]);
for (int i = 0; i < txt.Count; i++)
{
if (txt[i].Text != "" && txt[i].Text != " " && txt[i].Enabled)
{
if (txt[i].Tag.ToString() != "")
data["attachment_" + namee.Text][txt[i].Tag.ToString()] = txt[i].Text;
}
else if (data["attachment_" + namee.Text][txt[i].Tag.ToString()] != null)
{
data["attachment_" + namee.Text].RemoveKey(txt[i].Tag.ToString());
}
}
for (int i = 0; i < cb.Count; i++)
{
if (cb[i].Text != "" && cb[i].Text != " " && cb[i].Enabled)
{
if (cb[i].Tag.ToString() != "")
data["attachment_" + namee.Text][cb[i].Tag.ToString()] = cb[i].Text;
}
else if (data["attachment_" + namee.Text][cb[i].Tag.ToString()] != null)
{
data["attachment_" + namee.Text].RemoveKey(cb[i].Tag.ToString());
}
}
for (int i = 0; i < ch.Count; i++)
{
if (ch[i].Tag.ToString() != "")
data["attachment_" + namee.Text][ch[i].Tag.ToString()] = ch[i].Checked.ToString();
else if (data["attachment_" + namee.Text][ch[i].Tag.ToString()] != null)
{
data["attachment_" + namee.Text].RemoveKey(ch[i].Tag.ToString());
}
}
parser.WriteFile(sss[0], data);
Close();
}
private void attachments_Load(object sender, EventArgs e)
{
if (New_edit.lastact != null)
{
namee.Enabled = false;
List<Control> txt = Controls.OfType<TextBox>().Cast<Control>().ToList();
List<Control> cb = Controls.OfType<ComboBox>().Cast<Control>().ToList();
List<CheckBox> ch = Controls.OfType<CheckBox>().Cast<CheckBox>().ToList();
string[] sss = Directory.GetFiles(New_edit.path, "*.ini");
var parser = new IniParser.FileIniDataParser();
IniData data = parser.ReadFile(sss[0]);
for (int i = 0; i < txt.Count; i++)
{
if (txt[i].Tag != null && data["action_" + New_edit.lastact][txt[i].Tag.ToString()] != null)
txt[i].Text = data["action_" + New_edit.lastact][txt[i].Tag.ToString()].Replace("\\n", Environment.NewLine);
}
for (int i = 0; i < cb.Count; i++)
{
if (cb[i].Tag != null)
cb[i].Text = data["action_" + New_edit.lastact][cb[i].Tag.ToString()];
}
for (int i = 0; i < ch.Count; i++)
{
if (ch[i].Tag != null)
ch[i].Checked = Convert.ToBoolean(data["action_" + New_edit.lastact][ch[i].Tag.ToString()]);
}
namee.Text = New_edit.lastact;
}
}
}
}
| 40.320388 | 132 | 0.474356 | [
"Unlicense"
] | kc101010/RWStudio | RWS/attachments.cs | 4,155 | C# |
using System;
using System.Linq;
using EnterpriseWebLibrary.Configuration;
using EnterpriseWebLibrary.InstallationSupportUtility.DatabaseAbstraction;
using EnterpriseWebLibrary.InstallationSupportUtility.InstallationModel;
using EnterpriseWebLibrary.InstallationSupportUtility.SystemManagerInterface.Messages.SystemListMessage;
using EnterpriseWebLibrary.IO;
using Tewl.IO;
namespace EnterpriseWebLibrary.InstallationSupportUtility {
/// <summary>
/// Installation Support Utility use only.
/// </summary>
public class DataUpdateStatics {
public static Action DownloadDataPackageAndGetDataUpdateMethod(
ExistingInstallation installation, bool installationIsStandbyDb, RsisInstallation source, bool forceNewPackageDownload,
OperationResult operationResult ) {
var recognizedInstallation = installation as RecognizedInstallation;
var packageZipFilePath = recognizedInstallation != null ? source.GetDataPackage( forceNewPackageDownload, operationResult ) : "";
return () => {
IoMethods.ExecuteWithTempFolder(
tempFolderPath => {
var packageFolderPath = EwlStatics.CombinePaths( tempFolderPath, "Package" );
if( packageZipFilePath.Any() )
ZipOps.UnZipFileAsFolder( packageZipFilePath, packageFolderPath );
// Delete and re-create databases.
DatabaseOps.DeleteAndReCreateDatabaseFromFile(
installation.ExistingInstallationLogic.Database,
databaseHasMinimumDataRevision( installation.ExistingInstallationLogic.RuntimeConfiguration.PrimaryDatabaseSystemConfiguration ),
packageFolderPath );
if( recognizedInstallation != null )
foreach( var secondaryDatabase in recognizedInstallation.RecognizedInstallationLogic.SecondaryDatabasesIncludedInDataPackages ) {
DatabaseOps.DeleteAndReCreateDatabaseFromFile(
secondaryDatabase,
databaseHasMinimumDataRevision(
installation.ExistingInstallationLogic.RuntimeConfiguration.GetSecondaryDatabaseSystemConfiguration(
secondaryDatabase.SecondaryDatabaseName ) ),
packageFolderPath );
}
} );
DatabaseOps.WaitForDatabaseRecovery( installation.ExistingInstallationLogic.Database );
if( recognizedInstallation != null )
recompileProceduresInSecondaryOracleDatabases( recognizedInstallation );
if( !installationIsStandbyDb ) {
// Bring database logic up to date with the rest of the logic in this installation. In other words, reapply changes lost when we deleted the database.
StatusStatics.SetStatus( "Updating database logic..." );
DatabaseOps.UpdateDatabaseLogicIfUpdateFileExists(
installation.ExistingInstallationLogic.Database,
installation.ExistingInstallationLogic.DatabaseUpdateFilePath,
installation.ExistingInstallationLogic.RuntimeConfiguration.InstallationType == InstallationType.Development );
}
// If we're an intermediate installation and we are getting data from a live installation, sanitize the data and do other conversion commands.
if( installation is RecognizedInstalledInstallation recognizedInstalledInstallation &&
recognizedInstalledInstallation.KnownInstallationLogic.RsisInstallation.InstallationTypeElements is IntermediateInstallationElements &&
source.InstallationTypeElements is LiveInstallationElements ) {
StatusStatics.SetStatus( "Executing live -> intermediate conversion commands..." );
doDatabaseLiveToIntermediateConversionIfCommandsExist(
installation.ExistingInstallationLogic.Database,
installation.ExistingInstallationLogic.RuntimeConfiguration.PrimaryDatabaseSystemConfiguration );
foreach( var secondaryDatabase in recognizedInstallation.RecognizedInstallationLogic.SecondaryDatabasesIncludedInDataPackages ) {
doDatabaseLiveToIntermediateConversionIfCommandsExist(
secondaryDatabase,
installation.ExistingInstallationLogic.RuntimeConfiguration.GetSecondaryDatabaseSystemConfiguration( secondaryDatabase.SecondaryDatabaseName ) );
}
}
};
}
private static bool databaseHasMinimumDataRevision( Configuration.SystemGeneral.Database database ) =>
( database?.MinimumDataRevisionSpecified ?? false ) && database.MinimumDataRevision > 0;
/// <summary>
/// Recompile procedures in secondary Oracle databases in case there are inter-database dependencies that prevented the procedures from being valid when the
/// database was created.
/// </summary>
private static void recompileProceduresInSecondaryOracleDatabases( RecognizedInstallation installation ) {
foreach( var secondaryDatabase in installation.RecognizedInstallationLogic.SecondaryDatabasesIncludedInDataPackages ) {
if( secondaryDatabase is DatabaseAbstraction.Databases.Oracle )
secondaryDatabase.ExecuteDbMethod(
cn => {
foreach( var procedure in secondaryDatabase.GetProcedures() ) {
var command = cn.DatabaseInfo.CreateCommand();
command.CommandText = "ALTER PROCEDURE " + procedure + " COMPILE";
cn.ExecuteNonQueryCommand( command );
}
} );
}
}
private static void doDatabaseLiveToIntermediateConversionIfCommandsExist( Database database, Configuration.SystemGeneral.Database configuration ) {
if( !( configuration?.LiveToIntermediateConversionCommands ?? Enumerable.Empty<string>() ).Any() )
return;
database.ExecuteDbMethod(
cn => {
foreach( var commandText in configuration.LiveToIntermediateConversionCommands ) {
var cmd = cn.DatabaseInfo.CreateCommand();
cmd.CommandText = commandText;
cn.ExecuteNonQueryCommand( cmd, isLongRunning: true );
}
} );
database.ShrinkAfterPostUpdateDataCommands();
}
}
} | 53.165138 | 159 | 0.770664 | [
"MIT"
] | enduracode/enterprise-web-library | Core/InstallationSupportUtility/DataUpdateStatics.cs | 5,797 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dano.ACECalculator
{
public class StormIntensityNode
{
public DateTime DateTime { get; set; }
public double Intensity { get; set; }
public double ACE { get; set; }
public double Total { get; set; }
}
}
| 22 | 46 | 0.665775 | [
"MIT"
] | Cosmo224/TrackMaker | Dano.ACECalculator/Core/StormIntensityNode.cs | 376 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SuggestionSystem.Web.Api")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SuggestionSystem.Web.Api")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f7bc4e42-07b9-4b26-8013-2c3f299ff850")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.222222 | 84 | 0.752907 | [
"MIT"
] | fullstack101-alumni/Fall2016-SuggestionSystem | Source/SuggestionSystem/Web/SuggestionSystem.Web.Api/Properties/AssemblyInfo.cs | 1,379 | C# |
using Expenses.Data;
using ExpensesManager.Models;
using ExpensesManager.Services;
using System.Collections.Generic;
using System.Linq;
namespace ExpensesManager.Services
{
public class ExpensesService : IExpensesService
{
public void AddExpense(Expense exp)
{
Data.Expenses.Add(exp);
}
public void DeleteExpense(int expId)
{
var expense = Data.Expenses.FirstOrDefault(n => n.Id == expId);
if(expense != null)
{
Data.Expenses.Remove(expense);
}
}
public List<Expense> GetAllExpenses() => Data.Expenses.ToList();
public Expense GetExpenseById(int expId) => Data.Expenses.FirstOrDefault(n => n.Id == expId);
public void UpdateExpense(int expId, Expense exp)
{
var expTrip = Data.Expenses.FirstOrDefault(n => n.Id == expId);
if(expTrip != null)
{
expTrip.Name = exp.Name;
expTrip.Description = exp.Description;
expTrip.Date = exp.Date;
expTrip.Amount = exp.Amount;
}
}
}
} | 27.690476 | 101 | 0.566638 | [
"MIT"
] | kasuken/Course-Material | ASP.NET Core + React/ExpensesManager/ExpensesManager/Services/ExpensesService.cs | 1,163 | C# |
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Testura.Code.Builders.BuildMembers;
namespace Testura.Code.Builders.BuilderHelpers
{
internal class MemberHelper
{
public MemberHelper()
{
Members = new List<IBuildMember>();
}
public List<IBuildMember> Members { get; }
public MemberHelper AddMembers(params IBuildMember[] members)
{
Members.AddRange(members);
return this;
}
public TypeDeclarationSyntax BuildMembers(TypeDeclarationSyntax type)
{
return type.WithMembers(BuildSyntaxList());
}
public CompilationUnitSyntax BuildMembers(CompilationUnitSyntax compilationUnitSyntax)
{
return compilationUnitSyntax.WithMembers(BuildSyntaxList());
}
public SyntaxList<MemberDeclarationSyntax> BuildSyntaxList()
{
var members = default(SyntaxList<MemberDeclarationSyntax>);
foreach (var member in Members)
{
members = member.AddMember(members);
}
return members;
}
}
}
| 26.369565 | 94 | 0.628195 | [
"MIT"
] | Testura/Testura.Code | src/Testura.Code/Builders/BuilderHelpers/MemberHelper.cs | 1,215 | C# |
// Copyright (c) Stephan Tolksdorf 2007-2009
// License: Simplified BSD License. See accompanying documentation.
using System;
namespace FParsec {
public sealed class Position : IEquatable<Position>, IComparable, IComparable<Position> {
public long Index { get; private set; }
public long Line { get; private set; }
public long Column { get; private set; }
public string StreamName { get; private set; }
public Position(string streamName, long index, long line, long column) {
StreamName = streamName; Index = index; Line = line; Column = column;
}
public override string ToString() {
var ln = String.IsNullOrEmpty(StreamName) ? "(Ln: " : Text.Escape(StreamName, "", "(\"", "\", Ln: ", "", '"');
return ln + Line.ToString() + ", Col: " + Column.ToString() + ")";
}
public override bool Equals(object obj) {
return Equals(obj as Position);
}
public bool Equals(Position other) {
return (object)this == (object)other
|| ( (object)other != null
&& Index == other.Index
&& Line == other.Line
&& Column == other.Column
&& StreamName == other.StreamName);
}
public static bool operator==(Position left, Position right) {
return (object)left == null ? (object)right == null : left.Equals(right);
}
public static bool operator!=(Position left, Position right) { return !(left == right); }
public override int GetHashCode() {
return Index.GetHashCode();
}
public static int Compare(Position left, Position right) {
if ((object)left != null) return left.CompareTo(right);
return (object)right == null ? 0 : -1;
}
public int CompareTo(Position other) {
if ((object)this == (object)other) return 0;
if ((object)other == null) return 1;
int r = String.CompareOrdinal(StreamName, other.StreamName);
if (r != 0) return r;
r = Line.CompareTo(other.Line);
if (r != 0) return r;
r = Column.CompareTo(other.Column);
if (r != 0) return r;
return Index.CompareTo(other.Index);
}
int IComparable.CompareTo(object value) {
Position position = value as Position;
if ((object)position != null) return CompareTo(position);
if (value == null) return 1;
throw new ArgumentException("Object must be of type Position.");
}
}
}
| 36.661765 | 118 | 0.595267 | [
"MIT"
] | FoothillSolutions/Npgsql.FSharp.Analyzer | src/FParsecCS/Position.cs | 2,495 | C# |
namespace CameraBazaar.Web.ViewModels.Account
{
using System.Collections.Generic;
public class SendCodeViewModel
{
public string SelectedProvider { get; set; }
public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; }
public string ReturnUrl { get; set; }
public bool RememberMe { get; set; }
}
} | 30.083333 | 81 | 0.67313 | [
"MIT"
] | IvayloKodov/My-Projects | CameraBazaar/Web/CameraBazaar.Web/ViewModels/Account/SendCodeViewModel.cs | 361 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using CosmosDBStudio.Model.Services;
using CosmosDBStudio.Util.Extensions;
using CosmosDBStudio.ViewModel.Services;
using EssentialMVVM;
using Hamlet;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace CosmosDBStudio.ViewModel.Dialogs
{
public class DocumentEditorViewModel : DialogViewModelBase, ISizableDialog
{
private readonly IContainerContext _containerContext;
private readonly IDialogService _dialogService;
private readonly IUIDispatcher _uiDispatcher;
private readonly Timer _validateJsonTimer;
private JObject _document;
private bool _isNew;
private string _id;
private string? _eTag;
public DocumentEditorViewModel(
JObject document,
bool isNew,
IContainerContext containerContext,
IDialogService dialogService,
IUIDispatcher uiDispatcher)
{
_document = document;
_isNew = isNew;
_containerContext = containerContext;
_dialogService = dialogService;
_uiDispatcher = uiDispatcher;
_validateJsonTimer = new Timer(
state =>
{
var @this = ((DocumentEditorViewModel)state!);
@this._uiDispatcher.Invoke(() => @this.ValidateJson());
},
this,
Timeout.Infinite,
Timeout.Infinite);
if (_isNew)
{
Title = "New document";
}
else
{
Title = "Edit document";
}
_id = document["id"]!.Value<string>()!;
_eTag = document["_etag"]?.Value<string>();
_text = document.ToString(Formatting.Indented);
_isJsonValid = true;
base.AddButton(new DialogButton
{
Text = "Close",
Command = new DelegateCommand(() => Close(null)),
IsCancel = true
});
}
private string _text = string.Empty;
public string Text
{
get => _text;
set => Set(ref _text, value)
.AndExecute(InvalidateJson)
.AndRaiseCanExecuteChanged(_saveCommand);
}
private AsyncDelegateCommand<bool>? _saveCommand;
public ICommand SaveCommand => _saveCommand ??= new AsyncDelegateCommand<bool>(
SaveAsync,
_ => (_isNew || HasChanged) && IsJsonValid is true);
private bool? _isJsonValid;
public bool? IsJsonValid
{
get => _isJsonValid;
set => Set(ref _isJsonValid, value)
.AndNotifyPropertyChanged(nameof(IsError))
.AndRaiseCanExecuteChanged(_saveCommand);
}
private bool _hasChanged;
public bool HasChanged
{
get => _hasChanged;
set => Set(ref _hasChanged, value);
}
private void InvalidateJson()
{
IsJsonValid = null;
_validateJsonTimer.Change(500, Timeout.Infinite);
}
private void ValidateJson()
{
try
{
var newDoc = JObject.Parse(Text, new JsonLoadSettings
{
LineInfoHandling = LineInfoHandling.Load
});
HasChanged = _isNew || !JToken.DeepEquals(newDoc, _document);
IsJsonValid = true;
StatusText = null;
}
catch (JsonReaderException ex)
{
IsJsonValid = false;
StatusText = $"{ex.Message} at path '{ex.Path}' (line {ex.LineNumber}, position {ex.LinePosition})";
}
}
private string? _statusText;
public string? StatusText
{
get => _statusText;
set => Set(ref _statusText, value);
}
private bool _isError;
public bool IsError
{
get => _isError || (IsJsonValid is false);
set => Set(ref _isError, value);
}
private async Task SaveAsync(bool close)
{
var doc = JObject.Parse(Text);
var partitionKey =
_containerContext.PartitionKeyJsonPath is string jsonPath
? doc.ExtractScalar(jsonPath)
: Option.None();
try
{
JObject result;
if (_isNew)
{
result = await _containerContext.Documents.CreateAsync(
doc,
partitionKey,
default);
StatusText = "Successfully created";
}
else
{
result = await _containerContext.Documents.ReplaceAsync(
_id,
doc,
partitionKey,
_eTag,
default);
StatusText = "Successfully updated";
}
_id = result["id"]!.Value<string>()!;
_eTag = result["_etag"]?.Value<string?>();
_text = result.ToString(Formatting.Indented);
_isNew = false;
HasChanged = false;
_document = result;
IsError = false;
OnPropertyChanged(nameof(Text));
_saveCommand?.RaiseCanExecuteChanged();
if (close)
{
Close(true);
}
}
catch (Exception ex)
{
IsError = true;
StatusText = ex.Message;
}
}
public JObject? GetDocument() => _document;
private double _width = 500;
public double Width
{
get => _width;
set => Set(ref _width, value);
}
private double _height = 500;
public double Height
{
get => _height;
set => Set(ref _height, value);
}
public bool IsResizable => true;
public override void OnClosing(DialogClosingEventArgs args)
{
base.OnClosing(args);
if (HasChanged)
{
var result = _dialogService.YesNoCancel("Do you want to save the changes made to the document?");
if (result.TryGetValue(out bool save))
{
if (save)
{
args.Cancel = true;
_uiDispatcher.InvokeAsync(() =>
{
if (SaveCommand.CanExecute(true))
SaveCommand.Execute(true);
});
}
}
else
{
args.Cancel = true;
return;
}
}
}
public override void OnClosed(bool? result)
{
base.OnClosed(result);
_validateJsonTimer.Dispose();
}
}
}
| 30.122449 | 116 | 0.478997 | [
"MIT"
] | ricardopinedathen/CosmosDBStudio | src/CosmosDBStudio.ViewModel/Dialogs/DocumentEditorViewModel.cs | 7,382 | C# |
using Jint.Collections;
using Jint.Native.Array;
using Jint.Native.Object;
using Jint.Native.Symbol;
using Jint.Runtime;
using Jint.Runtime.Descriptors;
using Jint.Runtime.Interop;
namespace Jint.Native.Function
{
/// <summary>
/// https://tc39.es/ecma262/#sec-properties-of-the-function-prototype-object
/// </summary>
public sealed class FunctionPrototype : FunctionInstance
{
internal FunctionPrototype(
Engine engine,
Realm realm,
ObjectPrototype objectPrototype)
: base(engine, realm, JsString.Empty)
{
_prototype = objectPrototype;
_length = new PropertyDescriptor(JsNumber.PositiveZero, PropertyFlag.Configurable);
}
protected override void Initialize()
{
const PropertyFlag propertyFlags = PropertyFlag.Configurable | PropertyFlag.Writable;
const PropertyFlag lengthFlags = PropertyFlag.Configurable;
var properties = new PropertyDictionary(7, checkExistingKeys: false)
{
["constructor"] = new PropertyDescriptor(_realm.Intrinsics.Function, PropertyFlag.NonEnumerable),
["toString"] = new PropertyDescriptor(new ClrFunctionInstance(_engine, "toString", ToString, 0, lengthFlags), propertyFlags),
["apply"] = new PropertyDescriptor(new ClrFunctionInstance(_engine, "apply", Apply, 2, lengthFlags), propertyFlags),
["call"] = new PropertyDescriptor(new ClrFunctionInstance(_engine, "call", CallImpl, 1, lengthFlags), propertyFlags),
["bind"] = new PropertyDescriptor(new ClrFunctionInstance(_engine, "bind", Bind, 1, lengthFlags), propertyFlags),
["arguments"] = new GetSetPropertyDescriptor.ThrowerPropertyDescriptor(_engine, PropertyFlag.Configurable | PropertyFlag.CustomJsValue),
["caller"] = new GetSetPropertyDescriptor.ThrowerPropertyDescriptor(_engine, PropertyFlag.Configurable | PropertyFlag.CustomJsValue)
};
SetProperties(properties);
var symbols = new SymbolDictionary(1)
{
[GlobalSymbolRegistry.HasInstance] = new PropertyDescriptor(new ClrFunctionInstance(_engine, "[Symbol.hasInstance]", HasInstance, 1, PropertyFlag.Configurable), PropertyFlag.AllForbidden)
};
SetSymbols(symbols);
}
/// <summary>
/// https://tc39.es/ecma262/#sec-function.prototype-@@hasinstance
/// </summary>
private static JsValue HasInstance(JsValue thisObj, JsValue[] arguments)
{
return thisObj.OrdinaryHasInstance(arguments.At(0));
}
/// <summary>
/// https://tc39.es/ecma262/#sec-function.prototype.bind
/// </summary>
private JsValue Bind(JsValue thisObj, JsValue[] arguments)
{
if (thisObj is not ICallable)
{
ExceptionHelper.ThrowTypeError(_realm, "Bind must be called on a function");
}
var thisArg = arguments.At(0);
var f = BoundFunctionCreate((ObjectInstance) thisObj, thisArg, arguments.Skip(1));
JsNumber l;
var targetHasLength = thisObj.HasOwnProperty(CommonProperties.Length);
if (targetHasLength)
{
var targetLen = thisObj.Get(CommonProperties.Length);
if (targetLen is not JsNumber number)
{
l = JsNumber.PositiveZero;
}
else
{
if (number.IsPositiveInfinity())
{
l = number;
}
else if (number.IsNegativeInfinity())
{
l = JsNumber.PositiveZero;
}
else
{
var targetLenAsInt = (long) TypeConverter.ToIntegerOrInfinity(targetLen);
// first argument is target
var argumentsLength = System.Math.Max(0, arguments.Length - 1);
l = JsNumber.Create((ulong) System.Math.Max(targetLenAsInt - argumentsLength, 0));
}
}
}
else
{
l = JsNumber.PositiveZero;
}
f.DefinePropertyOrThrow(CommonProperties.Length, new PropertyDescriptor(l, PropertyFlag.Configurable));
var targetName = thisObj.Get(CommonProperties.Name);
if (!targetName.IsString())
{
targetName = JsString.Empty;
}
f.SetFunctionName(targetName, "bound");
return f;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-boundfunctioncreate
/// </summary>
private BindFunctionInstance BoundFunctionCreate(ObjectInstance targetFunction, JsValue boundThis, JsValue[] boundArgs)
{
var proto = targetFunction.GetPrototypeOf();
var obj = new BindFunctionInstance(_engine, _realm, proto, targetFunction, boundThis, boundArgs);
return obj;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-function.prototype.tostring
/// </summary>
private JsValue ToString(JsValue thisObj, JsValue[] arguments)
{
if (thisObj.IsObject() && thisObj.IsCallable)
{
return thisObj.ToString();
}
ExceptionHelper.ThrowTypeError(_realm, "Function.prototype.toString requires that 'this' be a Function");
return null;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-function.prototype.apply
/// </summary>
private JsValue Apply(JsValue thisObject, JsValue[] arguments)
{
var func = thisObject as ICallable;
if (func is null)
{
ExceptionHelper.ThrowTypeError(_realm);
}
var thisArg = arguments.At(0);
var argArray = arguments.At(1);
if (argArray.IsNullOrUndefined())
{
return func.Call(thisArg, Arguments.Empty);
}
var argList = CreateListFromArrayLike(_realm, argArray);
var result = func.Call(thisArg, argList);
return result;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-createlistfromarraylike
/// </summary>
internal static JsValue[] CreateListFromArrayLike(Realm realm, JsValue argArray, Types? elementTypes = null)
{
var argArrayObj = argArray as ObjectInstance;
if (argArrayObj is null)
{
ExceptionHelper.ThrowTypeError(realm);
}
var operations = ArrayOperations.For(argArrayObj);
var allowedTypes = elementTypes ??
Types.Undefined | Types.Null | Types.Boolean | Types.String | Types.Symbol | Types.Number | Types.Object;
var argList = operations.GetAll(allowedTypes);
return argList;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-function.prototype.call
/// </summary>
private JsValue CallImpl(JsValue thisObject, JsValue[] arguments)
{
var func = thisObject as ICallable;
if (func is null)
{
ExceptionHelper.ThrowTypeError(_realm);
}
JsValue[] values = System.Array.Empty<JsValue>();
if (arguments.Length > 1)
{
values = new JsValue[arguments.Length - 1];
System.Array.Copy(arguments, 1, values, 0, arguments.Length - 1);
}
var result = func.Call(arguments.At(0), values);
return result;
}
public override JsValue Call(JsValue thisObject, JsValue[] arguments)
{
return Undefined;
}
}
} | 38.414286 | 203 | 0.567621 | [
"BSD-2-Clause"
] | SebastianStehle/jint | Jint/Native/Function/FunctionPrototype.cs | 8,069 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the support-2013-04-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AWSSupport.Model
{
/// <summary>
/// Container for the parameters to the DescribeTrustedAdvisorCheckResult operation.
/// Returns the results of the AWS Trusted Advisor check that has the specified check
/// ID. You can get the check IDs by calling the <a>DescribeTrustedAdvisorChecks</a> operation.
///
///
/// <para>
/// The response contains a <a>TrustedAdvisorCheckResult</a> object, which contains these
/// three objects:
/// </para>
/// <ul> <li>
/// <para>
/// <a>TrustedAdvisorCategorySpecificSummary</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>TrustedAdvisorResourceDetail</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>TrustedAdvisorResourcesSummary</a>
/// </para>
/// </li> </ul>
/// <para>
/// In addition, the response contains these fields:
/// </para>
/// <ul> <li>
/// <para>
/// <b>status</b> - The alert status of the check: "ok" (green), "warning" (yellow),
/// "error" (red), or "not_available".
/// </para>
/// </li> <li>
/// <para>
/// <b>timestamp</b> - The time of the last refresh of the check.
/// </para>
/// </li> <li>
/// <para>
/// <b>checkId</b> - The unique identifier for the check.
/// </para>
/// </li> </ul> <note> <ul> <li>
/// <para>
/// You must have a Business or Enterprise support plan to use the AWS Support API.
/// </para>
/// </li> <li>
/// <para>
/// If you call the AWS Support API from an account that does not have a Business or Enterprise
/// support plan, the <code>SubscriptionRequiredException</code> error message appears.
/// For information about changing your support plan, see <a href="http://aws.amazon.com/premiumsupport/">AWS
/// Support</a>.
/// </para>
/// </li> </ul> </note>
/// </summary>
public partial class DescribeTrustedAdvisorCheckResultRequest : AmazonAWSSupportRequest
{
private string _checkId;
private string _language;
/// <summary>
/// Gets and sets the property CheckId.
/// <para>
/// The unique identifier for the Trusted Advisor check.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string CheckId
{
get { return this._checkId; }
set { this._checkId = value; }
}
// Check to see if CheckId property is set
internal bool IsSetCheckId()
{
return this._checkId != null;
}
/// <summary>
/// Gets and sets the property Language.
/// <para>
/// The ISO 639-1 code for the language in which AWS provides support. AWS Support currently
/// supports English ("en") and Japanese ("ja"). Language parameters must be passed explicitly
/// for operations that take them.
/// </para>
/// </summary>
public string Language
{
get { return this._language; }
set { this._language = value; }
}
// Check to see if Language property is set
internal bool IsSetLanguage()
{
return this._language != null;
}
}
} | 32.59375 | 113 | 0.591802 | [
"Apache-2.0"
] | KenHundley/aws-sdk-net | sdk/src/Services/AWSSupport/Generated/Model/DescribeTrustedAdvisorCheckResultRequest.cs | 4,172 | C# |
//---------------------------------------------------------------------------
//
// <copyright file="QuaternionAnimation.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Utility;
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using MS.Internal.PresentationCore;
namespace System.Windows.Media.Animation
{
/// <summary>
/// Animates the value of a Quaternion property using linear interpolation
/// between two values. The values are determined by the combination of
/// From, To, or By values that are set on the animation.
/// </summary>
public partial class QuaternionAnimation :
QuaternionAnimationBase
{
#region Data
/// <summary>
/// This is used if the user has specified From, To, and/or By values.
/// </summary>
private Quaternion[] _keyValues;
private AnimationType _animationType;
private bool _isAnimationFunctionValid;
#endregion
#region Constructors
/// <summary>
/// Static ctor for QuaternionAnimation establishes
/// dependency properties, using as much shared data as possible.
/// </summary>
static QuaternionAnimation()
{
Type typeofProp = typeof(Quaternion?);
Type typeofThis = typeof(QuaternionAnimation);
PropertyChangedCallback propCallback = new PropertyChangedCallback(AnimationFunction_Changed);
ValidateValueCallback validateCallback = new ValidateValueCallback(ValidateFromToOrByValue);
FromProperty = DependencyProperty.Register(
"From",
typeofProp,
typeofThis,
new PropertyMetadata((Quaternion?)null, propCallback),
validateCallback);
ToProperty = DependencyProperty.Register(
"To",
typeofProp,
typeofThis,
new PropertyMetadata((Quaternion?)null, propCallback),
validateCallback);
ByProperty = DependencyProperty.Register(
"By",
typeofProp,
typeofThis,
new PropertyMetadata((Quaternion?)null, propCallback),
validateCallback);
EasingFunctionProperty = DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeofThis);
}
/// <summary>
/// Creates a new QuaternionAnimation with all properties set to
/// their default values.
/// </summary>
public QuaternionAnimation()
: base()
{
}
/// <summary>
/// Creates a new QuaternionAnimation that will animate a
/// Quaternion property from its base value to the value specified
/// by the "toValue" parameter of this constructor.
/// </summary>
public QuaternionAnimation(Quaternion toValue, Duration duration)
: this()
{
To = toValue;
Duration = duration;
}
/// <summary>
/// Creates a new QuaternionAnimation that will animate a
/// Quaternion property from its base value to the value specified
/// by the "toValue" parameter of this constructor.
/// </summary>
public QuaternionAnimation(Quaternion toValue, Duration duration, FillBehavior fillBehavior)
: this()
{
To = toValue;
Duration = duration;
FillBehavior = fillBehavior;
}
/// <summary>
/// Creates a new QuaternionAnimation that will animate a
/// Quaternion property from the "fromValue" parameter of this constructor
/// to the "toValue" parameter.
/// </summary>
public QuaternionAnimation(Quaternion fromValue, Quaternion toValue, Duration duration)
: this()
{
From = fromValue;
To = toValue;
Duration = duration;
}
/// <summary>
/// Creates a new QuaternionAnimation that will animate a
/// Quaternion property from the "fromValue" parameter of this constructor
/// to the "toValue" parameter.
/// </summary>
public QuaternionAnimation(Quaternion fromValue, Quaternion toValue, Duration duration, FillBehavior fillBehavior)
: this()
{
From = fromValue;
To = toValue;
Duration = duration;
FillBehavior = fillBehavior;
}
#endregion
#region Freezable
/// <summary>
/// Creates a copy of this QuaternionAnimation
/// </summary>
/// <returns>The copy</returns>
public new QuaternionAnimation Clone()
{
return (QuaternionAnimation)base.Clone();
}
//
// Note that we don't override the Clone virtuals (CloneCore, CloneCurrentValueCore,
// GetAsFrozenCore, and GetCurrentValueAsFrozenCore) even though this class has state
// not stored in a DP.
//
// We don't need to clone _animationType and _keyValues because they are the the cached
// results of animation function validation, which can be recomputed. The other remaining
// field, isAnimationFunctionValid, defaults to false, which causes this recomputation to happen.
//
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new QuaternionAnimation();
}
#endregion
#region Methods
/// <summary>
/// Calculates the value this animation believes should be the current value for the property.
/// </summary>
/// <param name="defaultOriginValue">
/// This value is the suggested origin value provided to the animation
/// to be used if the animation does not have its own concept of a
/// start value. If this animation is the first in a composition chain
/// this value will be the snapshot value if one is available or the
/// base property value if it is not; otherise this value will be the
/// value returned by the previous animation in the chain with an
/// animationClock that is not Stopped.
/// </param>
/// <param name="defaultDestinationValue">
/// This value is the suggested destination value provided to the animation
/// to be used if the animation does not have its own concept of an
/// end value. This value will be the base value if the animation is
/// in the first composition layer of animations on a property;
/// otherwise this value will be the output value from the previous
/// composition layer of animations for the property.
/// </param>
/// <param name="animationClock">
/// This is the animationClock which can generate the CurrentTime or
/// CurrentProgress value to be used by the animation to generate its
/// output value.
/// </param>
/// <returns>
/// The value this animation believes should be the current value for the property.
/// </returns>
protected override Quaternion GetCurrentValueCore(Quaternion defaultOriginValue, Quaternion defaultDestinationValue, AnimationClock animationClock)
{
Debug.Assert(animationClock.CurrentState != ClockState.Stopped);
if (!_isAnimationFunctionValid)
{
ValidateAnimationFunction();
}
double progress = animationClock.CurrentProgress.Value;
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
progress = easingFunction.Ease(progress);
}
Quaternion from = Quaternion.Identity;
Quaternion to = Quaternion.Identity;
Quaternion accumulated = Quaternion.Identity;
Quaternion foundation = Quaternion.Identity;
// need to validate the default origin and destination values if
// the animation uses them as the from, to, or foundation values
bool validateOrigin = false;
bool validateDestination = false;
switch(_animationType)
{
case AnimationType.Automatic:
from = defaultOriginValue;
to = defaultDestinationValue;
validateOrigin = true;
validateDestination = true;
break;
case AnimationType.From:
from = _keyValues[0];
to = defaultDestinationValue;
validateDestination = true;
break;
case AnimationType.To:
from = defaultOriginValue;
to = _keyValues[0];
validateOrigin = true;
break;
case AnimationType.By:
// According to the SMIL specification, a By animation is
// always additive. But we don't force this so that a
// user can re-use a By animation and have it replace the
// animations that precede it in the list without having
// to manually set the From value to the base value.
to = _keyValues[0];
foundation = defaultOriginValue;
validateOrigin = true;
break;
case AnimationType.FromTo:
from = _keyValues[0];
to = _keyValues[1];
if (IsAdditive)
{
foundation = defaultOriginValue;
validateOrigin = true;
}
break;
case AnimationType.FromBy:
from = _keyValues[0];
to = AnimatedTypeHelpers.AddQuaternion(_keyValues[0], _keyValues[1]);
if (IsAdditive)
{
foundation = defaultOriginValue;
validateOrigin = true;
}
break;
default:
Debug.Fail("Unknown animation type.");
break;
}
if (validateOrigin
&& !AnimatedTypeHelpers.IsValidAnimationValueQuaternion(defaultOriginValue))
{
throw new InvalidOperationException(
SR.Get(
SRID.Animation_Invalid_DefaultValue,
this.GetType(),
"origin",
defaultOriginValue.ToString(CultureInfo.InvariantCulture)));
}
if (validateDestination
&& !AnimatedTypeHelpers.IsValidAnimationValueQuaternion(defaultDestinationValue))
{
throw new InvalidOperationException(
SR.Get(
SRID.Animation_Invalid_DefaultValue,
this.GetType(),
"destination",
defaultDestinationValue.ToString(CultureInfo.InvariantCulture)));
}
if (IsCumulative)
{
double currentRepeat = (double)(animationClock.CurrentIteration - 1);
if (currentRepeat > 0.0)
{
Quaternion accumulator = AnimatedTypeHelpers.SubtractQuaternion(to, from);
accumulated = AnimatedTypeHelpers.ScaleQuaternion(accumulator, currentRepeat);
}
}
// return foundation + accumulated + from + ((to - from) * progress)
return AnimatedTypeHelpers.AddQuaternion(
foundation,
AnimatedTypeHelpers.AddQuaternion(
accumulated,
AnimatedTypeHelpers.InterpolateQuaternion(from, to, progress, UseShortestPath)));
}
private void ValidateAnimationFunction()
{
_animationType = AnimationType.Automatic;
_keyValues = null;
if (From.HasValue)
{
if (To.HasValue)
{
_animationType = AnimationType.FromTo;
_keyValues = new Quaternion[2];
_keyValues[0] = From.Value;
_keyValues[1] = To.Value;
}
else if (By.HasValue)
{
_animationType = AnimationType.FromBy;
_keyValues = new Quaternion[2];
_keyValues[0] = From.Value;
_keyValues[1] = By.Value;
}
else
{
_animationType = AnimationType.From;
_keyValues = new Quaternion[1];
_keyValues[0] = From.Value;
}
}
else if (To.HasValue)
{
_animationType = AnimationType.To;
_keyValues = new Quaternion[1];
_keyValues[0] = To.Value;
}
else if (By.HasValue)
{
_animationType = AnimationType.By;
_keyValues = new Quaternion[1];
_keyValues[0] = By.Value;
}
_isAnimationFunctionValid = true;
}
#endregion
#region Properties
private static void AnimationFunction_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
QuaternionAnimation a = (QuaternionAnimation)d;
a._isAnimationFunctionValid = false;
a.PropertyChanged(e.Property);
}
private static bool ValidateFromToOrByValue(object value)
{
Quaternion? typedValue = (Quaternion?)value;
if (typedValue.HasValue)
{
return AnimatedTypeHelpers.IsValidAnimationValueQuaternion(typedValue.Value);
}
else
{
return true;
}
}
/// <summary>
/// FromProperty
/// </summary>
public static readonly DependencyProperty FromProperty;
/// <summary>
/// From
/// </summary>
public Quaternion? From
{
get
{
return (Quaternion?)GetValue(FromProperty);
}
set
{
SetValueInternal(FromProperty, value);
}
}
/// <summary>
/// ToProperty
/// </summary>
public static readonly DependencyProperty ToProperty;
/// <summary>
/// To
/// </summary>
public Quaternion? To
{
get
{
return (Quaternion?)GetValue(ToProperty);
}
set
{
SetValueInternal(ToProperty, value);
}
}
/// <summary>
/// ByProperty
/// </summary>
public static readonly DependencyProperty ByProperty;
/// <summary>
/// By
/// </summary>
public Quaternion? By
{
get
{
return (Quaternion?)GetValue(ByProperty);
}
set
{
SetValueInternal(ByProperty, value);
}
}
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty;
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
/// <summary>
/// If this property is set to true the animation will add its value to
/// the base value instead of replacing it entirely.
/// </summary>
public bool IsAdditive
{
get
{
return (bool)GetValue(IsAdditiveProperty);
}
set
{
SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value));
}
}
/// <summary>
/// It this property is set to true, the animation will accumulate its
/// value over repeats. For instance if you have a From value of 0.0 and
/// a To value of 1.0, the animation return values from 1.0 to 2.0 over
/// the second reteat cycle, and 2.0 to 3.0 over the third, etc.
/// </summary>
public bool IsCumulative
{
get
{
return (bool)GetValue(IsCumulativeProperty);
}
set
{
SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value));
}
}
#endregion
}
}
| 33.104505 | 155 | 0.528384 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/wpf/src/Core/CSharp/System/Windows/Media/Animation/Generated/QuaternionAnimation.cs | 18,373 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure.Internal;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Microsoft.EntityFrameworkCore.Infrastructure
{
public class InternalServiceCollectionMapTest
{
[ConditionalFact]
public void Can_patch_transient_service_with_concrete_implementation()
{
var serviceMap = CreateServiceMap();
serviceMap.TryAddTransient<IFakeService, FakeService>();
((InternalServiceCollectionMap)serviceMap.GetInfrastructure()).DoPatchInjection<IFakeService>();
Can_patch_transient_service(serviceMap);
}
[ConditionalFact]
public void Can_patch_transient_service_with_delegate_implementation()
{
var serviceMap = CreateServiceMap();
serviceMap.TryAddTransient<IFakeService, FakeService>(p => new FakeService());
((InternalServiceCollectionMap)serviceMap.GetInfrastructure()).DoPatchInjection<IFakeService>();
Can_patch_transient_service(serviceMap);
}
[ConditionalFact]
public void Can_patch_transient_service_with_service_typed_delegate_implementation()
{
var serviceMap = CreateServiceMap();
serviceMap.TryAddTransient<IFakeService>(p => new FakeService());
((InternalServiceCollectionMap)serviceMap.GetInfrastructure()).DoPatchInjection<IFakeService>();
Can_patch_transient_service(serviceMap);
}
[ConditionalFact]
public void Can_patch_transient_service_with_untyped_delegate_implementation()
{
var serviceMap = CreateServiceMap();
serviceMap.TryAddTransient(typeof(IFakeService), p => new FakeService());
((InternalServiceCollectionMap)serviceMap.GetInfrastructure()).DoPatchInjection<IFakeService>();
Can_patch_transient_service(serviceMap);
}
[ConditionalFact]
public void Can_patch_transient_service_with_concrete_implementation_already_registered()
{
var serviceMap = CreateServiceMap();
serviceMap.TryAddTransient<FakeService, DerivedFakeService>();
serviceMap.TryAddTransient<IFakeService, FakeService>();
((InternalServiceCollectionMap)serviceMap.GetInfrastructure()).DoPatchInjection<IFakeService>();
Assert.IsType<DerivedFakeService>(Can_patch_transient_service(serviceMap));
}
private static FakeService Can_patch_transient_service(ServiceCollectionMap serviceMap)
{
var serviceProvider = serviceMap.ServiceCollection.BuildServiceProvider();
FakeService service;
using (var context = CreateContext(serviceProvider))
{
service = (FakeService)context.GetService<IFakeService>();
Assert.Same(context, service.Context);
Assert.NotSame(service, context.GetService<IFakeService>());
}
using (var context = CreateContext(serviceProvider))
{
Assert.Same(context, ((FakeService)context.GetService<IFakeService>()).Context);
Assert.NotSame(service, context.GetService<IFakeService>());
}
return service;
}
[ConditionalFact]
public void Can_patch_scoped_service_with_concrete_implementation()
{
var serviceMap = CreateServiceMap();
serviceMap.TryAddScoped<IFakeService, FakeService>();
((InternalServiceCollectionMap)serviceMap.GetInfrastructure()).DoPatchInjection<IFakeService>();
Can_patch_scoped_service(serviceMap);
}
[ConditionalFact]
public void Can_patch_scoped_service_with_delegate_implementation()
{
var serviceMap = CreateServiceMap();
serviceMap.TryAddScoped<IFakeService, FakeService>(p => new FakeService());
((InternalServiceCollectionMap)serviceMap.GetInfrastructure()).DoPatchInjection<IFakeService>();
Can_patch_scoped_service(serviceMap);
}
[ConditionalFact]
public void Can_patch_scoped_service_with_service_typed_delegate_implementation()
{
var serviceMap = CreateServiceMap();
serviceMap.TryAddScoped<IFakeService>(p => new FakeService());
((InternalServiceCollectionMap)serviceMap.GetInfrastructure()).DoPatchInjection<IFakeService>();
Can_patch_scoped_service(serviceMap);
}
[ConditionalFact]
public void Can_patch_scoped_service_with_untyped_delegate_implementation()
{
var serviceMap = CreateServiceMap();
serviceMap.TryAddScoped(typeof(IFakeService), p => new FakeService());
((InternalServiceCollectionMap)serviceMap.GetInfrastructure()).DoPatchInjection<IFakeService>();
Can_patch_scoped_service(serviceMap);
}
[ConditionalFact]
public void Can_patch_scoped_service_with_concrete_implementation_already_registered()
{
var serviceMap = CreateServiceMap();
serviceMap.TryAddScoped<FakeService, DerivedFakeService>();
serviceMap.TryAddScoped<IFakeService, FakeService>();
((InternalServiceCollectionMap)serviceMap.GetInfrastructure()).DoPatchInjection<IFakeService>();
Assert.IsType<DerivedFakeService>(Can_patch_scoped_service(serviceMap));
}
private static FakeService Can_patch_scoped_service(ServiceCollectionMap serviceMap)
{
var serviceProvider = serviceMap.ServiceCollection.BuildServiceProvider();
FakeService service;
using (var context = CreateContext(serviceProvider))
{
service = (FakeService)context.GetService<IFakeService>();
Assert.Same(context, service.Context);
Assert.Same(service, context.GetService<IFakeService>());
}
using (var context = CreateContext(serviceProvider))
{
Assert.Same(context, ((FakeService)context.GetService<IFakeService>()).Context);
Assert.NotSame(service, context.GetService<IFakeService>());
}
return service;
}
[ConditionalFact]
public void Can_patch_singleton_service_with_concrete_implementation()
{
var serviceMap = CreateServiceMap();
serviceMap.TryAddSingleton<IFakeSingletonService, FakeSingletonService>();
((InternalServiceCollectionMap)serviceMap.GetInfrastructure()).DoPatchInjection<IFakeSingletonService>();
Can_patch_singleton_service(serviceMap);
}
[ConditionalFact]
public void Can_patch_singleton_service_with_delegate_implementation()
{
var serviceMap = CreateServiceMap();
serviceMap.TryAddSingleton<IFakeSingletonService, FakeSingletonService>(p => new FakeSingletonService());
((InternalServiceCollectionMap)serviceMap.GetInfrastructure()).DoPatchInjection<IFakeSingletonService>();
Can_patch_singleton_service(serviceMap);
}
[ConditionalFact]
public void Can_patch_singleton_service_with_service_typed_delegate_implementation()
{
var serviceMap = CreateServiceMap();
serviceMap.TryAddSingleton<IFakeSingletonService>(p => new FakeSingletonService());
((InternalServiceCollectionMap)serviceMap.GetInfrastructure()).DoPatchInjection<IFakeSingletonService>();
Can_patch_singleton_service(serviceMap);
}
[ConditionalFact]
public void Can_patch_singleton_service_with_untyped_delegate_implementation()
{
var serviceMap = CreateServiceMap();
serviceMap.TryAddSingleton(typeof(IFakeSingletonService), p => new FakeSingletonService());
((InternalServiceCollectionMap)serviceMap.GetInfrastructure()).DoPatchInjection<IFakeSingletonService>();
Can_patch_singleton_service(serviceMap);
}
[ConditionalFact]
public void Can_patch_singleton_service_with_concrete_implementation_already_registered()
{
var serviceMap = CreateServiceMap();
serviceMap.TryAddSingleton<FakeSingletonService, DerivedFakeSingletonService>();
serviceMap.TryAddSingleton<IFakeSingletonService, FakeSingletonService>();
((InternalServiceCollectionMap)serviceMap.GetInfrastructure()).DoPatchInjection<IFakeSingletonService>();
Assert.IsType<DerivedFakeSingletonService>(Can_patch_singleton_service(serviceMap));
}
[ConditionalFact]
public void Can_patch_singleton_service_with_instance_registered()
{
var serviceMap = CreateServiceMap();
serviceMap.TryAddSingleton<IFakeSingletonService>(new DerivedFakeSingletonService());
((InternalServiceCollectionMap)serviceMap.GetInfrastructure()).DoPatchInjection<IFakeSingletonService>();
Assert.IsType<DerivedFakeSingletonService>(Can_patch_singleton_service(serviceMap));
}
[ConditionalFact]
public void Can_patch_singleton_service_with_instance_registered_non_generic()
{
var serviceMap = CreateServiceMap();
serviceMap.TryAddSingleton(typeof(IFakeSingletonService), new DerivedFakeSingletonService());
((InternalServiceCollectionMap)serviceMap.GetInfrastructure()).DoPatchInjection<IFakeSingletonService>();
Assert.IsType<DerivedFakeSingletonService>(Can_patch_singleton_service(serviceMap));
}
private static FakeSingletonService Can_patch_singleton_service(ServiceCollectionMap serviceMap)
{
var serviceProvider = serviceMap.ServiceCollection.BuildServiceProvider();
FakeSingletonService singletonService;
using (var context = CreateContext(serviceProvider))
{
singletonService = (FakeSingletonService)context.GetService<IFakeSingletonService>();
Assert.Same(context.GetService<IModelSource>(), singletonService.ModelSource);
Assert.Same(singletonService, context.GetService<IFakeSingletonService>());
}
using (var context = CreateContext(serviceProvider))
{
Assert.Same(singletonService, context.GetService<IFakeSingletonService>());
}
return singletonService;
}
[ConditionalFact]
public void Throws_if_attempt_is_made_to_register_dependency_as_delegate()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<DatabaseProviderDependencies>(p => null);
var builder = new EntityFrameworkServicesBuilder(serviceCollection);
Assert.Equal(
CoreStrings.BadDependencyRegistration(nameof(DatabaseProviderDependencies)),
Assert.Throws<InvalidOperationException>(
() => builder.TryAddCoreServices())
.Message);
}
[ConditionalFact]
public void Throws_if_attempt_is_made_to_register_dependency_as_instance()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(new DatabaseProviderDependencies());
var builder = new EntityFrameworkServicesBuilder(serviceCollection);
Assert.Equal(
CoreStrings.BadDependencyRegistration(nameof(DatabaseProviderDependencies)),
Assert.Throws<InvalidOperationException>(
() => builder.TryAddCoreServices())
.Message);
}
private static ServiceCollectionMap CreateServiceMap()
=> new(new ServiceCollection().AddEntityFrameworkInMemoryDatabase());
private static DbContext CreateContext(IServiceProvider serviceProvider)
=> new(
new DbContextOptionsBuilder()
.UseInternalServiceProvider(serviceProvider)
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options);
private interface IFakeService
{
}
private class FakeService : IFakeService, IPatchServiceInjectionSite
{
public DbContext Context { get; private set; }
void IPatchServiceInjectionSite.InjectServices(IServiceProvider serviceProvider)
=> Context = serviceProvider.GetService<ICurrentDbContext>().Context;
}
private class DerivedFakeService : FakeService
{
}
private interface IFakeSingletonService
{
}
private class FakeSingletonService : IFakeSingletonService, IPatchServiceInjectionSite
{
public IModelSource ModelSource { get; private set; }
void IPatchServiceInjectionSite.InjectServices(IServiceProvider serviceProvider)
=> ModelSource = serviceProvider.GetService<IModelSource>();
}
private class DerivedFakeSingletonService : FakeSingletonService
{
}
}
}
| 39.625 | 117 | 0.676473 | [
"Apache-2.0"
] | 0x0309/efcore | test/EFCore.Tests/Infrastructure/InternalServiceCollectionMapTest.cs | 13,631 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан по шаблону.
//
// Изменения, вносимые в этот файл вручную, могут привести к непредвиденной работе приложения.
// Изменения, вносимые в этот файл вручную, будут перезаписаны при повторном создании кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Farming.WpfClient.Models
{
using System;
using System.Collections.Generic;
public partial class BloodType
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public BloodType()
{
this.Cows = new HashSet<Cow>();
}
public int Id { get; set; }
public string Name { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Cow> Cows { get; set; }
}
}
| 35.8 | 128 | 0.571695 | [
"MIT"
] | holydk/Farming | Farming/Farming.WpfClient/Models/BloodType.cs | 1,247 | C# |
using JetBrains.Annotations;
using Microsoft.Win32.TaskScheduler.V1Interop;
using Microsoft.Win32.TaskScheduler.V2Interop;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using IPrincipal = Microsoft.Win32.TaskScheduler.V2Interop.IPrincipal;
// ReSharper disable UnusedMember.Global
// ReSharper disable InconsistentNaming ReSharper disable SuspiciousTypeConversion.Global
namespace Microsoft.Win32.TaskScheduler
{
/// <summary>Defines what versions of Task Scheduler or the AT command that the task is compatible with.</summary>
public enum TaskCompatibility
{
/// <summary>The task is compatible with the AT command.</summary>
AT,
/// <summary>The task is compatible with Task Scheduler 1.0 (Windows Server™ 2003, Windows® XP, or Windows® 2000).</summary>
/// <remarks>
/// Items not available when compared to V2:
/// <list type="bullet">
/// <item>
/// <term>TaskDefinition.Principal.GroupId - All account information can be retrieved via the UserId property.</term>
/// </item>
/// <item>
/// <term>TaskLogonType values Group, None and S4U are not supported.</term>
/// </item>
/// <item>
/// <term>TaskDefinition.Principal.RunLevel == TaskRunLevel.Highest is not supported.</term>
/// </item>
/// <item>
/// <term>Assigning access security to a task is not supported using TaskDefinition.RegistrationInfo.SecurityDescriptorSddlForm or in RegisterTaskDefinition.</term>
/// </item>
/// <item>
/// <term>
/// TaskDefinition.RegistrationInfo.Documentation, Source, URI and Version properties are only supported using this library. See details in the remarks
/// for <see cref="TaskDefinition.Data"/>.
/// </term>
/// </item>
/// <item>
/// <term>TaskDefinition.Settings.AllowDemandStart cannot be false.</term>
/// </item>
/// <item>
/// <term>TaskDefinition.Settings.AllowHardTerminate cannot be false.</term>
/// </item>
/// <item>
/// <term>TaskDefinition.Settings.MultipleInstances can only be IgnoreNew.</term>
/// </item>
/// <item>
/// <term>TaskDefinition.Settings.NetworkSettings cannot have any values.</term>
/// </item>
/// <item>
/// <term>TaskDefinition.Settings.RestartCount can only be 0.</term>
/// </item>
/// <item>
/// <term>TaskDefinition.Settings.StartWhenAvailable can only be false.</term>
/// </item>
/// <item>
/// <term>
/// TaskDefinition.Actions can only contain ExecAction instances unless the TaskDefinition.Actions.PowerShellConversion property has the Version1 flag set.
/// </term>
/// </item>
/// <item>
/// <term>TaskDefinition.Triggers cannot contain CustomTrigger, EventTrigger, SessionStateChangeTrigger, or RegistrationTrigger instances.</term>
/// </item>
/// <item>
/// <term>TaskDefinition.Triggers cannot contain instances with delays set.</term>
/// </item>
/// <item>
/// <term>TaskDefinition.Triggers cannot contain instances with ExecutionTimeLimit or Id properties set.</term>
/// </item>
/// <item>
/// <term>TaskDefinition.Triggers cannot contain LogonTriggers instances with the UserId property set.</term>
/// </item>
/// <item>
/// <term>TaskDefinition.Triggers cannot contain MonthlyDOWTrigger instances with the RunOnLastWeekOfMonth property set to <c>true</c>.</term>
/// </item>
/// <item>
/// <term>TaskDefinition.Triggers cannot contain MonthlyTrigger instances with the RunOnDayWeekOfMonth property set to <c>true</c>.</term>
/// </item>
/// </list>
/// </remarks>
V1,
/// <summary>The task is compatible with Task Scheduler 2.0 (Windows Vista™, Windows Server™ 2008).</summary>
/// <remarks>
/// This version is the baseline for the new, non-file based Task Scheduler. See <see cref="TaskCompatibility.V1"/> remarks for functionality that was
/// not forward-compatible.
/// </remarks>
V2,
/// <summary>The task is compatible with Task Scheduler 2.1 (Windows® 7, Windows Server™ 2008 R2).</summary>
/// <remarks>
/// Changes from V2:
/// <list type="bullet">
/// <item>
/// <term>TaskDefinition.Principal.ProcessTokenSidType can be defined as a value other than Default.</term>
/// </item>
/// <item>
/// <term>
/// TaskDefinition.Actions may not contain EmailAction or ShowMessageAction instances unless the TaskDefinition.Actions.PowerShellConversion property has
/// the Version2 flag set.
/// </term>
/// </item>
/// <item>
/// <term>TaskDefinition.Principal.RequiredPrivileges can have privilege values assigned.</term>
/// </item>
/// <item>
/// <term>TaskDefinition.Settings.DisallowStartOnRemoteAppSession can be set to true.</term>
/// </item>
/// <item>
/// <term>TaskDefinition.UseUnifiedSchedulingEngine can be set to true.</term>
/// </item>
/// </list>
/// </remarks>
V2_1,
/// <summary>The task is compatible with Task Scheduler 2.2 (Windows® 8.x, Windows Server™ 2012).</summary>
/// <remarks>
/// Changes from V2_1:
/// <list type="bullet">
/// <item>
/// <term>
/// TaskDefinition.Settings.MaintenanceSettings can have Period or Deadline be values other than TimeSpan.Zero or the Exclusive property set to true.
/// </term>
/// </item>
/// <item>
/// <term>TaskDefinition.Settings.Volatile can be set to true.</term>
/// </item>
/// </list>
/// </remarks>
V2_2,
/// <summary>The task is compatible with Task Scheduler 2.3 (Windows® 10, Windows Server™ 2016).</summary>
/// <remarks>
/// Changes from V2_2:
/// <list type="bullet">
/// <item>
/// <term>None published.</term>
/// </item>
/// </list>
/// </remarks>
V2_3
}
/// <summary>Defines how the Task Scheduler service creates, updates, or disables the task.</summary>
[DefaultValue(CreateOrUpdate)]
public enum TaskCreation
{
/// <summary>The Task Scheduler service registers the task as a new task.</summary>
Create = 2,
/// <summary>
/// The Task Scheduler service either registers the task as a new task or as an updated version if the task already exists. Equivalent to Create | Update.
/// </summary>
CreateOrUpdate = 6,
/// <summary>
/// The Task Scheduler service registers the disabled task. A disabled task cannot run until it is enabled. For more information, see Enabled Property of
/// TaskSettings and Enabled Property of RegisteredTask.
/// </summary>
Disable = 8,
/// <summary>
/// The Task Scheduler service is prevented from adding the allow access-control entry (ACE) for the context principal. When the
/// TaskFolder.RegisterTaskDefinition or TaskFolder.RegisterTask functions are called with this flag to update a task, the Task Scheduler service does
/// not add the ACE for the new context principal and does not remove the ACE from the old context principal.
/// </summary>
DontAddPrincipalAce = 0x10,
/// <summary>
/// The Task Scheduler service creates the task, but ignores the registration triggers in the task. By ignoring the registration triggers, the task will
/// not execute when it is registered unless a time-based trigger causes it to execute on registration.
/// </summary>
IgnoreRegistrationTriggers = 0x20,
/// <summary>
/// The Task Scheduler service registers the task as an updated version of an existing task. When a task with a registration trigger is updated, the task
/// will execute after the update occurs.
/// </summary>
Update = 4,
/// <summary>
/// The Task Scheduler service checks the syntax of the XML that describes the task but does not register the task. This constant cannot be combined with
/// the Create, Update, or CreateOrUpdate values.
/// </summary>
ValidateOnly = 1
}
/// <summary>Defines how the Task Scheduler handles existing instances of the task when it starts a new instance of the task.</summary>
[DefaultValue(IgnoreNew)]
public enum TaskInstancesPolicy
{
/// <summary>Starts new instance while an existing instance is running.</summary>
Parallel,
/// <summary>Starts a new instance of the task after all other instances of the task are complete.</summary>
Queue,
/// <summary>Does not start a new instance if an existing instance of the task is running.</summary>
IgnoreNew,
/// <summary>Stops an existing instance of the task before it starts a new instance.</summary>
StopExisting
}
/// <summary>Defines what logon technique is required to run a task.</summary>
[DefaultValue(S4U)]
public enum TaskLogonType
{
/// <summary>The logon method is not specified. Used for non-NT credentials.</summary>
None,
/// <summary>Use a password for logging on the user. The password must be supplied at registration time.</summary>
Password,
/// <summary>
/// Use an existing interactive token to run a task. The user must log on using a service for user (S4U) logon. When an S4U logon is used, no password is
/// stored by the system and there is no access to either the network or to encrypted files.
/// </summary>
S4U,
/// <summary>User must already be logged on. The task will be run only in an existing interactive session.</summary>
InteractiveToken,
/// <summary>Group activation. The groupId field specifies the group.</summary>
Group,
/// <summary>Indicates that a Local System, Local Service, or Network Service account is being used as a security context to run the task.</summary>
ServiceAccount,
/// <summary>
/// First use the interactive token. If the user is not logged on (no interactive token is available), then the password is used. The password must be
/// specified when a task is registered. This flag is not recommended for new tasks because it is less reliable than Password.
/// </summary>
InteractiveTokenOrPassword
}
/// <summary>Defines which privileges must be required for a secured task.</summary>
public enum TaskPrincipalPrivilege
{
/// <summary>Required to create a primary token. User Right: Create a token object.</summary>
SeCreateTokenPrivilege = 1,
/// <summary>Required to assign the primary token of a process. User Right: Replace a process-level token.</summary>
SeAssignPrimaryTokenPrivilege,
/// <summary>Required to lock physical pages in memory. User Right: Lock pages in memory.</summary>
SeLockMemoryPrivilege,
/// <summary>Required to increase the quota assigned to a process. User Right: Adjust memory quotas for a process.</summary>
SeIncreaseQuotaPrivilege,
/// <summary>Required to read unsolicited input from a terminal device. User Right: Not applicable.</summary>
SeUnsolicitedInputPrivilege,
/// <summary>Required to create a computer account. User Right: Add workstations to domain.</summary>
SeMachineAccountPrivilege,
/// <summary>
/// This privilege identifies its holder as part of the trusted computer base. Some trusted protected subsystems are granted this privilege. User Right:
/// Act as part of the operating system.
/// </summary>
SeTcbPrivilege,
/// <summary>
/// Required to perform a number of security-related functions, such as controlling and viewing audit messages. This privilege identifies its holder as a
/// security operator. User Right: Manage auditing and the security log.
/// </summary>
SeSecurityPrivilege,
/// <summary>
/// Required to take ownership of an object without being granted discretionary access. This privilege allows the owner value to be set only to those
/// values that the holder may legitimately assign as the owner of an object. User Right: Take ownership of files or other objects.
/// </summary>
SeTakeOwnershipPrivilege,
/// <summary>Required to load or unload a device driver. User Right: Load and unload device drivers.</summary>
SeLoadDriverPrivilege,
/// <summary>Required to gather profiling information for the entire system. User Right: Profile system performance.</summary>
SeSystemProfilePrivilege,
/// <summary>Required to modify the system time. User Right: Change the system time.</summary>
SeSystemtimePrivilege,
/// <summary>Required to gather profiling information for a single process. User Right: Profile single process.</summary>
SeProfileSingleProcessPrivilege,
/// <summary>Required to increase the base priority of a process. User Right: Increase scheduling priority.</summary>
SeIncreaseBasePriorityPrivilege,
/// <summary>Required to create a paging file. User Right: Create a pagefile.</summary>
SeCreatePagefilePrivilege,
/// <summary>Required to create a permanent object. User Right: Create permanent shared objects.</summary>
SeCreatePermanentPrivilege,
/// <summary>
/// Required to perform backup operations. This privilege causes the system to grant all read access control to any file, regardless of the access
/// control list (ACL) specified for the file. Any access request other than read is still evaluated with the ACL. This privilege is required by the
/// RegSaveKey and RegSaveKeyExfunctions. The following access rights are granted if this privilege is held: READ_CONTROL, ACCESS_SYSTEM_SECURITY,
/// FILE_GENERIC_READ, FILE_TRAVERSE. User Right: Back up files and directories.
/// </summary>
SeBackupPrivilege,
/// <summary>
/// Required to perform restore operations. This privilege causes the system to grant all write access control to any file, regardless of the ACL
/// specified for the file. Any access request other than write is still evaluated with the ACL. Additionally, this privilege enables you to set any
/// valid user or group security identifier (SID) as the owner of a file. This privilege is required by the RegLoadKey function. The following access
/// rights are granted if this privilege is held: WRITE_DAC, WRITE_OWNER, ACCESS_SYSTEM_SECURITY, FILE_GENERIC_WRITE, FILE_ADD_FILE,
/// FILE_ADD_SUBDIRECTORY, DELETE. User Right: Restore files and directories.
/// </summary>
SeRestorePrivilege,
/// <summary>Required to shut down a local system. User Right: Shut down the system.</summary>
SeShutdownPrivilege,
/// <summary>Required to debug and adjust the memory of a process owned by another account. User Right: Debug programs.</summary>
SeDebugPrivilege,
/// <summary>Required to generate audit-log entries. Give this privilege to secure servers. User Right: Generate security audits.</summary>
SeAuditPrivilege,
/// <summary>
/// Required to modify the nonvolatile RAM of systems that use this type of memory to store configuration information. User Right: Modify firmware
/// environment values.
/// </summary>
SeSystemEnvironmentPrivilege,
/// <summary>
/// Required to receive notifications of changes to files or directories. This privilege also causes the system to skip all traversal access checks. It
/// is enabled by default for all users. User Right: Bypass traverse checking.
/// </summary>
SeChangeNotifyPrivilege,
/// <summary>Required to shut down a system by using a network request. User Right: Force shutdown from a remote system.</summary>
SeRemoteShutdownPrivilege,
/// <summary>Required to undock a laptop. User Right: Remove computer from docking station.</summary>
SeUndockPrivilege,
/// <summary>
/// Required for a domain controller to use the LDAP directory synchronization services. This privilege allows the holder to read all objects and
/// properties in the directory, regardless of the protection on the objects and properties. By default, it is assigned to the Administrator and
/// LocalSystem accounts on domain controllers. User Right: Synchronize directory service data.
/// </summary>
SeSyncAgentPrivilege,
/// <summary>
/// Required to mark user and computer accounts as trusted for delegation. User Right: Enable computer and user accounts to be trusted for delegation.
/// </summary>
SeEnableDelegationPrivilege,
/// <summary>Required to enable volume management privileges. User Right: Manage the files on a volume.</summary>
SeManageVolumePrivilege,
/// <summary>
/// Required to impersonate. User Right: Impersonate a client after authentication. Windows XP/2000: This privilege is not supported. Note that this
/// value is supported starting with Windows Server 2003, Windows XP with SP2, and Windows 2000 with SP4.
/// </summary>
SeImpersonatePrivilege,
/// <summary>
/// Required to create named file mapping objects in the global namespace during Terminal Services sessions. This privilege is enabled by default for
/// administrators, services, and the local system account. User Right: Create global objects. Windows XP/2000: This privilege is not supported. Note
/// that this value is supported starting with Windows Server 2003, Windows XP with SP2, and Windows 2000 with SP4.
/// </summary>
SeCreateGlobalPrivilege,
/// <summary>Required to access Credential Manager as a trusted caller. User Right: Access Credential Manager as a trusted caller.</summary>
SeTrustedCredManAccessPrivilege,
/// <summary>Required to modify the mandatory integrity level of an object. User Right: Modify an object label.</summary>
SeRelabelPrivilege,
/// <summary>Required to allocate more memory for applications that run in the context of users. User Right: Increase a process working set.</summary>
SeIncreaseWorkingSetPrivilege,
/// <summary>Required to adjust the time zone associated with the computer's internal clock. User Right: Change the time zone.</summary>
SeTimeZonePrivilege,
/// <summary>Required to create a symbolic link. User Right: Create symbolic links.</summary>
SeCreateSymbolicLinkPrivilege
}
/// <summary>
/// Defines the types of process security identifier (SID) that can be used by tasks. These changes are used to specify the type of process SID in the
/// IPrincipal2 interface.
/// </summary>
public enum TaskProcessTokenSidType
{
/// <summary>No changes will be made to the process token groups list.</summary>
None = 0,
/// <summary>
/// A task SID that is derived from the task name will be added to the process token groups list, and the token default discretionary access control list
/// (DACL) will be modified to allow only the task SID and local system full control and the account SID read control.
/// </summary>
Unrestricted = 1,
/// <summary>A Task Scheduler will apply default settings to the task process.</summary>
Default = 2
}
/// <summary>Defines how a task is run.</summary>
[Flags]
public enum TaskRunFlags
{
/// <summary>The task is run with all flags ignored.</summary>
NoFlags = 0,
/// <summary>The task is run as the user who is calling the Run method.</summary>
AsSelf = 1,
/// <summary>The task is run regardless of constraints such as "do not run on batteries" or "run only if idle".</summary>
IgnoreConstraints = 2,
/// <summary>The task is run using a terminal server session identifier.</summary>
UseSessionId = 4,
/// <summary>The task is run using a security identifier.</summary>
UserSID = 8
}
/// <summary>Defines LUA elevation flags that specify with what privilege level the task will be run.</summary>
public enum TaskRunLevel
{
/// <summary>Tasks will be run with the least privileges.</summary>
[XmlEnum("LeastPrivilege")]
LUA,
/// <summary>Tasks will be run with the highest privileges.</summary>
[XmlEnum("HighestAvailable")]
Highest
}
/// <summary>
/// Defines what kind of Terminal Server session state change you can use to trigger a task to start. These changes are used to specify the type of state
/// change in the SessionStateChangeTrigger.
/// </summary>
public enum TaskSessionStateChangeType
{
/// <summary>
/// Terminal Server console connection state change. For example, when you connect to a user session on the local computer by switching users on the computer.
/// </summary>
ConsoleConnect = 1,
/// <summary>
/// Terminal Server console disconnection state change. For example, when you disconnect to a user session on the local computer by switching users on
/// the computer.
/// </summary>
ConsoleDisconnect = 2,
/// <summary>
/// Terminal Server remote connection state change. For example, when a user connects to a user session by using the Remote Desktop Connection program
/// from a remote computer.
/// </summary>
RemoteConnect = 3,
/// <summary>
/// Terminal Server remote disconnection state change. For example, when a user disconnects from a user session while using the Remote Desktop Connection
/// program from a remote computer.
/// </summary>
RemoteDisconnect = 4,
/// <summary>Terminal Server session locked state change. For example, this state change causes the task to run when the computer is locked.</summary>
SessionLock = 7,
/// <summary>Terminal Server session unlocked state change. For example, this state change causes the task to run when the computer is unlocked.</summary>
SessionUnlock = 8
}
/// <summary>Options for use when calling the SetSecurityDescriptorSddlForm methods.</summary>
[Flags]
public enum TaskSetSecurityOptions
{
/// <summary>No special handling.</summary>
None = 0,
/// <summary>The Task Scheduler service is prevented from adding the allow access-control entry (ACE) for the context principal.</summary>
DontAddPrincipalAce = 0x10
}
/***** WAITING TO DETERMINE USE CASE *****
/// <summary>Success and error codes that some methods will expose through <see cref="COMExcpetion"/>.</summary>
public enum TaskResultCode
{
/// <summary>The task is ready to run at its next scheduled time.</summary>
TaskReady = 0x00041300,
/// <summary>The task is currently running.</summary>
TaskRunning = 0x00041301,
/// <summary>The task will not run at the scheduled times because it has been disabled.</summary>
TaskDisabled = 0x00041302,
/// <summary>The task has not yet run.</summary>
TaskHasNotRun = 0x00041303,
/// <summary>There are no more runs scheduled for this task.</summary>
TaskNoMoreRuns = 0x00041304,
/// <summary>One or more of the properties that are needed to run this task on a schedule have not been set.</summary>
TaskNotScheduled = 0x00041305,
/// <summary>The last run of the task was terminated by the user.</summary>
TaskTerminated = 0x00041306,
/// <summary>Either the task has no triggers or the existing triggers are disabled or not set.</summary>
TaskNoValidTriggers = 0x00041307,
/// <summary>Event triggers do not have set run times.</summary>
EventTrigger = 0x00041308,
/// <summary>A task's trigger is not found.</summary>
TriggerNotFound = 0x80041309,
/// <summary>One or more of the properties required to run this task have not been set.</summary>
TaskNotReady = 0x8004130A,
/// <summary>There is no running instance of the task.</summary>
TaskNotRunning = 0x8004130B,
/// <summary>The Task Scheduler service is not installed on this computer.</summary>
ServiceNotInstalled = 0x8004130C,
/// <summary>The task object could not be opened.</summary>
CannotOpenTask = 0x8004130D,
/// <summary>The object is either an invalid task object or is not a task object.</summary>
InvalidTask = 0x8004130E,
/// <summary>No account information could be found in the Task Scheduler security database for the task indicated.</summary>
AccountInformationNotSet = 0x8004130F,
/// <summary>Unable to establish existence of the account specified.</summary>
AccountNameNotFound = 0x80041310,
/// <summary>Corruption was detected in the Task Scheduler security database; the database has been reset.</summary>
AccountDbaseCorrupt = 0x80041311,
/// <summary>Task Scheduler security services are available only on Windows NT.</summary>
NoSecurityServices = 0x80041312,
/// <summary>The task object version is either unsupported or invalid.</summary>
UnknownObjectVersion = 0x80041313,
/// <summary>The task has been configured with an unsupported combination of account settings and run time options.</summary>
UnsupportedAccountOption = 0x80041314,
/// <summary>The Task Scheduler Service is not running.</summary>
ServiceNotRunning = 0x80041315,
/// <summary>The task XML contains an unexpected node.</summary>
UnexpectedNode = 0x80041316,
/// <summary>The task XML contains an element or attribute from an unexpected namespace.</summary>
Namespace = 0x80041317,
/// <summary>The task XML contains a value which is incorrectly formatted or out of range.</summary>
InvalidValue = 0x80041318,
/// <summary>The task XML is missing a required element or attribute.</summary>
MissingNode = 0x80041319,
/// <summary>The task XML is malformed.</summary>
MalformedXml = 0x8004131A,
/// <summary>The task is registered, but not all specified triggers will start the task.</summary>
SomeTriggersFailed = 0x0004131B,
/// <summary>The task is registered, but may fail to start. Batch logon privilege needs to be enabled for the task principal.</summary>
BatchLogonProblem = 0x0004131C,
/// <summary>The task XML contains too many nodes of the same type.</summary>
TooManyNodes = 0x8004131D,
/// <summary>The task cannot be started after the trigger end boundary.</summary>
PastEndBoundary = 0x8004131E,
/// <summary>An instance of this task is already running.</summary>
AlreadyRunning = 0x8004131F,
/// <summary>The task will not run because the user is not logged on.</summary>
UserNotLoggedOn = 0x80041320,
/// <summary>The task image is corrupt or has been tampered with.</summary>
InvalidTaskHash = 0x80041321,
/// <summary>The Task Scheduler service is not available.</summary>
ServiceNotAvailable = 0x80041322,
/// <summary>The Task Scheduler service is too busy to handle your request. Please try again later.</summary>
ServiceTooBusy = 0x80041323,
/// <summary>The Task Scheduler service attempted to run the task, but the task did not run due to one of the constraints in the task definition.</summary>
TaskAttempted = 0x80041324,
/// <summary>The Task Scheduler service has asked the task to run.</summary>
TaskQueued = 0x00041325,
/// <summary>The task is disabled.</summary>
TaskDisabled = 0x80041326,
/// <summary>The task has properties that are not compatible with earlier versions of Windows.</summary>
TaskNotV1Compatible = 0x80041327,
/// <summary>The task settings do not allow the task to start on demand.</summary>
StartOnDemand = 0x80041328,
}
*/
/// <summary>Defines the different states that a registered task can be in.</summary>
public enum TaskState
{
/// <summary>The state of the task is unknown.</summary>
Unknown,
/// <summary>The task is registered but is disabled and no instances of the task are queued or running. The task cannot be run until it is enabled.</summary>
Disabled,
/// <summary>Instances of the task are queued.</summary>
Queued,
/// <summary>The task is ready to be executed, but no instances are queued or running.</summary>
Ready,
/// <summary>One or more instances of the task is running.</summary>
Running
}
/// <summary>
/// Specifies how the Task Scheduler performs tasks when the computer is in an idle condition. For information about idle conditions, see Task Idle Conditions.
/// </summary>
[PublicAPI]
public sealed class IdleSettings : IDisposable
{
private ITask v1Task;
private IIdleSettings v2Settings;
internal IdleSettings([NotNull] IIdleSettings iSettings)
{
v2Settings = iSettings;
}
internal IdleSettings([NotNull] ITask iTask)
{
v1Task = iTask;
}
/// <summary>Gets or sets a value that indicates the amount of time that the computer must be in an idle state before the task is run.</summary>
/// <value>
/// A value that indicates the amount of time that the computer must be in an idle state before the task is run. The minimum value is one minute. If this
/// value is <c>TimeSpan.Zero</c>, then the delay will be set to the default of 10 minutes.
/// </value>
[DefaultValue(typeof(TimeSpan), "00:10:00")]
[XmlElement("Duration")]
public TimeSpan IdleDuration
{
get
{
if (v2Settings != null)
return Task.StringToTimeSpan(v2Settings.IdleDuration);
v1Task.GetIdleWait(out ushort _, out var deadMin);
return TimeSpan.FromMinutes(deadMin);
}
set
{
if (v2Settings != null)
{
if (value != TimeSpan.Zero && value < TimeSpan.FromMinutes(1))
throw new ArgumentOutOfRangeException(nameof(IdleDuration));
v2Settings.IdleDuration = Task.TimeSpanToString(value);
}
else
{
v1Task.SetIdleWait((ushort)WaitTimeout.TotalMinutes, (ushort)value.TotalMinutes);
}
}
}
/// <summary>
/// Gets or sets a Boolean value that indicates whether the task is restarted when the computer cycles into an idle condition more than once.
/// </summary>
[DefaultValue(false)]
public bool RestartOnIdle
{
get => v2Settings?.RestartOnIdle ?? v1Task.HasFlags(TaskFlags.RestartOnIdleResume);
set
{
if (v2Settings != null)
v2Settings.RestartOnIdle = value;
else
v1Task.SetFlags(TaskFlags.RestartOnIdleResume, value);
}
}
/// <summary>
/// Gets or sets a Boolean value that indicates that the Task Scheduler will terminate the task if the idle condition ends before the task is completed.
/// </summary>
[DefaultValue(true)]
public bool StopOnIdleEnd
{
get => v2Settings?.StopOnIdleEnd ?? v1Task.HasFlags(TaskFlags.KillOnIdleEnd);
set
{
if (v2Settings != null)
v2Settings.StopOnIdleEnd = value;
else
v1Task.SetFlags(TaskFlags.KillOnIdleEnd, value);
}
}
/// <summary>
/// Gets or sets a value that indicates the amount of time that the Task Scheduler will wait for an idle condition to occur. If no value is specified for
/// this property, then the Task Scheduler service will wait indefinitely for an idle condition to occur.
/// </summary>
/// <value>
/// A value that indicates the amount of time that the Task Scheduler will wait for an idle condition to occur. The minimum time allowed is 1 minute. If
/// this value is <c>TimeSpan.Zero</c>, then the delay will be set to the default of 1 hour.
/// </value>
[DefaultValue(typeof(TimeSpan), "01:00:00")]
public TimeSpan WaitTimeout
{
get
{
if (v2Settings != null)
return Task.StringToTimeSpan(v2Settings.WaitTimeout);
v1Task.GetIdleWait(out var idleMin, out var _);
return TimeSpan.FromMinutes(idleMin);
}
set
{
if (v2Settings != null)
{
if (value != TimeSpan.Zero && value < TimeSpan.FromMinutes(1))
throw new ArgumentOutOfRangeException(nameof(WaitTimeout));
v2Settings.WaitTimeout = Task.TimeSpanToString(value);
}
else
{
v1Task.SetIdleWait((ushort)value.TotalMinutes, (ushort)IdleDuration.TotalMinutes);
}
}
}
/// <summary>Releases all resources used by this class.</summary>
public void Dispose()
{
if (v2Settings != null)
Marshal.ReleaseComObject(v2Settings);
v1Task = null;
}
/// <summary>Returns a <see cref="System.String"/> that represents this instance.</summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString()
{
if (v2Settings != null || v1Task != null)
return DebugHelper.GetDebugString(this);
return base.ToString();
}
}
/// <summary>Specifies the task settings the Task scheduler will use to start task during Automatic maintenance.</summary>
[XmlType(IncludeInSchema = false)]
[PublicAPI]
public sealed class MaintenanceSettings : IDisposable
{
private IMaintenanceSettings iMaintSettings;
private ITaskSettings3 iSettings;
internal MaintenanceSettings([CanBeNull] ITaskSettings3 iSettings3)
{
iSettings = iSettings3;
if (iSettings3 != null)
iMaintSettings = iSettings.MaintenanceSettings;
}
/// <summary>
/// Gets or sets the amount of time after which the Task scheduler attempts to run the task during emergency Automatic maintenance, if the task failed to
/// complete during regular Automatic maintenance. The minimum value is one day. The value of the <see cref="Deadline"/> property should be greater than
/// the value of the <see cref="Period"/> property. If the deadline is not specified the task will not be started during emergency Automatic maintenance.
/// </summary>
/// <exception cref="NotSupportedPriorToException">Property set for a task on a Task Scheduler version prior to 2.2.</exception>
[DefaultValue(typeof(TimeSpan), "00:00:00")]
public TimeSpan Deadline
{
get => iMaintSettings != null ? Task.StringToTimeSpan(iMaintSettings.Deadline) : TimeSpan.Zero;
set
{
if (iSettings != null)
{
if (iMaintSettings == null && value != TimeSpan.Zero)
iMaintSettings = iSettings.CreateMaintenanceSettings();
if (iMaintSettings != null)
iMaintSettings.Deadline = Task.TimeSpanToString(value);
}
else
throw new NotSupportedPriorToException(TaskCompatibility.V2_2);
}
}
/// <summary>
/// Gets or sets a value indicating whether the Task Scheduler must start the task during the Automatic maintenance in exclusive mode. The exclusivity is
/// guaranteed only between other maintenance tasks and doesn't grant any ordering priority of the task. If exclusivity is not specified, the task is
/// started in parallel with other maintenance tasks.
/// </summary>
/// <exception cref="NotSupportedPriorToException">Property set for a task on a Task Scheduler version prior to 2.2.</exception>
[DefaultValue(false)]
public bool Exclusive
{
get => iMaintSettings != null && iMaintSettings.Exclusive;
set
{
if (iSettings != null)
{
if (iMaintSettings == null && value)
iMaintSettings = iSettings.CreateMaintenanceSettings();
if (iMaintSettings != null)
iMaintSettings.Exclusive = value;
}
else
throw new NotSupportedPriorToException(TaskCompatibility.V2_2);
}
}
/// <summary>Gets or sets the amount of time the task needs to be started during Automatic maintenance. The minimum value is one minute.</summary>
/// <exception cref="NotSupportedPriorToException">Property set for a task on a Task Scheduler version prior to 2.2.</exception>
[DefaultValue(typeof(TimeSpan), "00:00:00")]
public TimeSpan Period
{
get => iMaintSettings != null ? Task.StringToTimeSpan(iMaintSettings.Period) : TimeSpan.Zero;
set
{
if (iSettings != null)
{
if (iMaintSettings == null && value != TimeSpan.Zero)
iMaintSettings = iSettings.CreateMaintenanceSettings();
if (iMaintSettings != null)
iMaintSettings.Period = Task.TimeSpanToString(value);
}
else
throw new NotSupportedPriorToException(TaskCompatibility.V2_2);
}
}
/// <summary>Releases all resources used by this class.</summary>
public void Dispose()
{
if (iMaintSettings != null)
Marshal.ReleaseComObject(iMaintSettings);
}
/// <summary>Returns a <see cref="System.String"/> that represents this instance.</summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString() => iMaintSettings != null ? DebugHelper.GetDebugString(this) : base.ToString();
internal bool IsSet() => iMaintSettings != null && (iMaintSettings.Period != null || iMaintSettings.Deadline != null || iMaintSettings.Exclusive);
}
/// <summary>Provides the settings that the Task Scheduler service uses to obtain a network profile.</summary>
[XmlType(IncludeInSchema = false)]
[PublicAPI]
public sealed class NetworkSettings : IDisposable
{
private INetworkSettings v2Settings;
internal NetworkSettings([CanBeNull] INetworkSettings iSettings)
{
v2Settings = iSettings;
}
/// <summary>Gets or sets a GUID value that identifies a network profile.</summary>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
[DefaultValue(typeof(Guid), "00000000-0000-0000-0000-000000000000")]
public Guid Id
{
get
{
string id = null;
if (v2Settings != null)
id = v2Settings.Id;
return string.IsNullOrEmpty(id) ? Guid.Empty : new Guid(id);
}
set
{
if (v2Settings != null)
v2Settings.Id = value == Guid.Empty ? null : value.ToString();
else
throw new NotV1SupportedException();
}
}
/// <summary>Gets or sets the name of a network profile. The name is used for display purposes.</summary>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
[DefaultValue(null)]
public string Name
{
get => v2Settings?.Name;
set
{
if (v2Settings != null)
v2Settings.Name = value;
else
throw new NotV1SupportedException();
}
}
/// <summary>Releases all resources used by this class.</summary>
public void Dispose()
{
if (v2Settings != null)
Marshal.ReleaseComObject(v2Settings);
}
/// <summary>Returns a <see cref="System.String"/> that represents this instance.</summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString()
{
if (v2Settings != null)
return DebugHelper.GetDebugString(this);
return base.ToString();
}
internal bool IsSet() => v2Settings != null && (!string.IsNullOrEmpty(v2Settings.Id) || !string.IsNullOrEmpty(v2Settings.Name));
}
/// <summary>Provides the methods to get information from and control a running task.</summary>
[XmlType(IncludeInSchema = false)]
[PublicAPI]
public sealed class RunningTask : Task
{
private IRunningTask v2RunningTask;
internal RunningTask([NotNull] TaskService svc, [NotNull] IRegisteredTask iTask, [NotNull] IRunningTask iRunningTask)
: base(svc, iTask)
{
v2RunningTask = iRunningTask;
}
internal RunningTask([NotNull] TaskService svc, [NotNull] ITask iTask)
: base(svc, iTask)
{
}
/// <summary>Gets the process ID for the engine (process) which is running the task.</summary>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
public uint EnginePID
{
get
{
if (v2RunningTask != null)
return v2RunningTask.EnginePID;
throw new NotV1SupportedException();
}
}
/// <summary>Gets the name of the current action that the running task is performing.</summary>
public string CurrentAction => v2RunningTask != null ? v2RunningTask.CurrentAction : v1Task.GetApplicationName();
/// <summary>Gets the GUID identifier for this instance of the task.</summary>
public Guid InstanceGuid => v2RunningTask != null ? new Guid(v2RunningTask.InstanceGuid) : Guid.Empty;
/// <summary>Gets the operational state of the running task.</summary>
public override TaskState State => v2RunningTask?.State ?? base.State;
/// <summary>Releases all resources used by this class.</summary>
public new void Dispose()
{
base.Dispose();
if (v2RunningTask != null) Marshal.ReleaseComObject(v2RunningTask);
}
/// <summary>Refreshes all of the local instance variables of the task.</summary>
public void Refresh() { v2RunningTask?.Refresh(); }
}
/// <summary>
/// Provides the methods that are used to run the task immediately, get any running instances of the task, get or set the credentials that are used to
/// register the task, and the properties that describe the task.
/// </summary>
[XmlType(IncludeInSchema = false)]
[PublicAPI]
public class Task : IDisposable, IComparable, IComparable<Task>
{
internal const AccessControlSections defaultAccessControlSections = AccessControlSections.Owner | AccessControlSections.Group | AccessControlSections.Access;
internal const SecurityInfos defaultSecurityInfosSections = SecurityInfos.Owner | SecurityInfos.Group | SecurityInfos.DiscretionaryAcl;
internal ITask v1Task;
private static readonly int osLibMinorVer = GetOSLibraryMinorVersion();
private static readonly DateTime v2InvalidDate = new DateTime(1899, 12, 30);
private TaskDefinition myTD;
private IRegisteredTask v2Task;
internal Task([NotNull] TaskService svc, [NotNull] ITask iTask)
{
TaskService = svc;
v1Task = iTask;
ReadOnly = false;
}
internal Task([NotNull] TaskService svc, [NotNull] IRegisteredTask iTask, ITaskDefinition iDef = null)
{
TaskService = svc;
v2Task = iTask;
if (iDef != null)
myTD = new TaskDefinition(iDef);
ReadOnly = false;
}
/// <summary>Gets the definition of the task.</summary>
[NotNull]
public TaskDefinition Definition => myTD ?? (myTD = v2Task != null ? new TaskDefinition(GetV2Definition(TaskService, v2Task, true)) : new TaskDefinition(v1Task, Name));
/// <summary>Gets or sets a Boolean value that indicates if the registered task is enabled.</summary>
/// <remarks>
/// As of version 1.8.1, under V1 systems (prior to Vista), this property will immediately update the Disabled state and re-save the current task. If
/// changes have been made to the <see cref="TaskDefinition"/>, then those changes will be saved.
/// </remarks>
public bool Enabled
{
get => v2Task?.Enabled ?? Definition.Settings.Enabled;
set
{
if (v2Task != null)
v2Task.Enabled = value;
else
{
Definition.Settings.Enabled = value;
Definition.V1Save(null);
}
}
}
/// <summary>Gets an instance of the parent folder.</summary>
/// <value>A <see cref="TaskFolder"/> object representing the parent folder of this task.</value>
[NotNull]
public TaskFolder Folder
{
get
{
if (v2Task == null)
return TaskService.RootFolder;
var path = v2Task.Path;
var parentPath = System.IO.Path.GetDirectoryName(path);
if (string.IsNullOrEmpty(parentPath) || parentPath == TaskFolder.rootString)
return TaskService.RootFolder;
return TaskService.GetFolder(parentPath);
}
}
/// <summary>Gets a value indicating whether this task instance is active.</summary>
/// <value><c>true</c> if this task instance is active; otherwise, <c>false</c>.</value>
public bool IsActive
{
get
{
var now = DateTime.Now;
if (!Definition.Settings.Enabled) return false;
foreach (var trigger in Definition.Triggers)
{
if (!trigger.Enabled || now < trigger.StartBoundary || now > trigger.EndBoundary) continue;
if (!(trigger is ICalendarTrigger) || DateTime.MinValue != NextRunTime || trigger is TimeTrigger)
return true;
}
return false;
}
}
/// <summary>Gets the time the registered task was last run.</summary>
/// <value>Returns <see cref="DateTime.MinValue"/> if there are no prior run times.</value>
public DateTime LastRunTime
{
get
{
if (v2Task == null) return v1Task.GetMostRecentRunTime();
var dt = v2Task.LastRunTime;
return dt == v2InvalidDate ? DateTime.MinValue : dt;
}
}
/// <summary>Gets the results that were returned the last time the registered task was run.</summary>
public int LastTaskResult
{
get
{
if (v2Task != null)
return v2Task.LastTaskResult;
return (int)v1Task.GetExitCode();
}
}
/// <summary>Gets the time when the registered task is next scheduled to run.</summary>
/// <value>Returns <see cref="DateTime.MinValue"/> if there are no future run times.</value>
/// <remarks>
/// Potentially breaking change in release 1.8.2. For Task Scheduler 2.0, the return value prior to 1.8.2 would be Dec 30, 1899 if there were no future
/// run times. For 1.0, that value would have been <c>DateTime.MinValue</c>. In release 1.8.2 and later, all versions will return
/// <c>DateTime.MinValue</c> if there are no future run times. While this is different from the native 2.0 library, it was deemed more appropriate to
/// have consistency between the two libraries and with other .NET libraries.
/// </remarks>
public DateTime NextRunTime
{
get
{
if (v2Task == null) return v1Task.GetNextRunTime();
var ret = v2Task.NextRunTime;
if (ret != DateTime.MinValue && ret != v2InvalidDate) return ret == v2InvalidDate ? DateTime.MinValue : ret;
var nrts = GetRunTimes(DateTime.Now, DateTime.MaxValue, 1);
ret = nrts.Length > 0 ? nrts[0] : DateTime.MinValue;
return ret == v2InvalidDate ? DateTime.MinValue : ret;
}
}
/// <summary>Gets the number of times the registered task has missed a scheduled run.</summary>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
public int NumberOfMissedRuns => v2Task?.NumberOfMissedRuns ?? throw new NotV1SupportedException();
/// <summary>Gets the path to where the registered task is stored.</summary>
[NotNull]
public string Path => v2Task != null ? v2Task.Path : "\\" + Name;
/// <summary>
/// Gets a value indicating whether this task is read only. Only available if <see cref="Microsoft.Win32.TaskScheduler.TaskService.AllowReadOnlyTasks"/>
/// is <c>true</c>.
/// </summary>
/// <value><c>true</c> if read only; otherwise, <c>false</c>.</value>
public bool ReadOnly { get; internal set; }
/// <summary>Gets or sets the security descriptor for the task.</summary>
/// <value>The security descriptor.</value>
[Obsolete("This property will be removed in deference to the GetAccessControl, GetSecurityDescriptorSddlForm, SetAccessControl and SetSecurityDescriptorSddlForm methods.")]
public GenericSecurityDescriptor SecurityDescriptor
{
get
{
var sddl = GetSecurityDescriptorSddlForm();
return new RawSecurityDescriptor(sddl);
}
set => SetSecurityDescriptorSddlForm(value.GetSddlForm(defaultAccessControlSections));
}
/// <summary>Gets the operational state of the registered task.</summary>
public virtual TaskState State
{
get
{
if (v2Task != null)
return v2Task.State;
V1Reactivate();
if (!Enabled)
return TaskState.Disabled;
switch (v1Task.GetStatus())
{
case TaskStatus.Ready:
case TaskStatus.NeverRun:
case TaskStatus.NoMoreRuns:
case TaskStatus.Terminated:
return TaskState.Ready;
case TaskStatus.Running:
return TaskState.Running;
case TaskStatus.Disabled:
return TaskState.Disabled;
// case TaskStatus.NotScheduled: case TaskStatus.NoTriggers: case TaskStatus.NoTriggerTime:
default:
return TaskState.Unknown;
}
}
}
/// <summary>Gets or sets the <see cref="TaskService"/> that manages this task.</summary>
/// <value>The task service.</value>
public TaskService TaskService { get; }
/// <summary>Gets the name of the registered task.</summary>
[NotNull]
public string Name => v2Task != null ? v2Task.Name : System.IO.Path.GetFileNameWithoutExtension(GetV1Path(v1Task));
/// <summary>Gets the XML-formatted registration information for the registered task.</summary>
public string Xml => v2Task != null ? v2Task.Xml : Definition.XmlText;
/// <summary>
/// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes,
/// follows, or occurs in the same position in the sort order as the other object.
/// </summary>
/// <param name="other">An object to compare with this instance.</param>
/// <returns>A value that indicates the relative order of the objects being compared.</returns>
public int CompareTo(Task other) => string.Compare(Path, other?.Path, StringComparison.InvariantCulture);
/// <summary>Releases all resources used by this class.</summary>
public void Dispose()
{
if (v2Task != null)
Marshal.ReleaseComObject(v2Task);
v1Task = null;
}
/// <summary>Exports the task to the specified file in XML.</summary>
/// <param name="outputFileName">Name of the output file.</param>
public void Export([NotNull] string outputFileName)
{
File.WriteAllText(outputFileName, Xml, Encoding.Unicode);
}
/// <summary>
/// Gets a <see cref="TaskSecurity"/> object that encapsulates the specified type of access control list (ACL) entries for the task described by the
/// current <see cref="Task"/> object.
/// </summary>
/// <returns>A <see cref="TaskSecurity"/> object that encapsulates the access control rules for the current task.</returns>
public TaskSecurity GetAccessControl() => GetAccessControl(defaultAccessControlSections);
/// <summary>
/// Gets a <see cref="TaskSecurity"/> object that encapsulates the specified type of access control list (ACL) entries for the task described by the
/// current <see cref="Task"/> object.
/// </summary>
/// <param name="includeSections">
/// One of the <see cref="System.Security.AccessControl.AccessControlSections"/> values that specifies which group of access control entries to retrieve.
/// </param>
/// <returns>A <see cref="TaskSecurity"/> object that encapsulates the access control rules for the current task.</returns>
public TaskSecurity GetAccessControl(AccessControlSections includeSections) => new TaskSecurity(this, includeSections);
/// <summary>Gets all instances of the currently running registered task.</summary>
/// <returns>A <see cref="RunningTaskCollection"/> with all instances of current task.</returns>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
[NotNull, ItemNotNull]
public RunningTaskCollection GetInstances() => v2Task != null
? new RunningTaskCollection(TaskService, v2Task.GetInstances(0))
: throw new NotV1SupportedException();
/// <summary>
/// Gets the last registration time, looking first at the <see cref="TaskRegistrationInfo.Date"/> value and then looking for the most recent registration
/// event in the Event Log.
/// </summary>
/// <returns><see cref="DateTime"/> of the last registration or <see cref="DateTime.MinValue"/> if no value can be found.</returns>
public DateTime GetLastRegistrationTime()
{
var ret = Definition.RegistrationInfo.Date;
if (ret != DateTime.MinValue) return ret;
var log = new TaskEventLog(Path, new[] { (int)StandardTaskEventId.JobRegistered }, null, TaskService.TargetServer, TaskService.UserAccountDomain, TaskService.UserName, TaskService.UserPassword);
if (!log.Enabled) return ret;
foreach (var item in log)
{
if (item.TimeCreated.HasValue)
return item.TimeCreated.Value;
}
return ret;
}
/// <summary>Gets the times that the registered task is scheduled to run during a specified time.</summary>
/// <param name="start">The starting time for the query.</param>
/// <param name="end">The ending time for the query.</param>
/// <param name="count">The requested number of runs. A value of 0 will return all times requested.</param>
/// <returns>The scheduled times that the task will run.</returns>
[NotNull]
public DateTime[] GetRunTimes(DateTime start, DateTime end, uint count = 0)
{
const ushort TASK_MAX_RUN_TIMES = 1440;
NativeMethods.SYSTEMTIME stStart = start;
NativeMethods.SYSTEMTIME stEnd = end;
var runTimes = IntPtr.Zero;
var ret = new DateTime[0];
try
{
if (v2Task != null)
v2Task.GetRunTimes(ref stStart, ref stEnd, ref count, ref runTimes);
else
{
var count1 = count > 0 && count <= TASK_MAX_RUN_TIMES ? (ushort)count : TASK_MAX_RUN_TIMES;
v1Task.GetRunTimes(ref stStart, ref stEnd, ref count1, ref runTimes);
count = count1;
}
ret = InteropUtil.ToArray<NativeMethods.SYSTEMTIME, DateTime>(runTimes, (int)count);
}
catch (Exception ex)
{
Debug.WriteLine($"Task.GetRunTimes failed: Error {ex}.");
}
finally
{
Marshal.FreeCoTaskMem(runTimes);
}
Debug.WriteLine($"Task.GetRunTimes ({(v2Task != null ? "V2" : "V1")}): Returned {count} items from {stStart} to {stEnd}.");
return ret;
}
/// <summary>Gets the security descriptor for the task. Not available to Task Scheduler 1.0.</summary>
/// <param name="includeSections">Section(s) of the security descriptor to return.</param>
/// <returns>The security descriptor for the task.</returns>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
public string GetSecurityDescriptorSddlForm(SecurityInfos includeSections = defaultSecurityInfosSections) => v2Task != null ? v2Task.GetSecurityDescriptor((int) includeSections) : throw new NotV1SupportedException();
/// <summary>
/// Updates the task with any changes made to the <see cref="Definition"/> by calling
/// <see cref="TaskFolder.RegisterTaskDefinition(string, TaskDefinition)"/> from the currently registered folder using the currently registered name.
/// </summary>
/// <exception cref="System.Security.SecurityException">Thrown if task was previously registered with a password.</exception>
public void RegisterChanges()
{
if (Definition.Principal.LogonType == TaskLogonType.InteractiveTokenOrPassword || Definition.Principal.LogonType == TaskLogonType.Password)
throw new SecurityException("Tasks which have been registered previously with stored passwords must use the TaskFolder.RegisterTaskDefinition method for updates.");
if (v2Task != null)
TaskService.GetFolder(System.IO.Path.GetDirectoryName(Path)).RegisterTaskDefinition(Name, Definition);
else
TaskService.RootFolder.RegisterTaskDefinition(Name, Definition);
}
/// <summary>Runs the registered task immediately.</summary>
/// <param name="parameters">
/// <para>The parameters used as values in the task actions. A maximum of 32 parameters can be supplied.</para>
/// <para>
/// These values can be used in the task action where the $(ArgX) variables are used in the action properties. For more information see
/// <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa383549(v=vs.85).aspx#USING_VARIABLES_IN_ACTION_PROPERTIES">Task Actions</a>.
/// </para>
/// </param>
/// <returns>A <see cref="RunningTask"/> instance that defines the new instance of the task.</returns>
public RunningTask Run(params string[] parameters)
{
if (v2Task != null)
{
if (parameters.Length > 32)
throw new ArgumentOutOfRangeException(nameof(parameters), "A maximum of 32 values is allowed.");
if (TaskService.HighestSupportedVersion < TaskServiceVersion.V1_5 && parameters.Any(p => (p?.Length ?? 0) >= 260))
throw new ArgumentOutOfRangeException(nameof(parameters), "On systems prior to Windows 10, all individual parameters must be less than 260 characters.");
var irt = v2Task.Run(parameters.Length == 0 ? null : parameters);
return irt != null ? new RunningTask(TaskService, v2Task, irt) : null;
}
v1Task.Run();
return new RunningTask(TaskService, v1Task);
}
/// <summary>Runs the registered task immediately using specified flags and a session identifier.</summary>
/// <param name="flags">Defines how the task is run.</param>
/// <param name="sessionID">
/// <para>The terminal server session in which you want to start the task.</para>
/// <para>
/// If the <see cref="TaskRunFlags.UseSessionId"/> value is not passed into the <paramref name="flags"/> parameter, then the value specified in this
/// parameter is ignored.If the <see cref="TaskRunFlags.UseSessionId"/> value is passed into the flags parameter and the sessionID value is less than or
/// equal to 0, then an invalid argument error will be returned.
/// </para>
/// <para>
/// If the <see cref="TaskRunFlags.UseSessionId"/> value is passed into the <paramref name="flags"/> parameter and the sessionID value is a valid session
/// ID greater than 0 and if no value is specified for the user parameter, then the Task Scheduler service will try to start the task interactively as
/// the user who is logged on to the specified session.
/// </para>
/// <para>
/// If the <see cref="TaskRunFlags.UseSessionId"/> value is passed into the <paramref name="flags"/> parameter and the sessionID value is a valid session
/// ID greater than 0 and if a user is specified in the user parameter, then the Task Scheduler service will try to start the task interactively as the
/// user who is specified in the user parameter.
/// </para>
/// </param>
/// <param name="user">The user for which the task runs.</param>
/// <param name="parameters">
/// <para>The parameters used as values in the task actions. A maximum of 32 parameters can be supplied.</para>
/// <para>
/// These values can be used in the task action where the $(ArgX) variables are used in the action properties. For more information see
/// <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa383549(v=vs.85).aspx#USING_VARIABLES_IN_ACTION_PROPERTIES">Task Actions</a>.
/// </para>
/// </param>
/// <returns>A <see cref="RunningTask"/> instance that defines the new instance of the task.</returns>
/// <remarks>
/// <para>
/// This method will return without error, but the task will not run if the AllowDemandStart property of ITaskSettings is set to false for the task.
/// </para>
/// <para>If RunEx is invoked from a disabled task, it will return <c>null</c> and the task will not be run.</para>
/// </remarks>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
public RunningTask RunEx(TaskRunFlags flags, int sessionID, string user, params string[] parameters)
{
if (v2Task == null) throw new NotV1SupportedException();
if (parameters.Length > 32)
throw new ArgumentOutOfRangeException(nameof(parameters), "A maximum of 32 parameters can be supplied to RunEx.");
if (TaskService.HighestSupportedVersion < TaskServiceVersion.V1_5 && parameters.Any(p => (p?.Length ?? 0) >= 260))
throw new ArgumentOutOfRangeException(nameof(parameters), "On systems prior to Windows 10, no individual parameter may be more than 260 characters.");
var irt = v2Task.RunEx(parameters.Length == 0 ? null : parameters, (int)flags, sessionID, user);
return irt != null ? new RunningTask(TaskService, v2Task, irt) : null;
}
/// <summary>
/// Applies access control list (ACL) entries described by a <see cref="TaskSecurity"/> object to the file described by the current <see cref="Task"/> object.
/// </summary>
/// <param name="taskSecurity">A <see cref="TaskSecurity"/> object that describes an access control list (ACL) entry to apply to the current task.</param>
/// <example>
/// <para>Give read access to all authenticated users for a task.</para>
/// <code lang="cs">
/// <![CDATA[
/// // Assume variable 'task' is a valid Task instance
/// var taskSecurity = task.GetAccessControl();
/// taskSecurity.AddAccessRule(new TaskAccessRule("Authenticated Users", TaskRights.Read, System.Security.AccessControl.AccessControlType.Allow));
/// task.SetAccessControl(taskSecurity);
/// ]]>
/// </code>
/// </example>
public void SetAccessControl([NotNull] TaskSecurity taskSecurity)
{
taskSecurity.Persist(this);
}
/// <summary>Sets the security descriptor for the task. Not available to Task Scheduler 1.0.</summary>
/// <param name="sddlForm">The security descriptor for the task.</param>
/// <param name="options">Flags that specify how to set the security descriptor.</param>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
public void SetSecurityDescriptorSddlForm([NotNull] string sddlForm, TaskSetSecurityOptions options = TaskSetSecurityOptions.None)
{
if (v2Task != null)
v2Task.SetSecurityDescriptor(sddlForm, (int)options);
else
throw new NotV1SupportedException();
}
/// <summary>Dynamically tries to load the assembly for the editor and displays it as editable for this task.</summary>
/// <returns><c>true</c> if editor returns with OK response; <c>false</c> otherwise.</returns>
/// <remarks>
/// The Microsoft.Win32.TaskSchedulerEditor.dll assembly must reside in the same directory as the Microsoft.Win32.TaskScheduler.dll or in the GAC.
/// </remarks>
public bool ShowEditor()
{
try
{
var t = ReflectionHelper.LoadType("Microsoft.Win32.TaskScheduler.TaskEditDialog", "Microsoft.Win32.TaskSchedulerEditor.dll");
if (t != null)
return ReflectionHelper.InvokeMethod<int>(t, new object[] { this, true, true }, "ShowDialog") == 1;
}
catch { }
return false;
}
/// <summary>Shows the property page for the task (v1.0 only).</summary>
public void ShowPropertyPage()
{
if (v1Task != null)
v1Task.EditWorkItem(IntPtr.Zero, 0);
else
throw new NotV2SupportedException();
}
/// <summary>Stops the registered task immediately.</summary>
/// <remarks>
/// <para>The <c>Stop</c> method stops all instances of the task.</para>
/// <para>
/// System account users can stop a task, users with Administrator group privileges can stop a task, and if a user has rights to execute and read a task,
/// then the user can stop the task. A user can stop the task instances that are running under the same credentials as the user account. In all other
/// cases, the user is denied access to stop the task.
/// </para>
/// </remarks>
public void Stop()
{
if (v2Task != null)
v2Task.Stop(0);
else
v1Task.Terminate();
}
/// <summary>Returns a <see cref="System.String"/> that represents this instance.</summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString() => Name;
int IComparable.CompareTo(object other) => CompareTo(other as Task);
internal static Task CreateTask(TaskService svc, IRegisteredTask iTask, bool throwError = false)
{
var iDef = GetV2Definition(svc, iTask, throwError);
if (iDef != null || !svc.AllowReadOnlyTasks) return new Task(svc, iTask, iDef);
iDef = GetV2StrippedDefinition(svc, iTask);
return new Task(svc, iTask, iDef) { ReadOnly = true };
}
internal static int GetOSLibraryMinorVersion() => TaskService.LibraryVersion.Minor;
[NotNull]
internal static string GetV1Path(ITask v1Task)
{
var iFile = (IPersistFile)v1Task;
iFile.GetCurFile(out var fileName);
return fileName ?? string.Empty;
}
/// <summary>Gets the ITaskDefinition for a V2 task and prevents the errors that come when connecting remotely to a higher version of the Task Scheduler.</summary>
/// <param name="svc">The local task service.</param>
/// <param name="iTask">The task instance.</param>
/// <param name="throwError">if set to <c>true</c> this method will throw an exception if unable to get the task definition.</param>
/// <returns>A valid ITaskDefinition that should not throw errors on the local instance.</returns>
/// <exception cref="System.InvalidOperationException">Unable to get a compatible task definition for this version of the library.</exception>
internal static ITaskDefinition GetV2Definition(TaskService svc, IRegisteredTask iTask, bool throwError = false)
{
var xmlVer = new Version();
try
{
var dd = new DefDoc(iTask.Xml);
xmlVer = dd.Version;
if (xmlVer.Minor > osLibMinorVer)
{
var newMinor = xmlVer.Minor;
if (!dd.Contains("Volatile", "false", true) &&
!dd.Contains("MaintenanceSettings"))
newMinor = 3;
if (!dd.Contains("UseUnifiedSchedulingEngine", "false", true) &&
!dd.Contains("DisallowStartOnRemoteAppSession", "false", true) &&
!dd.Contains("RequiredPrivileges") &&
!dd.Contains("ProcessTokenSidType", "Default", true))
newMinor = 2;
if (!dd.Contains("DisplayName") &&
!dd.Contains("GroupId") &&
!dd.Contains("RunLevel", "LeastPrivilege", true) &&
!dd.Contains("SecurityDescriptor") &&
!dd.Contains("Source") &&
!dd.Contains("URI") &&
!dd.Contains("AllowStartOnDemand", "true", true) &&
!dd.Contains("AllowHardTerminate", "true", true) &&
!dd.Contains("MultipleInstancesPolicy", "IgnoreNew", true) &&
!dd.Contains("NetworkSettings") &&
!dd.Contains("StartWhenAvailable", "false", true) &&
!dd.Contains("SendEmail") &&
!dd.Contains("ShowMessage") &&
!dd.Contains("ComHandler") &&
!dd.Contains("EventTrigger") &&
!dd.Contains("SessionStateChangeTrigger") &&
!dd.Contains("RegistrationTrigger") &&
!dd.Contains("RestartOnFailure") &&
!dd.Contains("LogonType", "None", true))
newMinor = 1;
if (newMinor > osLibMinorVer && throwError)
throw new InvalidOperationException($"The current version of the native library (1.{osLibMinorVer}) does not support the original or minimum version of the \"{iTask.Name}\" task ({xmlVer}/1.{newMinor})");
if (newMinor != xmlVer.Minor)
{
dd.Version = new Version(1, newMinor);
var def = svc.v2TaskService.NewTask(0);
def.XmlText = dd.Xml;
return def;
}
}
return iTask.Definition;
}
catch (COMException comEx)
{
if (throwError)
{
if ((uint)comEx.ErrorCode == 0x80041318 && xmlVer.Minor != osLibMinorVer) // Incorrect XML value
throw new InvalidOperationException($"The current version of the native library (1.{osLibMinorVer}) does not support the version of the \"{iTask.Name}\" task ({xmlVer})");
throw;
}
}
catch
{
if (throwError)
throw;
}
return null;
}
internal static ITaskDefinition GetV2StrippedDefinition(TaskService svc, IRegisteredTask iTask)
{
try
{
var dd = new DefDoc(iTask.Xml);
var xmlVer = dd.Version;
if (xmlVer.Minor > osLibMinorVer)
{
if (osLibMinorVer < 4)
{
dd.RemoveTag("Volatile");
dd.RemoveTag("MaintenanceSettings");
}
if (osLibMinorVer < 3)
{
dd.RemoveTag("UseUnifiedSchedulingEngine");
dd.RemoveTag("DisallowStartOnRemoteAppSession");
dd.RemoveTag("RequiredPrivileges");
dd.RemoveTag("ProcessTokenSidType");
}
if (osLibMinorVer < 2)
{
dd.RemoveTag("DisplayName");
dd.RemoveTag("GroupId");
dd.RemoveTag("RunLevel");
dd.RemoveTag("SecurityDescriptor");
dd.RemoveTag("Source");
dd.RemoveTag("URI");
dd.RemoveTag("AllowStartOnDemand");
dd.RemoveTag("AllowHardTerminate");
dd.RemoveTag("MultipleInstancesPolicy");
dd.RemoveTag("NetworkSettings");
dd.RemoveTag("StartWhenAvailable");
dd.RemoveTag("SendEmail");
dd.RemoveTag("ShowMessage");
dd.RemoveTag("ComHandler");
dd.RemoveTag("EventTrigger");
dd.RemoveTag("SessionStateChangeTrigger");
dd.RemoveTag("RegistrationTrigger");
dd.RemoveTag("RestartOnFailure");
dd.RemoveTag("LogonType");
}
dd.RemoveTag("WnfStateChangeTrigger"); // Remove custom triggers that can't be sent to Xml
dd.Version = new Version(1, osLibMinorVer);
var def = svc.v2TaskService.NewTask(0);
#if DEBUG
var path = System.IO.Path.Combine(System.IO.Path.GetTempPath(),
$"TS_Stripped_Def_{xmlVer.Minor}-{osLibMinorVer}_{iTask.Name}.xml");
File.WriteAllText(path, dd.Xml, Encoding.Unicode);
#endif
def.XmlText = dd.Xml;
return def;
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error in GetV2StrippedDefinition: {ex}");
#if DEBUG
throw;
#endif
}
return iTask.Definition;
}
internal static TimeSpan StringToTimeSpan(string input)
{
if (!string.IsNullOrEmpty(input))
try { return XmlConvert.ToTimeSpan(input); } catch { }
return TimeSpan.Zero;
}
internal static string TimeSpanToString(TimeSpan span)
{
if (span != TimeSpan.Zero)
try { return XmlConvert.ToString(span); } catch { }
return null;
}
internal void V1Reactivate()
{
var iTask = TaskService.GetTask(TaskService.v1TaskScheduler, Name);
if (iTask != null)
v1Task = iTask;
}
private class DefDoc
{
private readonly XmlDocument doc;
public DefDoc(string xml)
{
doc = new XmlDocument();
doc.LoadXml(xml);
}
public Version Version
{
get
{
try
{
return new Version(doc["Task"].Attributes["version"].Value);
}
catch
{
throw new InvalidOperationException("Task definition does not contain a version.");
}
}
set
{
var task = doc["Task"];
if (task != null) task.Attributes["version"].Value = value.ToString(2);
}
}
public string Xml => doc.OuterXml;
public bool Contains(string tag, string defaultVal = null, bool removeIfFound = false)
{
var nl = doc.GetElementsByTagName(tag);
while (nl.Count > 0)
{
var e = nl[0];
if (e.InnerText != defaultVal || !removeIfFound || e.ParentNode == null)
return true;
e.ParentNode?.RemoveChild(e);
nl = doc.GetElementsByTagName(tag);
}
return false;
}
public void RemoveTag(string tag)
{
var nl = doc.GetElementsByTagName(tag);
while (nl.Count > 0)
{
var e = nl[0];
e.ParentNode?.RemoveChild(e);
nl = doc.GetElementsByTagName(tag);
}
}
}
}
/// <summary>Contains information about the compatibility of the current configuration with a specified version.</summary>
[PublicAPI]
public class TaskCompatibilityEntry
{
internal TaskCompatibilityEntry(TaskCompatibility comp, string prop, string reason)
{
CompatibilityLevel = comp;
Property = prop;
Reason = reason;
}
/// <summary>Gets the compatibility level.</summary>
/// <value>The compatibility level.</value>
public TaskCompatibility CompatibilityLevel { get; }
/// <summary>Gets the property name with the incompatibility.</summary>
/// <value>The property name.</value>
public string Property { get; }
/// <summary>Gets the reason for the incompatibility.</summary>
/// <value>The reason.</value>
public string Reason { get; }
}
/// <summary>Defines all the components of a task, such as the task settings, triggers, actions, and registration information.</summary>
[XmlRoot("Task", Namespace = tns, IsNullable = false)]
[XmlSchemaProvider("GetV1SchemaFile")]
[PublicAPI]
public sealed class TaskDefinition : IDisposable, IXmlSerializable
{
internal const string tns = "http://schemas.microsoft.com/windows/2004/02/mit/task";
internal string v1Name = string.Empty;
internal ITask v1Task;
internal ITaskDefinition v2Def;
private ActionCollection actions;
private TaskPrincipal principal;
private TaskRegistrationInfo regInfo;
private TaskSettings settings;
private TriggerCollection triggers;
internal TaskDefinition([NotNull] ITask iTask, string name)
{
v1Task = iTask;
v1Name = name;
}
internal TaskDefinition([NotNull] ITaskDefinition iDef)
{
v2Def = iDef;
}
/// <summary>Gets a collection of actions that are performed by the task.</summary>
[XmlArrayItem(ElementName = "Exec", IsNullable = true, Type = typeof(ExecAction))]
[XmlArrayItem(ElementName = "ShowMessage", IsNullable = true, Type = typeof(ShowMessageAction))]
[XmlArrayItem(ElementName = "ComHandler", IsNullable = true, Type = typeof(ComHandlerAction))]
[XmlArrayItem(ElementName = "SendEmail", IsNullable = true, Type = typeof(EmailAction))]
[XmlArray]
[NotNull, ItemNotNull]
public ActionCollection Actions => actions ?? (actions = v2Def != null ? new ActionCollection(v2Def) : new ActionCollection(v1Task));
/// <summary>
/// Gets or sets the data that is associated with the task. This data is ignored by the Task Scheduler service, but is used by third-parties who wish to
/// extend the task format.
/// </summary>
/// <remarks>
/// For V1 tasks, this library makes special use of the SetWorkItemData and GetWorkItemData methods and does not expose that data stream directly.
/// Instead, it uses that data stream to hold a dictionary of properties that are not supported under V1, but can have values under V2. An example of
/// this is the <see cref="TaskRegistrationInfo.URI"/> value which is stored in the data stream.
/// <para>
/// The library does not provide direct access to the V1 work item data. If using V2 properties with a V1 task, programmatic access to the task using the
/// native API will retrieve unreadable results from GetWorkItemData and will eliminate those property values if SetWorkItemData is used.
/// </para>
/// </remarks>
[CanBeNull]
public string Data
{
get => v2Def != null ? v2Def.Data : v1Task.GetDataItem(nameof(Data));
set
{
if (v2Def != null)
v2Def.Data = value;
else
v1Task.SetDataItem(nameof(Data), value);
}
}
/// <summary>Gets the lowest supported version that supports the settings for this <see cref="TaskDefinition"/>.</summary>
[XmlIgnore]
public TaskCompatibility LowestSupportedVersion => GetLowestSupportedVersion();
/// <summary>Gets a collection of triggers that are used to start a task.</summary>
[XmlArrayItem(ElementName = "BootTrigger", IsNullable = true, Type = typeof(BootTrigger))]
[XmlArrayItem(ElementName = "CalendarTrigger", IsNullable = true, Type = typeof(CalendarTrigger))]
[XmlArrayItem(ElementName = "IdleTrigger", IsNullable = true, Type = typeof(IdleTrigger))]
[XmlArrayItem(ElementName = "LogonTrigger", IsNullable = true, Type = typeof(LogonTrigger))]
[XmlArrayItem(ElementName = "TimeTrigger", IsNullable = true, Type = typeof(TimeTrigger))]
[XmlArray]
[NotNull, ItemNotNull]
public TriggerCollection Triggers => triggers ?? (triggers = v2Def != null ? new TriggerCollection(v2Def) : new TriggerCollection(v1Task));
/// <summary>Gets or sets the XML-formatted definition of the task.</summary>
[XmlIgnore]
public string XmlText
{
get => v2Def != null ? v2Def.XmlText : XmlSerializationHelper.WriteObjectToXmlText(this);
set
{
if (v2Def != null)
v2Def.XmlText = value;
else
XmlSerializationHelper.ReadObjectFromXmlText(value, this);
}
}
/// <summary>Gets the principal for the task that provides the security credentials for the task.</summary>
[NotNull]
public TaskPrincipal Principal => principal ?? (principal = v2Def != null ? new TaskPrincipal(v2Def.Principal) : new TaskPrincipal(v1Task));
/// <summary>
/// Gets a class instance of registration information that is used to describe a task, such as the description of the task, the author of the task, and
/// the date the task is registered.
/// </summary>
public TaskRegistrationInfo RegistrationInfo => regInfo ?? (regInfo = v2Def != null ? new TaskRegistrationInfo(v2Def.RegistrationInfo) : new TaskRegistrationInfo(v1Task));
/// <summary>Gets the settings that define how the Task Scheduler service performs the task.</summary>
[NotNull]
public TaskSettings Settings => settings ?? (settings = v2Def != null ? new TaskSettings(v2Def.Settings) : new TaskSettings(v1Task));
/// <summary>Gets the XML Schema file for V1 tasks.</summary>
/// <param name="xs">The <see cref="System.Xml.Schema.XmlSchemaSet"/> for V1 tasks.</param>
/// <returns>An object containing the XML Schema for V1 tasks.</returns>
public static XmlSchemaComplexType GetV1SchemaFile([NotNull] XmlSchemaSet xs)
{
XmlSchema schema;
using (var xsdFile = Assembly.GetAssembly(typeof(TaskDefinition)).GetManifestResourceStream("Microsoft.Win32.TaskScheduler.V1.TaskSchedulerV1Schema.xsd"))
{
var schemaSerializer = new XmlSerializer(typeof(XmlSchema));
schema = (XmlSchema)schemaSerializer.Deserialize(XmlReader.Create(xsdFile));
xs.Add(schema);
}
// target namespace
var name = new XmlQualifiedName("taskType", tns);
var productType = (XmlSchemaComplexType)schema.SchemaTypes[name];
return productType;
}
/// <summary>Determines whether this <see cref="TaskDefinition"/> can use the Unified Scheduling Engine or if it contains unsupported properties.</summary>
/// <param name="throwExceptionWithDetails">
/// if set to <c>true</c> throws an <see cref="InvalidOperationException"/> with details about unsupported properties in the Data property of the exception.
/// </param>
/// <param name="taskSchedulerVersion"></param>
/// <returns><c>true</c> if this <see cref="TaskDefinition"/> can use the Unified Scheduling Engine; otherwise, <c>false</c>.</returns>
public bool CanUseUnifiedSchedulingEngine(bool throwExceptionWithDetails = false, Version taskSchedulerVersion = null)
{
var tsVer = taskSchedulerVersion ?? TaskService.LibraryVersion;
if (tsVer < TaskServiceVersion.V1_3) return false;
var ex = new InvalidOperationException { HelpLink = "http://msdn.microsoft.com/en-us/library/windows/desktop/aa384138(v=vs.85).aspx" };
var bad = false;
/*if (Principal.LogonType == TaskLogonType.InteractiveTokenOrPassword)
{
bad = true;
if (!throwExceptionWithDetails) return false;
TryAdd(ex.Data, "Principal.LogonType", "== TaskLogonType.InteractiveTokenOrPassword");
}
if (Settings.MultipleInstances == TaskInstancesPolicy.StopExisting)
{
bad = true;
if (!throwExceptionWithDetails) return false;
TryAdd(ex.Data, "Settings.MultipleInstances", "== TaskInstancesPolicy.StopExisting");
}*/
if (Settings.NetworkSettings.Id != Guid.Empty && tsVer >= TaskServiceVersion.V1_5)
{
bad = true;
if (!throwExceptionWithDetails) return false;
TryAdd(ex.Data, "Settings.NetworkSettings.Id", "!= Guid.Empty");
}
/*if (!Settings.AllowHardTerminate)
{
bad = true;
if (!throwExceptionWithDetails) return false;
TryAdd(ex.Data, "Settings.AllowHardTerminate", "== false");
}*/
if (!Actions.PowerShellConversion.IsFlagSet(PowerShellActionPlatformOption.Version2))
for (var i = 0; i < Actions.Count; i++)
{
var a = Actions[i];
switch (a)
{
case EmailAction _:
bad = true;
if (!throwExceptionWithDetails) return false;
TryAdd(ex.Data, $"Actions[{i}]", "== typeof(EmailAction)");
break;
case ShowMessageAction _:
bad = true;
if (!throwExceptionWithDetails) return false;
TryAdd(ex.Data, $"Actions[{i}]", "== typeof(ShowMessageAction)");
break;
}
}
if (tsVer == TaskServiceVersion.V1_3)
for (var i = 0; i < Triggers.Count; i++)
{
Trigger t;
try { t = Triggers[i]; }
catch
{
if (!throwExceptionWithDetails) return false;
TryAdd(ex.Data, $"Triggers[{i}]", "is irretrievable.");
continue;
}
switch (t)
{
case MonthlyTrigger _:
bad = true;
if (!throwExceptionWithDetails) return false;
TryAdd(ex.Data, $"Triggers[{i}]", "== typeof(MonthlyTrigger)");
break;
case MonthlyDOWTrigger _:
bad = true;
if (!throwExceptionWithDetails) return false;
TryAdd(ex.Data, $"Triggers[{i}]", "== typeof(MonthlyDOWTrigger)");
break;
/*case ICalendarTrigger _ when t.Repetition.IsSet():
bad = true;
if (!throwExceptionWithDetails) return false;
TryAdd(ex.Data, $"Triggers[{i}].Repetition", "");
break;
case EventTrigger _ when ((EventTrigger)t).ValueQueries.Count > 0:
bad = true;
if (!throwExceptionWithDetails) return false;
TryAdd(ex.Data, $"Triggers[{i}].ValueQueries.Count", "!= 0");
break;*/
}
if (t.ExecutionTimeLimit != TimeSpan.Zero)
{
bad = true;
if (!throwExceptionWithDetails) return false;
TryAdd(ex.Data, $"Triggers[{i}].ExecutionTimeLimit", "!= TimeSpan.Zero");
}
}
if (bad && throwExceptionWithDetails)
throw ex;
return !bad;
}
/// <summary>Releases all resources used by this class.</summary>
public void Dispose()
{
regInfo = null;
triggers = null;
settings = null;
principal = null;
actions = null;
if (v2Def != null) Marshal.ReleaseComObject(v2Def);
v1Task = null;
}
/// <summary>Validates the current <see cref="TaskDefinition"/>.</summary>
/// <param name="throwException">if set to <c>true</c> throw a <see cref="InvalidOperationException"/> with details about invalid properties.</param>
/// <returns><c>true</c> if current <see cref="TaskDefinition"/> is valid; <c>false</c> if not.</returns>
public bool Validate(bool throwException = false)
{
var ex = new InvalidOperationException();
if (Settings.UseUnifiedSchedulingEngine)
{
try { CanUseUnifiedSchedulingEngine(throwException); }
catch (InvalidOperationException iox)
{
foreach (DictionaryEntry kvp in iox.Data)
TryAdd(ex.Data, (kvp.Key as ICloneable)?.Clone() ?? kvp.Key, (kvp.Value as ICloneable)?.Clone() ?? kvp.Value);
}
}
if (Settings.Compatibility >= TaskCompatibility.V2_2)
{
var PT1D = TimeSpan.FromDays(1);
if (Settings.MaintenanceSettings.IsSet() && (Settings.MaintenanceSettings.Period < PT1D || Settings.MaintenanceSettings.Deadline < PT1D || Settings.MaintenanceSettings.Deadline <= Settings.MaintenanceSettings.Period))
TryAdd(ex.Data, "Settings.MaintenanceSettings", "Period or Deadline must be at least 1 day and Deadline must be greater than Period.");
}
var list = new List<TaskCompatibilityEntry>();
if (GetLowestSupportedVersion(list) > Settings.Compatibility)
foreach (var item in list)
TryAdd(ex.Data, item.Property, item.Reason);
var startWhenAvailable = Settings.StartWhenAvailable;
var delOldTask = Settings.DeleteExpiredTaskAfter != TimeSpan.Zero;
var v1 = Settings.Compatibility < TaskCompatibility.V2;
var hasEndBound = false;
for (var i = 0; i < Triggers.Count; i++)
{
Trigger trigger;
try { trigger = Triggers[i]; }
catch
{
TryAdd(ex.Data, $"Triggers[{i}]", "is irretrievable.");
continue;
}
if (startWhenAvailable && trigger.Repetition.Duration != TimeSpan.Zero && trigger.EndBoundary == DateTime.MaxValue)
TryAdd(ex.Data, "Settings.StartWhenAvailable", "== true requires time-based tasks with an end boundary or time-based tasks that are set to repeat infinitely.");
if (v1 && trigger.Repetition.Interval != TimeSpan.Zero && trigger.Repetition.Interval >= trigger.Repetition.Duration)
TryAdd(ex.Data, "Trigger.Repetition.Interval", ">= Trigger.Repetition.Duration under Task Scheduler 1.0.");
if (delOldTask && trigger.EndBoundary != DateTime.MaxValue)
hasEndBound = true;
}
if (delOldTask && !hasEndBound)
TryAdd(ex.Data, "Settings.DeleteExpiredTaskAfter", "!= TimeSpan.Zero requires at least one trigger with an end boundary.");
if (throwException && ex.Data.Count > 0)
throw ex;
return ex.Data.Count == 0;
}
XmlSchema IXmlSerializable.GetSchema() => null;
void IXmlSerializable.ReadXml(XmlReader reader)
{
reader.ReadStartElement(XmlSerializationHelper.GetElementName(this), tns);
XmlSerializationHelper.ReadObjectProperties(reader, this);
reader.ReadEndElement();
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
// TODO:FIX writer.WriteAttributeString("version", "1.1");
XmlSerializationHelper.WriteObjectProperties(writer, this);
}
internal static Dictionary<string, string> GetV1TaskDataDictionary(ITask v1Task)
{
Dictionary<string, string> dict;
var o = GetV1TaskData(v1Task);
if (o is string)
dict = new Dictionary<string, string> { { "Data", o.ToString() }, { "Documentation", o.ToString() } };
else
dict = o as Dictionary<string, string>;
return dict ?? new Dictionary<string, string>();
}
internal static void SetV1TaskData(ITask v1Task, object value)
{
if (value == null)
v1Task.SetWorkItemData(0, null);
else
{
var b = new BinaryFormatter();
var stream = new MemoryStream();
b.Serialize(stream, value);
v1Task.SetWorkItemData((ushort)stream.Length, stream.ToArray());
}
}
internal void V1Save(string newName)
{
if (v1Task != null)
{
Triggers.Bind();
var iFile = (IPersistFile)v1Task;
if (string.IsNullOrEmpty(newName) || newName == v1Name)
{
try
{
iFile.Save(null, false);
iFile = null;
return;
}
catch { }
}
iFile.GetCurFile(out var path);
File.Delete(path);
path = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + newName + Path.GetExtension(path);
File.Delete(path);
iFile.Save(path, true);
}
}
private static object GetV1TaskData(ITask v1Task)
{
var Data = IntPtr.Zero;
try
{
v1Task.GetWorkItemData(out var DataLen, out Data);
if (DataLen == 0)
return null;
var bytes = new byte[DataLen];
Marshal.Copy(Data, bytes, 0, DataLen);
var stream = new MemoryStream(bytes, false);
var b = new BinaryFormatter();
return b.Deserialize(stream);
}
catch { }
finally
{
if (Data != IntPtr.Zero)
Marshal.FreeCoTaskMem(Data);
}
return null;
}
private static void TryAdd(IDictionary d, object k, object v)
{
if (!d.Contains(k))
d.Add(k, v);
}
/// <summary>Gets the lowest supported version.</summary>
/// <param name="outputList">The output list.</param>
/// <returns></returns>
private TaskCompatibility GetLowestSupportedVersion(IList<TaskCompatibilityEntry> outputList = null)
{
var res = TaskCompatibility.V1;
var list = new List<TaskCompatibilityEntry>();
//if (Principal.DisplayName != null)
// { list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Principal.DisplayName", "cannot have a value.")); }
if (Principal.GroupId != null)
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Principal.GroupId", "cannot have a value.")); }
//this.Principal.Id != null ||
if (Principal.LogonType == TaskLogonType.Group || Principal.LogonType == TaskLogonType.None || Principal.LogonType == TaskLogonType.S4U)
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Principal.LogonType", "cannot be Group, None or S4U.")); }
if (Principal.RunLevel == TaskRunLevel.Highest)
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Principal.RunLevel", "cannot be set to Highest.")); }
if (RegistrationInfo.SecurityDescriptorSddlForm != null)
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "RegistrationInfo.SecurityDescriptorSddlForm", "cannot have a value.")); }
//if (RegistrationInfo.Source != null)
// { list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "RegistrationInfo.Source", "cannot have a value.")); }
//if (RegistrationInfo.URI != null)
// { list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "RegistrationInfo.URI", "cannot have a value.")); }
//if (RegistrationInfo.Version != new Version(1, 0))
// { list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "RegistrationInfo.Version", "cannot be set or equal 1.0.")); }
if (Settings.AllowDemandStart == false)
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Settings.AllowDemandStart", "must be true.")); }
if (Settings.AllowHardTerminate == false)
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Settings.AllowHardTerminate", "must be true.")); }
if (Settings.MultipleInstances != TaskInstancesPolicy.IgnoreNew)
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Settings.MultipleInstances", "must be set to IgnoreNew.")); }
if (Settings.NetworkSettings.IsSet())
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Settings.NetworkSetting", "cannot have a value.")); }
if (Settings.RestartCount != 0)
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Settings.RestartCount", "must be 0.")); }
if (Settings.RestartInterval != TimeSpan.Zero)
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Settings.RestartInterval", "must be 0 (TimeSpan.Zero).")); }
if (Settings.StartWhenAvailable)
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Settings.StartWhenAvailable", "must be false.")); }
if ((Actions.PowerShellConversion & PowerShellActionPlatformOption.Version1) != PowerShellActionPlatformOption.Version1 && (Actions.ContainsType(typeof(EmailAction)) || Actions.ContainsType(typeof(ShowMessageAction)) || Actions.ContainsType(typeof(ComHandlerAction))))
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Actions", "may only contain ExecAction types unless Actions.PowerShellConversion includes Version1.")); }
if ((Actions.PowerShellConversion & PowerShellActionPlatformOption.Version2) != PowerShellActionPlatformOption.Version2 && (Actions.ContainsType(typeof(EmailAction)) || Actions.ContainsType(typeof(ShowMessageAction))))
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2_1, "Actions", "may only contain ExecAction and ComHanlderAction types unless Actions.PowerShellConversion includes Version2.")); }
try
{
if (null != Triggers.Find(t => t is ITriggerDelay && ((ITriggerDelay)t).Delay != TimeSpan.Zero))
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Triggers", "cannot contain delays.")); }
if (null != Triggers.Find(t => t.ExecutionTimeLimit != TimeSpan.Zero || t.Id != null))
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Triggers", "cannot contain an ExecutionTimeLimit or Id.")); }
if (null != Triggers.Find(t => (t as LogonTrigger)?.UserId != null))
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Triggers", "cannot contain a LogonTrigger with a UserId.")); }
if (null != Triggers.Find(t => t is MonthlyDOWTrigger && ((MonthlyDOWTrigger)t).RunOnLastWeekOfMonth || t is MonthlyDOWTrigger && (((MonthlyDOWTrigger)t).WeeksOfMonth & (((MonthlyDOWTrigger)t).WeeksOfMonth - 1)) != 0))
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Triggers", "cannot contain a MonthlyDOWTrigger with RunOnLastWeekOfMonth set or multiple WeeksOfMonth.")); }
if (null != Triggers.Find(t => t is MonthlyTrigger && ((MonthlyTrigger)t).RunOnLastDayOfMonth))
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Triggers", "cannot contain a MonthlyTrigger with RunOnLastDayOfMonth set.")); }
if (Triggers.ContainsType(typeof(EventTrigger)) || Triggers.ContainsType(typeof(SessionStateChangeTrigger)) || Triggers.ContainsType(typeof(RegistrationTrigger)))
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Triggers", "cannot contain EventTrigger, SessionStateChangeTrigger, or RegistrationTrigger types.")); }
}
catch
{
list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2, "Triggers", "cannot contain Custom triggers."));
}
if (Principal.ProcessTokenSidType != TaskProcessTokenSidType.Default)
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2_1, "Principal.ProcessTokenSidType", "must be Default.")); }
if (Principal.RequiredPrivileges.Count > 0)
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2_1, "Principal.RequiredPrivileges", "must be empty.")); }
if (Settings.DisallowStartOnRemoteAppSession)
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2_1, "Settings.DisallowStartOnRemoteAppSession", "must be false.")); }
if (Settings.UseUnifiedSchedulingEngine)
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2_1, "Settings.UseUnifiedSchedulingEngine", "must be false.")); }
if (Settings.MaintenanceSettings.IsSet())
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2_2, "this.Settings.MaintenanceSettings", "must have no values set.")); }
if (Settings.Volatile)
{ list.Add(new TaskCompatibilityEntry(TaskCompatibility.V2_2, " this.Settings.Volatile", "must be false.")); }
foreach (var item in list)
{
if (res < item.CompatibilityLevel) res = item.CompatibilityLevel;
outputList?.Add(item);
}
return res;
}
}
/// <summary>
/// Provides the security credentials for a principal. These security credentials define the security context for the tasks that are associated with the principal.
/// </summary>
[XmlRoot("Principals", Namespace = TaskDefinition.tns, IsNullable = true)]
[PublicAPI]
public sealed class TaskPrincipal : IDisposable, IXmlSerializable
{
private const string localSystemAcct = "SYSTEM";
private TaskPrincipalPrivileges reqPriv;
private string v1CachedAcctInfo;
private ITask v1Task;
private IPrincipal v2Principal;
private IPrincipal2 v2Principal2;
internal TaskPrincipal([NotNull] IPrincipal iPrincipal)
{
v2Principal = iPrincipal;
try { v2Principal2 = (IPrincipal2)v2Principal; }
catch { }
}
internal TaskPrincipal([NotNull] ITask iTask)
{
v1Task = iTask;
}
/// <summary>Gets or sets the name of the principal that is displayed in the Task Scheduler UI.</summary>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
[DefaultValue(null)]
public string DisplayName
{
get => v2Principal != null ? v2Principal.DisplayName : v1Task.GetDataItem("PrincipalDisplayName");
set
{
if (v2Principal != null)
v2Principal.DisplayName = value;
else
v1Task.SetDataItem("PrincipalDisplayName", value);
}
}
/// <summary>
/// Gets or sets the identifier of the user group that is required to run the tasks that are associated with the principal. Setting this property to
/// something other than a null or empty string, will set the <see cref="UserId"/> property to NULL and will set the <see cref="LogonType"/> property to TaskLogonType.Group;
/// </summary>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
[DefaultValue(null)]
[XmlIgnore]
public string GroupId
{
get => v2Principal?.GroupId;
set
{
if (v2Principal != null)
{
if (string.IsNullOrEmpty(value))
value = null;
else
{
v2Principal.UserId = null;
v2Principal.LogonType = TaskLogonType.Group;
}
v2Principal.GroupId = value;
}
else
throw new NotV1SupportedException();
}
}
/// <summary>Gets or sets the identifier of the principal.</summary>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
[DefaultValue(null)]
[XmlAttribute(AttributeName = "id", DataType = "ID")]
public string Id
{
get => v2Principal != null ? v2Principal.Id : v1Task.GetDataItem("PrincipalId");
set
{
if (v2Principal != null)
v2Principal.Id = value;
else
v1Task.SetDataItem("PrincipalId", value);
}
}
/// <summary>Gets or sets the security logon method that is required to run the tasks that are associated with the principal.</summary>
/// <exception cref="NotV1SupportedException">TaskLogonType values of Group, None, or S4UNot are not supported under Task Scheduler 1.0.</exception>
[DefaultValue(typeof(TaskLogonType), "None")]
public TaskLogonType LogonType
{
get
{
if (v2Principal != null)
return v2Principal.LogonType;
if (UserId == localSystemAcct)
return TaskLogonType.ServiceAccount;
if (v1Task.HasFlags(TaskFlags.RunOnlyIfLoggedOn))
return TaskLogonType.InteractiveToken;
return TaskLogonType.InteractiveTokenOrPassword;
}
set
{
if (v2Principal != null)
v2Principal.LogonType = value;
else
{
if (value == TaskLogonType.Group || value == TaskLogonType.None || value == TaskLogonType.S4U)
throw new NotV1SupportedException();
v1Task.SetFlags(TaskFlags.RunOnlyIfLoggedOn, value == TaskLogonType.InteractiveToken);
}
}
}
/// <summary>Gets or sets the task process security identifier (SID) type.</summary>
/// <value>One of the <see cref="TaskProcessTokenSidType"/> enumeration constants.</value>
/// <remarks>Setting this value appears to break the Task Scheduler MMC and does not output in XML. Removed to prevent problems.</remarks>
/// <exception cref="NotSupportedPriorToException">Not supported under Task Scheduler versions prior to 2.1.</exception>
[XmlIgnore, DefaultValue(typeof(TaskProcessTokenSidType), "Default")]
public TaskProcessTokenSidType ProcessTokenSidType
{
get => v2Principal2?.ProcessTokenSidType ?? TaskProcessTokenSidType.Default;
set
{
if (v2Principal2 != null)
v2Principal2.ProcessTokenSidType = value;
else
throw new NotSupportedPriorToException(TaskCompatibility.V2_1);
}
}
/// <summary>
/// Gets the security credentials for a principal. These security credentials define the security context for the tasks that are associated with the principal.
/// </summary>
/// <remarks>Setting this value appears to break the Task Scheduler MMC and does not output in XML. Removed to prevent problems.</remarks>
[XmlIgnore]
public TaskPrincipalPrivileges RequiredPrivileges => reqPriv ?? (reqPriv = new TaskPrincipalPrivileges(v2Principal2));
/// <summary>
/// Gets or sets the identifier that is used to specify the privilege level that is required to run the tasks that are associated with the principal.
/// </summary>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
[DefaultValue(typeof(TaskRunLevel), "LUA")]
[XmlIgnore]
public TaskRunLevel RunLevel
{
get => v2Principal?.RunLevel ?? TaskRunLevel.LUA;
set
{
if (v2Principal != null)
v2Principal.RunLevel = value;
else if (value != TaskRunLevel.LUA)
throw new NotV1SupportedException();
}
}
/// <summary>
/// Gets or sets the user identifier that is required to run the tasks that are associated with the principal. Setting this property to something other
/// than a null or empty string, will set the <see cref="GroupId"/> property to NULL;
/// </summary>
[DefaultValue(null)]
public string UserId
{
get
{
if (v2Principal != null)
return v2Principal.UserId;
if (v1CachedAcctInfo == null)
{
try
{
string acct = v1Task.GetAccountInformation();
v1CachedAcctInfo = string.IsNullOrEmpty(acct) ? localSystemAcct : acct;
}
catch { v1CachedAcctInfo = string.Empty; }
}
return v1CachedAcctInfo == string.Empty ? null : v1CachedAcctInfo;
}
set
{
if (v2Principal != null)
{
if (string.IsNullOrEmpty(value))
value = null;
else
{
v2Principal.GroupId = null;
//if (value.Contains(@"\") && !value.Contains(@"\\"))
// value = value.Replace(@"\", @"\\");
}
v2Principal.UserId = value;
}
else
{
if (value.Equals(localSystemAcct, StringComparison.CurrentCultureIgnoreCase))
value = "";
v1Task.SetAccountInformation(value, IntPtr.Zero);
v1CachedAcctInfo = null;
}
}
}
/// <summary>Validates the supplied account against the supplied <see cref="TaskProcessTokenSidType"/>.</summary>
/// <param name="acct">The user or group account name.</param>
/// <param name="sidType">The SID type for the process.</param>
/// <returns><c>true</c> if supplied account can be used for the supplied SID type.</returns>
public static bool ValidateAccountForSidType(string acct, TaskProcessTokenSidType sidType)
{
string[] validUserIds = { "NETWORK SERVICE", "LOCAL SERVICE", "S-1-5-19", "S-1-5-20" };
return sidType == TaskProcessTokenSidType.Default || Array.Find(validUserIds, id => id.Equals(acct, StringComparison.InvariantCultureIgnoreCase)) != null;
}
/// <summary>Releases all resources used by this class.</summary>
public void Dispose()
{
if (v2Principal != null)
Marshal.ReleaseComObject(v2Principal);
v1Task = null;
}
/// <summary>Gets a value indicating whether current Principal settings require a password to be provided.</summary>
/// <value><c>true</c> if settings requires a password to be provided; otherwise, <c>false</c>.</value>
public bool RequiresPassword() => LogonType == TaskLogonType.InteractiveTokenOrPassword ||
LogonType == TaskLogonType.Password || LogonType == TaskLogonType.S4U && UserId != null && string.Compare(UserId, WindowsIdentity.GetCurrent().Name, StringComparison.OrdinalIgnoreCase) != 0;
/// <summary>Returns a <see cref="System.String"/> that represents this instance.</summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString() => LogonType == TaskLogonType.Group ? GroupId : UserId;
XmlSchema IXmlSerializable.GetSchema() => null;
void IXmlSerializable.ReadXml(XmlReader reader)
{
reader.ReadStartElement(XmlSerializationHelper.GetElementName(this), TaskDefinition.tns);
if (reader.HasAttributes)
Id = reader.GetAttribute("id");
reader.Read();
while (reader.MoveToContent() == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "Principal":
reader.Read();
XmlSerializationHelper.ReadObjectProperties(reader, this);
reader.ReadEndElement();
break;
default:
reader.Skip();
break;
}
}
reader.ReadEndElement();
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if (string.IsNullOrEmpty(ToString()) && LogonType == TaskLogonType.None) return;
writer.WriteStartElement("Principal");
if (!string.IsNullOrEmpty(Id))
writer.WriteAttributeString("id", Id);
XmlSerializationHelper.WriteObjectProperties(writer, this);
writer.WriteEndElement();
}
}
/// <summary>
/// List of security credentials for a principal under version 1.3 of the Task Scheduler. These security credentials define the security context for the
/// tasks that are associated with the principal.
/// </summary>
[PublicAPI]
public sealed class TaskPrincipalPrivileges : IList<TaskPrincipalPrivilege>
{
private IPrincipal2 v2Principal2;
internal TaskPrincipalPrivileges(IPrincipal2 iPrincipal2 = null)
{
v2Principal2 = iPrincipal2;
}
/// <summary>Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</summary>
/// <returns>The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</returns>
public int Count => v2Principal2?.RequiredPrivilegeCount ?? 0;
/// <summary>Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</summary>
/// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.</returns>
public bool IsReadOnly => false;
/// <summary>Gets or sets the element at the specified index.</summary>
/// <returns>The element at the specified index.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception>
/// <exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception>
public TaskPrincipalPrivilege this[int index]
{
get
{
if (v2Principal2 != null)
return (TaskPrincipalPrivilege)Enum.Parse(typeof(TaskPrincipalPrivilege), v2Principal2[index + 1]);
throw new IndexOutOfRangeException();
}
set => throw new NotImplementedException();
}
/// <summary>Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</summary>
/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
public void Add(TaskPrincipalPrivilege item)
{
if (v2Principal2 != null)
v2Principal2.AddRequiredPrivilege(item.ToString());
else
throw new NotSupportedPriorToException(TaskCompatibility.V2_1);
}
/// <summary>Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.</summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <returns>true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.</returns>
public bool Contains(TaskPrincipalPrivilege item) => IndexOf(item) != -1;
/// <summary>Copies to.</summary>
/// <param name="array">The array.</param>
/// <param name="arrayIndex">Index of the array.</param>
public void CopyTo(TaskPrincipalPrivilege[] array, int arrayIndex)
{
using (var pEnum = GetEnumerator())
{
for (var i = arrayIndex; i < array.Length; i++)
{
if (!pEnum.MoveNext())
break;
array[i] = pEnum.Current;
}
}
}
/// <summary>Returns an enumerator that iterates through the collection.</summary>
/// <returns>A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.</returns>
public IEnumerator<TaskPrincipalPrivilege> GetEnumerator() => new TaskPrincipalPrivilegesEnumerator(v2Principal2);
/// <summary>Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"/>.</summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"/>.</param>
/// <returns>The index of <paramref name="item"/> if found in the list; otherwise, -1.</returns>
public int IndexOf(TaskPrincipalPrivilege item)
{
for (var i = 0; i < Count; i++)
{
if (item == this[i])
return i;
}
return -1;
}
/// <summary>Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</summary>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
void ICollection<TaskPrincipalPrivilege>.Clear()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <summary>Inserts an item to the <see cref="T:System.Collections.Generic.IList`1"/> at the specified index.</summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1"/>.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception>
void IList<TaskPrincipalPrivilege>.Insert(int index, TaskPrincipalPrivilege item)
{
throw new NotImplementedException();
}
/// <summary>Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</summary>
/// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <returns>
/// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This
/// method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
bool ICollection<TaskPrincipalPrivilege>.Remove(TaskPrincipalPrivilege item)
{
throw new NotImplementedException();
}
/// <summary>Removes the <see cref="T:System.Collections.Generic.IList`1"/> item at the specified index.</summary>
/// <param name="index">The zero-based index of the item to remove.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception>
void IList<TaskPrincipalPrivilege>.RemoveAt(int index)
{
throw new NotImplementedException();
}
/// <summary>Enumerates the privileges set for a principal under version 1.3 of the Task Scheduler.</summary>
public sealed class TaskPrincipalPrivilegesEnumerator : IEnumerator<TaskPrincipalPrivilege>
{
private readonly IPrincipal2 v2Principal2;
private int cur;
internal TaskPrincipalPrivilegesEnumerator(IPrincipal2 iPrincipal2 = null)
{
v2Principal2 = iPrincipal2;
Reset();
}
/// <summary>Gets the element in the collection at the current position of the enumerator.</summary>
/// <returns>The element in the collection at the current position of the enumerator.</returns>
public TaskPrincipalPrivilege Current { get; private set; }
object IEnumerator.Current => Current;
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
public void Dispose() { }
/// <summary>Advances the enumerator to the next element of the collection.</summary>
/// <returns>true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.</returns>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created.</exception>
public bool MoveNext()
{
if (v2Principal2 != null && cur < v2Principal2.RequiredPrivilegeCount)
{
cur++;
Current = (TaskPrincipalPrivilege)Enum.Parse(typeof(TaskPrincipalPrivilege), v2Principal2[cur]);
return true;
}
Current = 0;
return false;
}
/// <summary>Sets the enumerator to its initial position, which is before the first element in the collection.</summary>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created.</exception>
public void Reset()
{
cur = 0;
Current = 0;
}
}
}
/// <summary>
/// Provides the administrative information that can be used to describe the task. This information includes details such as a description of the task, the
/// author of the task, the date the task is registered, and the security descriptor of the task.
/// </summary>
[XmlRoot("RegistrationInfo", Namespace = TaskDefinition.tns, IsNullable = true)]
[PublicAPI]
public sealed class TaskRegistrationInfo : IDisposable, IXmlSerializable
{
private ITask v1Task;
private IRegistrationInfo v2RegInfo;
internal TaskRegistrationInfo([NotNull] IRegistrationInfo iRegInfo)
{
v2RegInfo = iRegInfo;
}
internal TaskRegistrationInfo([NotNull] ITask iTask)
{
v1Task = iTask;
}
/// <summary>Gets or sets the author of the task.</summary>
[DefaultValue(null)]
public string Author
{
get => v2RegInfo != null ? v2RegInfo.Author : v1Task.GetCreator();
set
{
if (v2RegInfo != null)
v2RegInfo.Author = value;
else
v1Task.SetCreator(value);
}
}
/// <summary>Gets or sets the date and time when the task is registered.</summary>
[DefaultValue(typeof(DateTime), "0001-01-01T00:00:00")]
public DateTime Date
{
get
{
if (v2RegInfo != null)
{
if (DateTime.TryParse(v2RegInfo.Date, Trigger.DefaultDateCulture, DateTimeStyles.AssumeLocal, out var ret))
return ret;
}
else
{
var v1Path = Task.GetV1Path(v1Task);
if (!string.IsNullOrEmpty(v1Path) && File.Exists(v1Path))
return File.GetLastWriteTime(v1Path);
}
return DateTime.MinValue;
}
set
{
if (v2RegInfo != null)
v2RegInfo.Date = value == DateTime.MinValue ? null : value.ToString(Trigger.V2BoundaryDateFormat, Trigger.DefaultDateCulture);
else
{
var v1Path = Task.GetV1Path(v1Task);
if (!string.IsNullOrEmpty(v1Path) && File.Exists(v1Path))
File.SetLastWriteTime(v1Path, value);
}
}
}
/// <summary>Gets or sets the description of the task.</summary>
[DefaultValue(null)]
public string Description
{
get => v2RegInfo != null ? FixCrLf(v2RegInfo.Description) : v1Task.GetComment();
set
{
if (v2RegInfo != null)
v2RegInfo.Description = value;
else
v1Task.SetComment(value);
}
}
/// <summary>Gets or sets any additional documentation for the task.</summary>
[DefaultValue(null)]
public string Documentation
{
get => v2RegInfo != null ? FixCrLf(v2RegInfo.Documentation) : v1Task.GetDataItem(nameof(Documentation));
set
{
if (v2RegInfo != null)
v2RegInfo.Documentation = value;
else
v1Task.SetDataItem(nameof(Documentation), value);
}
}
/// <summary>Gets or sets the security descriptor of the task.</summary>
/// <value>The security descriptor.</value>
[XmlIgnore]
public GenericSecurityDescriptor SecurityDescriptor
{
get => new RawSecurityDescriptor(SecurityDescriptorSddlForm);
set => SecurityDescriptorSddlForm = value?.GetSddlForm(Task.defaultAccessControlSections);
}
/// <summary>Gets or sets the security descriptor of the task.</summary>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
[DefaultValue(null)]
[XmlIgnore]
public string SecurityDescriptorSddlForm
{
get
{
object sddl = null;
if (v2RegInfo != null)
sddl = v2RegInfo.SecurityDescriptor;
return sddl?.ToString();
}
set
{
if (v2RegInfo != null)
v2RegInfo.SecurityDescriptor = value;
else
throw new NotV1SupportedException();
}
}
/// <summary>Gets or sets where the task originated from. For example, a task may originate from a component, service, application, or user.</summary>
[DefaultValue(null)]
public string Source
{
get => v2RegInfo != null ? v2RegInfo.Source : v1Task.GetDataItem(nameof(Source));
set
{
if (v2RegInfo != null)
v2RegInfo.Source = value;
else
v1Task.SetDataItem(nameof(Source), value);
}
}
/// <summary>Gets or sets the URI of the task.</summary>
/// <remarks>
/// <c>Note:</c> Breaking change in version 2.0. This property was previously of type <see cref="Uri"/>. It was found that in Windows 8, many of the
/// native tasks use this property in a string format rather than in a URI format.
/// </remarks>
[DefaultValue(null)]
public string URI
{
get
{
var uri = v2RegInfo != null ? v2RegInfo.URI : v1Task.GetDataItem(nameof(URI));
return string.IsNullOrEmpty(uri) ? null : uri;
}
set
{
if (v2RegInfo != null)
v2RegInfo.URI = value;
else
v1Task.SetDataItem(nameof(URI), value);
}
}
/// <summary>Gets or sets the version number of the task.</summary>
[DefaultValueEx(typeof(Version), "1.0")]
public Version Version
{
get
{
var sver = v2RegInfo != null ? v2RegInfo.Version : v1Task.GetDataItem(nameof(Version));
if (sver != null) try { return new Version(sver); } catch { }
return new Version(1, 0);
}
set
{
if (v2RegInfo != null)
v2RegInfo.Version = value?.ToString();
else
v1Task.SetDataItem(nameof(Version), value.ToString());
}
}
/// <summary>Gets or sets an XML-formatted version of the registration information for the task.</summary>
[XmlIgnore]
public string XmlText
{
get => v2RegInfo != null ? v2RegInfo.XmlText : XmlSerializationHelper.WriteObjectToXmlText(this);
set
{
if (v2RegInfo != null)
v2RegInfo.XmlText = value;
else
XmlSerializationHelper.ReadObjectFromXmlText(value, this);
}
}
/// <summary>Releases all resources used by this class.</summary>
public void Dispose()
{
v1Task = null;
if (v2RegInfo != null)
Marshal.ReleaseComObject(v2RegInfo);
}
/// <summary>Returns a <see cref="System.String"/> that represents this instance.</summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString()
{
if (v2RegInfo != null || v1Task != null)
return DebugHelper.GetDebugString(this);
return base.ToString();
}
XmlSchema IXmlSerializable.GetSchema() => null;
void IXmlSerializable.ReadXml(XmlReader reader)
{
if (!reader.IsEmptyElement)
{
reader.ReadStartElement(XmlSerializationHelper.GetElementName(this), TaskDefinition.tns);
XmlSerializationHelper.ReadObjectProperties(reader, this, ProcessVersionXml);
reader.ReadEndElement();
}
else
reader.Skip();
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
XmlSerializationHelper.WriteObjectProperties(writer, this, ProcessVersionXml);
}
internal static string FixCrLf(string text) => text == null ? null : Regex.Replace(text, "\r?\n", "\r\n");
private bool ProcessVersionXml(PropertyInfo pi, object obj, ref object value)
{
if (pi.Name != "Version" || value == null) return false;
if (value is Version)
value = value.ToString();
else if (value is string)
value = new Version(value.ToString());
return true;
}
}
/// <summary>Provides the settings that the Task Scheduler service uses to perform the task.</summary>
[XmlRoot("Settings", Namespace = TaskDefinition.tns, IsNullable = true)]
[PublicAPI]
public sealed class TaskSettings : IDisposable, IXmlSerializable
{
private const uint InfiniteRunTimeV1 = 0xFFFFFFFF;
private IdleSettings idleSettings;
private MaintenanceSettings maintenanceSettings;
private NetworkSettings networkSettings;
private ITask v1Task;
private ITaskSettings v2Settings;
private ITaskSettings2 v2Settings2;
private ITaskSettings3 v2Settings3;
internal TaskSettings([NotNull] ITaskSettings iSettings)
{
v2Settings = iSettings;
try { v2Settings2 = (ITaskSettings2)v2Settings; }
catch { }
try { v2Settings3 = (ITaskSettings3)v2Settings; }
catch { }
}
internal TaskSettings([NotNull] ITask iTask)
{
v1Task = iTask;
}
/// <summary>Gets or sets a Boolean value that indicates that the task can be started by using either the Run command or the Context menu.</summary>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
[DefaultValue(true)]
[XmlElement("AllowStartOnDemand")]
[XmlIgnore]
public bool AllowDemandStart
{
get => v2Settings == null || v2Settings.AllowDemandStart;
set
{
if (v2Settings != null)
v2Settings.AllowDemandStart = value;
else
throw new NotV1SupportedException();
}
}
/// <summary>Gets or sets a Boolean value that indicates that the task may be terminated by using TerminateProcess.</summary>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
[DefaultValue(true)]
[XmlIgnore]
public bool AllowHardTerminate
{
get => v2Settings == null || v2Settings.AllowHardTerminate;
set
{
if (v2Settings != null)
v2Settings.AllowHardTerminate = value;
else
throw new NotV1SupportedException();
}
}
/// <summary>Gets or sets an integer value that indicates which version of Task Scheduler a task is compatible with.</summary>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
[XmlIgnore]
public TaskCompatibility Compatibility
{
get => v2Settings?.Compatibility ?? TaskCompatibility.V1;
set
{
if (v2Settings != null)
v2Settings.Compatibility = value;
else
if (value != TaskCompatibility.V1)
throw new NotV1SupportedException();
}
}
/// <summary>
/// Gets or sets the amount of time that the Task Scheduler will wait before deleting the task after it expires. If no value is specified for this
/// property, then the Task Scheduler service will not delete the task.
/// </summary>
/// <value>
/// Gets and sets the amount of time that the Task Scheduler will wait before deleting the task after it expires. A TimeSpan value of 1 second indicates
/// the task is set to delete when done. A value of TimeSpan.Zero indicates that the task should not be deleted.
/// </value>
/// <remarks>
/// A task expires after the end boundary has been exceeded for all triggers associated with the task. The end boundary for a trigger is specified by the
/// <c>EndBoundary</c> property of all trigger types.
/// </remarks>
[DefaultValue(typeof(TimeSpan), "12:00:00")]
public TimeSpan DeleteExpiredTaskAfter
{
get
{
if (v2Settings != null)
return v2Settings.DeleteExpiredTaskAfter == "PT0S" ? TimeSpan.FromSeconds(1) : Task.StringToTimeSpan(v2Settings.DeleteExpiredTaskAfter);
return v1Task.HasFlags(TaskFlags.DeleteWhenDone) ? TimeSpan.FromSeconds(1) : TimeSpan.Zero;
}
set
{
if (v2Settings != null)
v2Settings.DeleteExpiredTaskAfter = value == TimeSpan.FromSeconds(1) ? "PT0S" : Task.TimeSpanToString(value);
else
v1Task.SetFlags(TaskFlags.DeleteWhenDone, value >= TimeSpan.FromSeconds(1));
}
}
/// <summary>Gets or sets a Boolean value that indicates that the task will not be started if the computer is running on battery power.</summary>
[DefaultValue(true)]
public bool DisallowStartIfOnBatteries
{
get => v2Settings?.DisallowStartIfOnBatteries ?? v1Task.HasFlags(TaskFlags.DontStartIfOnBatteries);
set
{
if (v2Settings != null)
v2Settings.DisallowStartIfOnBatteries = value;
else
v1Task.SetFlags(TaskFlags.DontStartIfOnBatteries, value);
}
}
/// <summary>
/// Gets or sets a Boolean value that indicates that the task will not be started if the task is triggered to run in a Remote Applications Integrated
/// Locally (RAIL) session.
/// </summary>
/// <exception cref="NotSupportedPriorToException">Property set for a task on a Task Scheduler version prior to 2.1.</exception>
[DefaultValue(false)]
[XmlIgnore]
public bool DisallowStartOnRemoteAppSession
{
get
{
if (v2Settings2 != null)
return v2Settings2.DisallowStartOnRemoteAppSession;
if (v2Settings3 != null)
return v2Settings3.DisallowStartOnRemoteAppSession;
return false;
}
set
{
if (v2Settings2 != null)
v2Settings2.DisallowStartOnRemoteAppSession = value;
else if (v2Settings3 != null)
v2Settings3.DisallowStartOnRemoteAppSession = value;
else
throw new NotSupportedPriorToException(TaskCompatibility.V2_1);
}
}
/// <summary>Gets or sets a Boolean value that indicates that the task is enabled. The task can be performed only when this setting is TRUE.</summary>
[DefaultValue(true)]
public bool Enabled
{
get => v2Settings?.Enabled ?? !v1Task.HasFlags(TaskFlags.Disabled);
set
{
if (v2Settings != null)
v2Settings.Enabled = value;
else
v1Task.SetFlags(TaskFlags.Disabled, !value);
}
}
/// <summary>
/// Gets or sets the amount of time that is allowed to complete the task. By default, a task will be stopped 72 hours after it starts to run.
/// </summary>
/// <value>
/// The amount of time that is allowed to complete the task. When this parameter is set to <see cref="TimeSpan.Zero"/>, the execution time limit is infinite.
/// </value>
/// <remarks>
/// If a task is started on demand, the ExecutionTimeLimit setting is bypassed. Therefore, a task that is started on demand will not be terminated if it
/// exceeds the ExecutionTimeLimit.
/// </remarks>
[DefaultValue(typeof(TimeSpan), "3")]
public TimeSpan ExecutionTimeLimit
{
get
{
if (v2Settings != null)
return Task.StringToTimeSpan(v2Settings.ExecutionTimeLimit);
var ms = v1Task.GetMaxRunTime();
return ms == InfiniteRunTimeV1 ? TimeSpan.Zero : TimeSpan.FromMilliseconds(ms);
}
set
{
if (v2Settings != null)
v2Settings.ExecutionTimeLimit = value == TimeSpan.Zero ? "PT0S" : Task.TimeSpanToString(value);
else
{
// Due to an issue introduced in Vista, and propagated to Windows 7, setting the MaxRunTime to INFINITE results in the task only running for
// 72 hours. For these operating systems, setting the RunTime to "INFINITE - 1" gets the desired behavior of allowing an "infinite" run of
// the task.
var ms = value == TimeSpan.Zero ? InfiniteRunTimeV1 : Convert.ToUInt32(value.TotalMilliseconds);
v1Task.SetMaxRunTime(ms);
if (value == TimeSpan.Zero && v1Task.GetMaxRunTime() != InfiniteRunTimeV1)
v1Task.SetMaxRunTime(InfiniteRunTimeV1 - 1);
}
}
}
/// <summary>Gets or sets a Boolean value that indicates that the task will not be visible in the UI by default.</summary>
[DefaultValue(false)]
public bool Hidden
{
get => v2Settings?.Hidden ?? v1Task.HasFlags(TaskFlags.Hidden);
set
{
if (v2Settings != null)
v2Settings.Hidden = value;
else
v1Task.SetFlags(TaskFlags.Hidden, value);
}
}
/// <summary>Gets or sets the information that the Task Scheduler uses during Automatic maintenance.</summary>
[XmlIgnore]
[NotNull]
public MaintenanceSettings MaintenanceSettings => maintenanceSettings ?? (maintenanceSettings = new MaintenanceSettings(v2Settings3));
/// <summary>Gets or sets the policy that defines how the Task Scheduler handles multiple instances of the task.</summary>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
[DefaultValue(typeof(TaskInstancesPolicy), "IgnoreNew")]
[XmlIgnore]
public TaskInstancesPolicy MultipleInstances
{
get => v2Settings?.MultipleInstances ?? TaskInstancesPolicy.IgnoreNew;
set
{
if (v2Settings != null)
v2Settings.MultipleInstances = value;
else
throw new NotV1SupportedException();
}
}
/// <summary>Gets or sets the priority level of the task.</summary>
/// <value>The priority.</value>
/// <exception cref="NotV1SupportedException">Value set to AboveNormal or BelowNormal on Task Scheduler 1.0.</exception>
[DefaultValue(typeof(ProcessPriorityClass), "Normal")]
public ProcessPriorityClass Priority
{
get => v2Settings != null ? GetPriorityFromInt(v2Settings.Priority) : (ProcessPriorityClass)v1Task.GetPriority();
set
{
if (v2Settings != null)
{
v2Settings.Priority = GetPriorityAsInt(value);
}
else
{
if (value == ProcessPriorityClass.AboveNormal || value == ProcessPriorityClass.BelowNormal)
throw new NotV1SupportedException("Unsupported priority level on Task Scheduler 1.0.");
v1Task.SetPriority((uint)value);
}
}
}
/// <summary>Gets or sets the number of times that the Task Scheduler will attempt to restart the task.</summary>
/// <value>
/// The number of times that the Task Scheduler will attempt to restart the task. If this property is set, the <see cref="RestartInterval"/> property
/// must also be set.
/// </value>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
[DefaultValue(0)]
[XmlIgnore]
public int RestartCount
{
get => v2Settings?.RestartCount ?? 0;
set
{
if (v2Settings != null)
v2Settings.RestartCount = value;
else
throw new NotV1SupportedException();
}
}
/// <summary>Gets or sets a value that specifies how long the Task Scheduler will attempt to restart the task.</summary>
/// <value>
/// A value that specifies how long the Task Scheduler will attempt to restart the task. If this property is set, the <see cref="RestartCount"/> property
/// must also be set. The maximum time allowed is 31 days, and the minimum time allowed is 1 minute.
/// </value>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
[DefaultValue(typeof(TimeSpan), "00:00:00")]
[XmlIgnore]
public TimeSpan RestartInterval
{
get => v2Settings != null ? Task.StringToTimeSpan(v2Settings.RestartInterval) : TimeSpan.Zero;
set
{
if (v2Settings != null)
v2Settings.RestartInterval = Task.TimeSpanToString(value);
else
throw new NotV1SupportedException();
}
}
/// <summary>Gets or sets a Boolean value that indicates that the Task Scheduler will run the task only if the computer is in an idle condition.</summary>
[DefaultValue(false)]
public bool RunOnlyIfIdle
{
get => v2Settings?.RunOnlyIfIdle ?? v1Task.HasFlags(TaskFlags.StartOnlyIfIdle);
set
{
if (v2Settings != null)
v2Settings.RunOnlyIfIdle = value;
else
v1Task.SetFlags(TaskFlags.StartOnlyIfIdle, value);
}
}
/// <summary>Gets or sets a Boolean value that indicates that the Task Scheduler will run the task only if the user is logged on (v1.0 only)</summary>
/// <exception cref="NotV2SupportedException">Property set for a task on a Task Scheduler version other than 1.0.</exception>
[XmlIgnore]
public bool RunOnlyIfLoggedOn
{
get => v2Settings != null || v1Task.HasFlags(TaskFlags.RunOnlyIfLoggedOn);
set
{
if (v1Task != null)
v1Task.SetFlags(TaskFlags.RunOnlyIfLoggedOn, value);
else if (v2Settings != null)
throw new NotV2SupportedException("Task Scheduler 2.0 (1.2) does not support setting this property. You must use an InteractiveToken in order to have the task run in the current user session.");
}
}
/// <summary>Gets or sets a Boolean value that indicates that the Task Scheduler will run the task only when a network is available.</summary>
[DefaultValue(false)]
public bool RunOnlyIfNetworkAvailable
{
get => v2Settings?.RunOnlyIfNetworkAvailable ?? v1Task.HasFlags(TaskFlags.RunIfConnectedToInternet);
set
{
if (v2Settings != null)
v2Settings.RunOnlyIfNetworkAvailable = value;
else
v1Task.SetFlags(TaskFlags.RunIfConnectedToInternet, value);
}
}
/// <summary>Gets or sets a Boolean value that indicates that the Task Scheduler can start the task at any time after its scheduled time has passed.</summary>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
[DefaultValue(false)]
[XmlIgnore]
public bool StartWhenAvailable
{
get => v2Settings != null && v2Settings.StartWhenAvailable;
set
{
if (v2Settings != null)
v2Settings.StartWhenAvailable = value;
else
throw new NotV1SupportedException();
}
}
/// <summary>Gets or sets a Boolean value that indicates that the task will be stopped if the computer switches to battery power.</summary>
[DefaultValue(true)]
public bool StopIfGoingOnBatteries
{
get => v2Settings?.StopIfGoingOnBatteries ?? v1Task.HasFlags(TaskFlags.KillIfGoingOnBatteries);
set
{
if (v2Settings != null)
v2Settings.StopIfGoingOnBatteries = value;
else
v1Task.SetFlags(TaskFlags.KillIfGoingOnBatteries, value);
}
}
/// <summary>Gets or sets a Boolean value that indicates that the Unified Scheduling Engine will be utilized to run this task.</summary>
/// <exception cref="NotSupportedPriorToException">Property set for a task on a Task Scheduler version prior to 2.1.</exception>
[DefaultValue(false)]
[XmlIgnore]
public bool UseUnifiedSchedulingEngine
{
get
{
if (v2Settings2 != null)
return v2Settings2.UseUnifiedSchedulingEngine;
if (v2Settings3 != null)
return v2Settings3.UseUnifiedSchedulingEngine;
return false;
}
set
{
if (v2Settings2 != null)
v2Settings2.UseUnifiedSchedulingEngine = value;
else if (v2Settings3 != null)
v2Settings3.UseUnifiedSchedulingEngine = value;
else
throw new NotSupportedPriorToException(TaskCompatibility.V2_1);
}
}
/// <summary>Gets or sets a boolean value that indicates whether the task is automatically disabled every time Windows starts.</summary>
/// <exception cref="NotSupportedPriorToException">Property set for a task on a Task Scheduler version prior to 2.2.</exception>
[DefaultValue(false)]
[XmlIgnore]
public bool Volatile
{
get => v2Settings3 != null && v2Settings3.Volatile;
set
{
if (v2Settings3 != null)
v2Settings3.Volatile = value;
else
throw new NotSupportedPriorToException(TaskCompatibility.V2_2);
}
}
/// <summary>Gets or sets a Boolean value that indicates that the Task Scheduler will wake the computer when it is time to run the task.</summary>
[DefaultValue(false)]
public bool WakeToRun
{
get => v2Settings?.WakeToRun ?? v1Task.HasFlags(TaskFlags.SystemRequired);
set
{
if (v2Settings != null)
v2Settings.WakeToRun = value;
else
v1Task.SetFlags(TaskFlags.SystemRequired, value);
}
}
/// <summary>Gets or sets an XML-formatted definition of the task settings.</summary>
[XmlIgnore]
public string XmlText
{
get => v2Settings != null ? v2Settings.XmlText : XmlSerializationHelper.WriteObjectToXmlText(this);
set
{
if (v2Settings != null)
v2Settings.XmlText = value;
else
XmlSerializationHelper.ReadObjectFromXmlText(value, this);
}
}
/// <summary>Gets or sets the information that specifies how the Task Scheduler performs tasks when the computer is in an idle state.</summary>
[NotNull]
public IdleSettings IdleSettings => idleSettings ?? (idleSettings = v2Settings != null ? new IdleSettings(v2Settings.IdleSettings) : new IdleSettings(v1Task));
/// <summary>
/// Gets or sets the network settings object that contains a network profile identifier and name. If the RunOnlyIfNetworkAvailable property of
/// ITaskSettings is true and a network profile is specified in the NetworkSettings property, then the task will run only if the specified network
/// profile is available.
/// </summary>
[XmlIgnore]
[NotNull]
public NetworkSettings NetworkSettings => networkSettings ?? (networkSettings = new NetworkSettings(v2Settings?.NetworkSettings));
/// <summary>Releases all resources used by this class.</summary>
public void Dispose()
{
if (v2Settings != null)
Marshal.ReleaseComObject(v2Settings);
idleSettings = null;
networkSettings = null;
v1Task = null;
}
/// <summary>Returns a <see cref="System.String"/> that represents this instance.</summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString()
{
if (v2Settings != null || v1Task != null)
return DebugHelper.GetDebugString(this);
return base.ToString();
}
XmlSchema IXmlSerializable.GetSchema() => null;
void IXmlSerializable.ReadXml(XmlReader reader)
{
if (!reader.IsEmptyElement)
{
reader.ReadStartElement(XmlSerializationHelper.GetElementName(this), TaskDefinition.tns);
XmlSerializationHelper.ReadObjectProperties(reader, this, ConvertXmlProperty);
reader.ReadEndElement();
}
else
reader.Skip();
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
XmlSerializationHelper.WriteObjectProperties(writer, this, ConvertXmlProperty);
}
private bool ConvertXmlProperty(PropertyInfo pi, object obj, ref object value)
{
if (pi.Name == "Priority" && value != null)
{
if (value is int)
value = GetPriorityFromInt((int)value);
else if (value is ProcessPriorityClass)
value = GetPriorityAsInt((ProcessPriorityClass)value);
return true;
}
return false;
}
private int GetPriorityAsInt(ProcessPriorityClass value)
{
var p = 7;
switch (value)
{
case ProcessPriorityClass.AboveNormal:
p = 3;
break;
case ProcessPriorityClass.High:
p = 1;
break;
case ProcessPriorityClass.Idle:
p = 10;
break;
case ProcessPriorityClass.Normal:
p = 5;
break;
case ProcessPriorityClass.RealTime:
p = 0;
break;
// case ProcessPriorityClass.BelowNormal: default: break;
}
return p;
}
private ProcessPriorityClass GetPriorityFromInt(int value)
{
switch (value)
{
case 0:
return ProcessPriorityClass.RealTime;
case 1:
return ProcessPriorityClass.High;
case 2:
case 3:
return ProcessPriorityClass.AboveNormal;
case 4:
case 5:
case 6:
return ProcessPriorityClass.Normal;
// case 7: case 8:
default:
return ProcessPriorityClass.BelowNormal;
case 9:
case 10:
return ProcessPriorityClass.Idle;
}
}
}
internal static class DebugHelper
{
[SuppressMessage("Language", "CSE0003:Use expression-bodied members", Justification = "<Pending>")]
public static string GetDebugString(object inst)
{
#if DEBUG
var sb = new StringBuilder();
foreach (var pi in inst.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
if (pi.Name.StartsWith("Xml"))
continue;
var outval = pi.GetValue(inst, null);
if (outval != null)
{
var defval = XmlSerializationHelper.GetDefaultValue(pi);
if (!outval.Equals(defval))
{
var s = $"{pi.Name}:{outval}";
if (s.Length > 30) s = s.Remove(30);
sb.Append(s + "; ");
}
}
}
return sb.ToString();
#else
return inst.GetType().ToString();
#endif
}
}
internal static class TSInteropExt
{
public static string GetDataItem(this ITask v1Task, string name)
{
TaskDefinition.GetV1TaskDataDictionary(v1Task).TryGetValue(name, out var ret);
return ret;
}
public static bool HasFlags(this ITask v1Task, TaskFlags flags) => v1Task.GetFlags().IsFlagSet(flags);
public static void SetDataItem(this ITask v1Task, string name, string value)
{
var d = TaskDefinition.GetV1TaskDataDictionary(v1Task);
d[name] = value;
TaskDefinition.SetV1TaskData(v1Task, d);
}
public static void SetFlags(this ITask v1Task, TaskFlags flags, bool value = true)
{
v1Task.SetFlags(v1Task.GetFlags().SetFlags(flags, value));
}
}
internal class DefaultValueExAttribute : DefaultValueAttribute
{
public DefaultValueExAttribute(Type type, string value) : base(null)
{
try
{
if (type == typeof(Version))
{
SetValue(new Version(value));
return;
}
SetValue(TypeDescriptor.GetConverter(type).ConvertFromInvariantString(value));
}
catch
{
Debug.Fail("Default value attribute of type " + type.FullName + " threw converting from the string '" + value + "'.");
}
}
}
} | 40.543453 | 272 | 0.691583 | [
"MIT"
] | basheermohamed/taskscheduler | TaskService/Task.cs | 141,840 | C# |
using JT1078.Protocol.Enums;
using JT1078.Protocol.H264;
using JT1078.Protocol.MessagePack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using JT1078.Protocol;
using JT1078.Hls.MessagePack;
using JT1078.Hls.Enums;
using System.Collections.Concurrent;
using System.Security.Cryptography;
[assembly: InternalsVisibleTo("JT1078.Hls.Test")]
namespace JT1078.Hls
{
/// <summary>
/// 1.PAT
/// 2.PMT
/// 3.PES
/// </summary>
public class TSEncoder
{
private const int FiexdSegmentPESLength = 184;
private const int FiexdTSLength = 188;
private ConcurrentDictionary<string, byte> PATCounter = new ConcurrentDictionary<string, byte>();
private ConcurrentDictionary<string, byte> PMTCounter = new ConcurrentDictionary<string, byte>();
private ConcurrentDictionary<string, byte> VideoCounter = new ConcurrentDictionary<string, byte>();
//private ConcurrentDictionary<string, byte> AudioCounter = new ConcurrentDictionary<string, byte>();
public byte[] CreatePAT(JT1078Package jt1078Package, int minBufferSize = 188)
{
byte[] buffer = TSArrayPool.Rent(minBufferSize);
try
{
TS_PAT_Package package = new TS_PAT_Package();
package.Header = new TS_Header();
package.Header.ContinuityCounter = PATCounter.AddOrUpdate(jt1078Package.GetKey(), 0, (a, b) =>
{
if (b > 0xf)
{
return 0;
}
else
{
return (byte)(b +1);
}
});
package.Header.AdaptationFieldControl = AdaptationFieldControl.无自适应域_仅含有效负载;
package.Header.PayloadUnitStartIndicator = 1;
package.Header.PID = 0;
TSMessagePackWriter messagePackReader = new TSMessagePackWriter(buffer);
package.ToBuffer(ref messagePackReader);
return messagePackReader.FlushAndGetArray();
}
finally
{
TSArrayPool.Return(buffer);
}
}
public byte[] CreatePMT(JT1078Package jt1078Package, int minBufferSize = 188)
{
byte[] buffer = TSArrayPool.Rent(minBufferSize);
try
{
TS_PMT_Package package = new TS_PMT_Package();
package.Header = new TS_Header();
package.Header.ContinuityCounter = PMTCounter.AddOrUpdate(jt1078Package.GetKey(), 0, (a, b) =>
{
if (b > 0xf)
{
return 0;
}
else
{
return (byte)(b + 1);
}
});
package.Header.AdaptationFieldControl = AdaptationFieldControl.无自适应域_仅含有效负载;
package.Header.PayloadUnitStartIndicator = 1;
package.Header.PID = 4096;
package.TableId = 0x02;
package.Components = new List<TS_PMT_Component>();
package.Components.Add(new TS_PMT_Component
{
StreamType= StreamType.h264,
ElementaryPID = 256,
ESInfoLength=0
});
TSMessagePackWriter messagePackReader = new TSMessagePackWriter(buffer);
package.ToBuffer(ref messagePackReader);
return messagePackReader.FlushAndGetArray();
}
finally
{
TSArrayPool.Return(buffer);
}
}
public byte[] CreatePES(JT1078Package jt1078Package, int minBufferSize = 188)
{
//将1078一帧的数据拆分成一小段一小段的PES包
byte[] buffer = TSArrayPool.Rent(jt1078Package.Bodies.Length + minBufferSize);
TSMessagePackWriter messagePackReader = new TSMessagePackWriter(buffer);
//TSHeader + Adaptation + PES1
//TSHeader + PES2
//TSHeader + Adaptation + PESN
try
{
int totalLength = 0;
TS_Package package = new TS_Package();
package.Header = new TS_Header();
//ts header 4
totalLength += 4;
package.Header.PID = 256;
string key = jt1078Package.GetKey();
if (VideoCounter.TryGetValue(key, out byte counter))
{
if (counter > 0xf)
{
counter = 0;
}
package.Header.ContinuityCounter = counter++;
VideoCounter.TryUpdate(key, counter, counter);
}
else
{
package.Header.ContinuityCounter = counter++;
VideoCounter.TryAdd(key, counter);
}
package.Header.PayloadUnitStartIndicator = 1;
package.Header.Adaptation = new TS_AdaptationInfo();
package.Payload = new PES_Package();
package.Payload.StreamId = 0xe0;
package.Payload.PESPacketLength = 0;
//PESStartCode + StreamId + PESPacketLength
//3 + 1 + 2
totalLength += (3+1+2);
package.Payload.PTS_DTS_Flag = PTS_DTS_Flags.all;
if (jt1078Package.Label3.DataType== JT1078DataType.视频I帧)
{
//ts header adaptation
//PCRIncluded + PCR
//1 + 5
totalLength += (1 + 5);
package.Header.Adaptation.PCRIncluded = PCRInclude.包含;
package.Header.Adaptation.PCR = jt1078Package.LastIFrameInterval;
package.Payload.DTS = jt1078Package.LastIFrameInterval;
package.Payload.PTS = jt1078Package.LastIFrameInterval;
}
else
{
//ts header adaptation
//PCRIncluded
//1
totalLength += 1;
package.Header.Adaptation.PCRIncluded = PCRInclude.不包含;
package.Payload.DTS = jt1078Package.LastFrameInterval;
package.Payload.PTS = jt1078Package.LastFrameInterval;
}
//Flag1 + PTS_DTS_Flag + DTS + PTS
//1 + 1 + 5 + 5
totalLength += 12;
//根据计算剩余的长度进行是否需要填充第一包
var remainingLength = FiexdTSLength - totalLength;
int index = 0;
//情况1:1078的第一包不够剩余(remainingLength)字节
//情况2:1078的第一包比剩余(remainingLength)字节多
//情况3: 1078的第一包等于剩余(remainingLength)字节
//填充大小
int fullSize = jt1078Package.Bodies.Length - remainingLength;
package.Payload.Payload = new ES_Package();
if (fullSize < 0)
{
//这个很重要,需要控制
package.Header.AdaptationFieldControl = AdaptationFieldControl.同时带有自适应域和有效负载;
//还差一点
fullSize = Math.Abs(fullSize);
package.Header.Adaptation.FillSize = (byte)fullSize;
package.Payload.Payload.NALUs = new List<byte[]>() { jt1078Package.Bodies };
package.ToBuffer(ref messagePackReader);
}
else if(fullSize==0)
{
//这个很重要,需要控制
package.Header.AdaptationFieldControl = AdaptationFieldControl.无自适应域_仅含有效负载;
//刚刚好
package.Header.Adaptation.FillSize = 0;
package.Payload.Payload.NALUs = new List<byte[]>() { jt1078Package.Bodies };
package.ToBuffer(ref messagePackReader);
}
else
{
//这个很重要,需要控制
package.Header.AdaptationFieldControl = AdaptationFieldControl.同时带有自适应域和有效负载;
//太多了,需要拆分
package.Header.Adaptation.FillSize = 0;
package.Payload.Payload.NALUs = new List<byte[]>();
ReadOnlySpan<byte> dataReader = jt1078Package.Bodies;
package.Payload.Payload.NALUs.Add(dataReader.Slice(index, remainingLength).ToArray());
index += remainingLength;
package.ToBuffer(ref messagePackReader);
while(index!= jt1078Package.Bodies.Length)
{
if (counter > 0xf)
{
counter = 0;
}
int segmentFullSize = jt1078Package.Bodies.Length - index;
if(segmentFullSize >= FiexdSegmentPESLength)
{
CreateSegmentPES(ref messagePackReader, dataReader.Slice(index, FiexdSegmentPESLength).ToArray(), counter++);
}
else
{
CreateSegmentPES(ref messagePackReader, dataReader.Slice(index, segmentFullSize).ToArray(), counter++);
index += segmentFullSize;
}
}
VideoCounter.TryUpdate(key, counter, counter);
}
return messagePackReader.FlushAndGetArray();
}
finally
{
TSArrayPool.Return(buffer);
}
}
internal void CreateSegmentPES(ref TSMessagePackWriter writer,byte[] nalu, byte counter)
{
TS_Segment_Package package = new TS_Segment_Package();
package.Header = new TS_Header();
package.Header.PID = 256;
package.Header.ContinuityCounter = counter;
package.Header.PayloadUnitStartIndicator = 0;
package.Payload = nalu;
//这个很重要,需要控制
//package.Header.AdaptationFieldControl= AdaptationFieldControl.同时带有自适应域和有效负载
//这个很重要,填充大小
//package.Header.Adaptation.FillSize
if (nalu.Length < FiexdSegmentPESLength)
{
package.Header.Adaptation = new TS_AdaptationInfo();
package.Header.Adaptation.PCRIncluded = PCRInclude.不包含;
package.Header.Adaptation.FillSize = (byte)(FiexdSegmentPESLength - nalu.Length);
package.Header.AdaptationFieldControl = AdaptationFieldControl.同时带有自适应域和有效负载;
}
else
{
package.Header.AdaptationFieldControl = AdaptationFieldControl.无自适应域_仅含有效负载;
}
package.Payload = nalu;
package.ToBuffer(ref writer);
}
}
}
| 43.11284 | 137 | 0.516426 | [
"MIT"
] | ewsq/JT1078 | src/JT1078.Hls/TSEncoder.cs | 11,580 | C# |
using Newtonsoft.Json;
using SimpleChecklist.Common;
using SimpleChecklist.Common.Interfaces.Utils;
using SimpleChecklist.Core.DTOs;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace SimpleChecklist.Core.Repositories
{
public class BackupRepository
{
private readonly IDateTimeProvider _dateTimeProvider;
private readonly Func<string, IDirectoryFilesReader> _directoryFrFunc;
private readonly Func<string, IFile> _fileFunc;
public BackupRepository(Func<string, IFile> fileFunc, Func<string, IDirectoryFilesReader> directoryFrFunc, IDateTimeProvider dateTimeProvider)
{
_fileFunc = fileFunc;
_directoryFrFunc = directoryFrFunc;
_dateTimeProvider = dateTimeProvider;
}
public async Task CreateBackupAsync()
{
var appDataFile = _fileFunc(AppSettings.ApplicationDataFileName);
if (!appDataFile.Exist)
{
return;
}
await RemoveOldBackupsAsync(int.Parse(AppSettings.BackupsLimit));
var backupFile = _fileFunc($"{AppSettings.BackupsDir}\\{_dateTimeProvider.UtcNow:yyyy-MM-ddTHHmmssZ}{AppSettings.ApplicationDataFileName}");
await appDataFile.CopyFileAsync(backupFile);
}
public async Task<bool> RestoreLastBackupAsync()
{
var backupsDir = _directoryFrFunc(AppSettings.BackupsDir);
if (!backupsDir.Exist)
{
return false;
}
var backups = (await backupsDir.GetFilesAsync())
.Where(file => file.NameWithExtension.EndsWith(AppSettings.ApplicationDataFileName))
.OrderByDescending(file => file.NameWithExtension);
foreach (var backup in backups)
{
var serializedData = await backup.ReadTextAsync();
var fileData = JsonConvert.DeserializeObject<FileData>(serializedData);
if (fileData?.ToDoItems?.Any() == true || fileData?.DoneItems?.Any() == true)
{
await backup.CopyFileAsync(_fileFunc(AppSettings.ApplicationDataFileName));
return true;
}
}
return false;
}
private async Task RemoveOldBackupsAsync(int limit)
{
var backupsDir = _directoryFrFunc(AppSettings.BackupsDir);
if (!backupsDir.Exist)
{
return;
}
var backupsToRemove = (await backupsDir.GetFilesAsync())
.Where(file => file.NameWithExtension.EndsWith(AppSettings.ApplicationDataFileName))
.OrderByDescending(file => file.NameWithExtension)
.Skip(limit - 1); // - 1 because we will create one more backup after this method is called
foreach (var backupToRemove in backupsToRemove)
{
await backupToRemove.DeleteAsync();
}
}
}
} | 36.059524 | 152 | 0.615054 | [
"MIT"
] | metem/SimpleChecklist | SimpleChecklist/SimpleChecklist.Core/Repositories/BackupRepository.cs | 3,031 | C# |
//------------------------------------------------------------------------------
// <copyright file="PrologCodeVariable.cs" company="Axiom">
//
// Copyright (c) 2006 Ali Hodroj. All rights reserved.
//
// The use and distribution terms for this source code are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
// </copyright>
//------------------------------------------------------------------------------
namespace Axiom.Compiler.CodeObjectModel
{
using System;
/// <summary>
/// Represents a Prolog variable.
/// </summary>
public class PrologCodeVariable
: PrologCodeTerm
{
private string _name;
public PrologCodeVariable (string name)
{
this._name = name;
}
public string Name
{
get
{
return this._name;
}
}
public override string ToString()
{
return _name;
}
}
} | 25.574468 | 85 | 0.509151 | [
"MIT"
] | FacticiusVir/prologdotnet | Prolog.Compiler/CodeObjectModel/PrologCodeVariable.cs | 1,202 | C# |
namespace Parrot.Renderers.Infrastructure
{
using System.IO;
public interface IPathResolver
{
Stream OpenFile(string path);
bool FileExists(string path);
string ResolvePath(string path);
string ResolveAttributeRelativePath(string key, object value);
}
} | 26.166667 | 71 | 0.66242 | [
"MIT"
] | ParrotFx/Parrot | src/Parrot.Renderers/Infrastructure/IPathResolver.cs | 316 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="UpdateBindingOnTextChanged.cs" company="Catel development team">
// Copyright (c) 2008 - 2014 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
#if !WIN80 && !XAMARIN
namespace Catel.Windows.Interactivity
{
using System;
#if NETFX_CORE
using global::Windows.UI.Xaml;
using global::Windows.UI.Xaml.Controls;
using UIEventArgs = global::Windows.UI.Xaml.RoutedEventArgs;
using TimerTickEventArgs = System.Object;
#else
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Threading;
using UIEventArgs = System.EventArgs;
using TimerTickEventArgs = System.EventArgs;
#endif
/// <summary>
/// This behavior automatically updates the binding of a <see cref="TextBox"/> when the
/// <c>TextChanged</c> event occurs.
/// </summary>
public class UpdateBindingOnTextChanged : UpdateBindingBehaviorBase<TextBox>
{
#region Fields
private readonly DispatcherTimer _timer;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBindingOnTextChanged"/> class.
/// </summary>
public UpdateBindingOnTextChanged()
: base("Text")
{
UpdateDelay = 250;
_timer = new DispatcherTimer();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the update delay.
/// <para/>
/// This is the value that is used between updates in milliseconds. The binding will be updated
/// when no new text change event is detected within the delay.
/// <para/>
/// The default value is <c>250</c>. If the value is smaller than <c>50</c>, the value
/// will be ignored and there will be no delay between the key down and the binding update. If the
/// value is higher than <c>5000</c>, it will be set to <c>5000</c>.
/// </summary>
/// <value>The update delay.</value>
public int UpdateDelay { get; set; }
#endregion
#region Methods
/// <summary>
/// Called when the <see cref="Behavior{T}.AssociatedObject"/> is loaded.
/// </summary>
protected override void OnAssociatedObjectLoaded()
{
AssociatedObject.TextChanged += OnAssociatedObjectTextChanged;
_timer.Tick += OnTimerTick;
}
/// <summary>
/// Called when the <see cref="Behavior{T}.AssociatedObject"/> is unloaded.
/// </summary>
protected override void OnAssociatedObjectUnloaded()
{
_timer.Stop();
_timer.Tick -= OnTimerTick;
AssociatedObject.TextChanged -= OnAssociatedObjectTextChanged;
}
/// <summary>
/// Called when the <c>TextChanged</c> event occurs.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The text change event args instance containing the event data.</param>
private void OnAssociatedObjectTextChanged(object sender, TextChangedEventArgs e)
{
if (UpdateDelay < 50)
{
UpdateBinding();
return;
}
if (UpdateDelay > 5000)
{
UpdateDelay = 5000;
}
if (_timer.IsEnabled)
{
_timer.Stop();
}
_timer.Interval = new TimeSpan(0, 0, 0, 0, UpdateDelay);
_timer.Start();
}
/// <summary>
/// Called when timer ticks.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void OnTimerTick(object sender, TimerTickEventArgs e)
{
_timer.Stop();
UpdateBinding();
}
#endregion
}
}
#endif | 33.21875 | 120 | 0.548213 | [
"MIT"
] | IvanKupriyanov/Catel | src/Catel.MVVM/Catel.MVVM.Shared/Windows/Interactivity/Behaviors/UpdateBindingOnTextChanged.cs | 4,254 | C# |
//--------------------------------------------------
// Motion Framework
// Copyright©2018-2021 何冠峰
// Licensed under the MIT license
//--------------------------------------------------
using System.Collections.Generic;
using System;
namespace MotionFramework.Resource
{
internal abstract class FileLoaderBase
{
/// <summary>
/// 资源文件信息
/// </summary>
public AssetBundleInfo BundleInfo { get; private set; }
/// <summary>
/// 引用计数
/// </summary>
public int RefCount { get; private set; }
/// <summary>
/// 加载状态
/// </summary>
public ELoaderStates States { get; protected set; }
/// <summary>
/// 是否为场景加载器
/// </summary>
public bool IsSceneLoader { private set; get; } = false;
/// <summary>
/// 是否已经销毁
/// </summary>
public bool IsDestroyed { private set; get; } = false;
public FileLoaderBase(AssetBundleInfo bundleInfo)
{
BundleInfo = bundleInfo;
RefCount = 0;
States = ELoaderStates.None;
}
/// <summary>
/// 引用(引用计数递加)
/// </summary>
protected virtual void Reference()
{
RefCount++;
}
/// <summary>
/// 释放(引用计数递减)
/// </summary>
protected virtual void Release()
{
RefCount--;
}
/// <summary>
/// 轮询更新
/// </summary>
public virtual void Update()
{
if(CheckFileLoadDone())
{
UpdateProviders();
}
}
/// <summary>
/// 销毁
/// </summary>
public virtual void Destroy(bool checkFatal)
{
IsDestroyed = true;
}
/// <summary>
/// 是否可以销毁
/// </summary>
public bool CanDestroy()
{
if (IsDone() == false)
return false;
if (RefCount <= 0 && _providers.Count == 0)
return true;
else
return false;
}
/// <summary>
/// 是否完毕(无论成功失败)
/// </summary>
public bool IsDone()
{
if (CheckFileLoadDone())
return CheckProvidersDone();
else
return false;
}
/// <summary>
/// 文件加载是否完毕
/// </summary>
public bool CheckFileLoadDone()
{
return States == ELoaderStates.Success || States == ELoaderStates.Fail;
}
/// <summary>
/// 主线程等待异步操作完毕
/// </summary>
public abstract void WaitForAsyncComplete();
#region Asset Provider
private readonly List<IAssetProvider> _providers = new List<IAssetProvider>();
/// <summary>
/// 调试接口
/// </summary>
internal List<IAssetProvider> GetProviders()
{
return _providers;
}
/// <summary>
/// 异步加载场景
/// </summary>
/// <param name="sceneName">场景名称</param>
public AssetOperationHandle LoadSceneAsync(string sceneName, SceneInstanceParam instanceParam)
{
IAssetProvider provider = TryGetProvider(sceneName);
if (provider == null)
{
IsSceneLoader = true;
provider = new AssetSceneProvider(this, sceneName, instanceParam);
_providers.Add(provider);
}
// 引用计数增加
provider.Reference();
return provider.Handle;
}
/// <summary>
/// 异步加载资源对象
/// </summary>
/// <param name="assetName">资源名称</param>
/// <param name="assetType">资源类型</param>
/// <param name="syncLoadMode">同步加载模式</param>
public AssetOperationHandle LoadAssetAsync(string assetName, System.Type assetType, bool syncLoadMode)
{
IAssetProvider provider = TryGetProvider(assetName);
if (provider == null)
{
if (this is AssetBundleLoader)
provider = new AssetBundleProvider(this, assetName, assetType);
else if (this is AssetDatabaseLoader)
provider = new AssetDatabaseProvider(this, assetName, assetType);
else
throw new NotImplementedException($"{this.GetType()}");
_providers.Add(provider);
}
// 异步转同步
if (syncLoadMode)
{
provider.SetSyncLoadMode();
}
// 引用计数增加
provider.Reference();
return provider.Handle;
}
/// <summary>
/// 异步加载所有子资源对象
/// </summary>
/// <param name="assetName">资源名称</param>
/// <param name="assetType">资源类型</param>、
/// <param name="syncLoadMode">同步加载模式</param>
public AssetOperationHandle LoadSubAssetsAsync(string assetName, System.Type assetType, bool syncLoadMode)
{
IAssetProvider provider = TryGetProvider(assetName);
if (provider == null)
{
if (this is AssetBundleLoader)
provider = new AssetBundleSubProvider(this, assetName, assetType);
else if (this is AssetDatabaseLoader)
provider = new AssetDatabaseSubProvider(this, assetName, assetType);
else
throw new NotImplementedException($"{this.GetType()}");
_providers.Add(provider);
}
// 异步转同步
if (syncLoadMode)
{
provider.SetSyncLoadMode();
}
// 引用计数增加
provider.Reference();
return provider.Handle;
}
/// <summary>
/// 检测所有的资源提供者是否完毕
/// </summary>
private bool CheckProvidersDone()
{
for (int i = 0; i < _providers.Count; i++)
{
var provider = _providers[i];
if (provider.IsDone == false)
return false;
}
return true;
}
/// <summary>
/// 轮询更新所有的资源提供者
/// </summary>
private void UpdateProviders()
{
for (int i = _providers.Count - 1; i >= 0; i--)
{
var provider = _providers[i];
provider.Update();
// 检测是否可以销毁
if (provider.CanDestroy())
{
provider.Destory();
_providers.RemoveAt(i);
}
}
}
/// <summary>
/// 获取一个资源提供者
/// </summary>
private IAssetProvider TryGetProvider(string assetName)
{
IAssetProvider provider = null;
for (int i = 0; i < _providers.Count; i++)
{
IAssetProvider temp = _providers[i];
if (temp.AssetName.Equals(assetName))
{
provider = temp;
break;
}
}
return provider;
}
#endregion
}
} | 20.719697 | 108 | 0.618099 | [
"MIT"
] | ArcherPeng/MotionFramework | Assets/MotionFramework/Scripts/Runtime/Engine/Engine.Resource/Loader/FileLoaderBase.cs | 5,927 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System;
namespace Game
{
public abstract class Task : MonoBehaviour
{
public GameObject taskContent;
public bool isCompleted;
private void CheckTask(PlayerScript player)
{
if (!isCompleted)
{
if (Input.GetKeyDown(KeyCode.E) || Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.Return))
{
TaskContent(player);
}
}
}
public virtual void TaskContent(PlayerScript player)
{
isCompleted = false;
taskContent.SetActive(true);
PlayerStaticVars.state = clientState.showingUI;
}
public virtual void TaskCompleted(PlayerScript player)
{
isCompleted = true;
taskContent.SetActive(false);
PlayerStaticVars.state = clientState.showingGameplay;
FindObjectOfType<TaskManager>().AddCompletedTask();
player.RemoveTask(this);
}
private void OnTriggerEnter2D(Collider2D collision)
{
PlayerScript player = collision.gameObject.GetComponent<PlayerScript>();
if (player != null)
{
if (player.playerType.Equals(PlayerType.crewmate))
{
if (player.playerTasks.Contains(this))
{
AddTaskToListener(player);
}
}
}
}
void AddTaskToListener(PlayerScript player)
{
if (player.isLocalPlayer)
{
player.taskAction += delegate { CheckTask(player); };
}
}
private void OnTriggerExit2D(Collider2D collision)
{
PlayerScript player = collision.gameObject.GetComponent<PlayerScript>();
if (player != null)
{
if (player.playerType.Equals(PlayerType.crewmate))
{
if ((Array.Find(player.playerTasks.ToArray(), taskk => taskk == this)) != null)
{
DeleteTaskFromListener(player);
}
}
}
}
void DeleteTaskFromListener(PlayerScript player)
{
if (player.isLocalPlayer)
{
player.taskAction -= delegate { CheckTask(player); };
}
}
public void SetButton(Button button, UnityAction action)
{
button.onClick.RemoveAllListeners();
button.onClick.AddListener(action);
}
}
}
| 31.850575 | 119 | 0.525442 | [
"Unlicense"
] | SophieNe/Among-Us-En-24-Horas | Assets/Task.cs | 2,773 | C# |
using Akka.Actor;
using Lyra.Core.API;
using Lyra.Core.Blocks;
using Lyra.Core.Cryptography;
using Lyra.Core.Decentralize;
using Lyra.Core.Utils;
using Lyra.Shared;
using Microsoft.Extensions.Logging;
using Neo;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Lyra.Core.Decentralize
{
public class ConsensusWorker
{
ConsensusService _context;
ILogger _log;
private AuthorizersFactory _authorizers;
ConcurrentQueue<SourceSignedMessage> _outOfOrderedMessages;
AuthState _state;
public AuthState State { get => _state; set => _state = value; }
public ConsensusWorker(ConsensusService context)
{
_context = context;
_log = new SimpleLogger("ConsensusWorker").Logger;
_authorizers = new AuthorizersFactory();
_outOfOrderedMessages = new ConcurrentQueue<SourceSignedMessage>();
}
public void Create(AuthState state, WaitHandle waitHandle = null)
{
_state = state;
//_log.LogInformation($"Receive AuthState: {_state.InputMsg.Block.UIndex}/{_state.InputMsg.Block.Index}/{_state.InputMsg.Block.Hash}");
_ = Task.Run(async () =>
{
if (waitHandle != null)
{
_log.LogWarning($"Consensus Create: Wait for previous block to get its consensus result...");
await waitHandle.AsTask();
}
_context.Send2P2pNetwork(_state.InputMsg);
state.T1 = DateTime.Now;
await AuthorizeAsync(_state.InputMsg);
state.T2 = DateTime.Now;
});
}
private async Task<AuthState> CreateAuthringStateAsync(AuthorizingMsg item)
{
_log.LogInformation($"Consensus: CreateAuthringState Called: BlockIndex: {item.Block.Height}");
var ukey = item.Block.Hash;
//if (_activeConsensus.ContainsKey(ukey))
//{
// return _activeConsensus[ukey];
//}
var state = new AuthState();
state.SetView(await BlockChain.Singleton.GetLastServiceBlockAsync());
state.InputMsg = item;
//// add possible out of ordered messages belong to the block
//if (_outOfOrderedMessages.ContainsKey(item.Block.Hash))
//{
// var msgs = _outOfOrderedMessages[item.Block.Hash];
// _outOfOrderedMessages.Remove(item.Block.Hash);
// foreach (var msg in msgs)
// {
// switch (msg)
// {
// case AuthorizedMsg authorized:
// state.AddAuthResult(authorized);
// break;
// case AuthorizerCommitMsg committed:
// state.AddCommitedResult(committed);
// break;
// }
// }
//}
// check if block existing
//if (null != BlockChain.Singleton.FindBlockByHash(item.Block.Hash))
//{
// _log.LogInformation("CreateAuthringState: Block is already in database.");
// return null;
//}
// check if block was replaced by nulltrans
//if (null != BlockChain.Singleton.FindNullTransBlockByHash(item.Block.Hash))
//{
// _log.LogInformation("CreateAuthringState: Block is already consolidated by nulltrans.");
// return null;
//}
//_activeConsensus.Add(ukey, state);
return state;
}
private async Task<AuthorizedMsg> LocalAuthorizingAsync(AuthorizingMsg item)
{
////_log.LogInformation($"LocalAuthorizingAsync: {item.Block.BlockType} {item.Block.UIndex}/{item.Block.Index}/{item.Block.Hash}");
var errCode = APIResultCodes.Success;
//if (!ConsensusService.Board.CanDoConsensus)
//{
// errCode = APIResultCodes.PBFTNetworkNotReadyForConsensus;
//}
//else if(!ConsensusService.AuthorizerShapshot.Contains(NodeService.Instance.PosWallet.AccountId))
//{
// errCode = APIResultCodes.NotListedAsQualifiedAuthorizer;
//}
if(errCode != APIResultCodes.Success)
{
var result0 = new AuthorizedMsg
{
From = NodeService.Instance.PosWallet.AccountId,
MsgType = ChatMessageType.AuthorizerPrepare,
BlockHash = item.Block.Hash,
Result = errCode
};
return result0;
}
var stopwatch = Stopwatch.StartNew();
var authorizer = _authorizers.Create(item.Block.BlockType);
AuthorizedMsg result;
try
{
var localAuthResult = await authorizer.AuthorizeAsync(item.Block);
result = new AuthorizedMsg
{
From = NodeService.Instance.PosWallet.AccountId,
MsgType = ChatMessageType.AuthorizerPrepare,
BlockHash = item.Block.Hash,
Result = localAuthResult.Item1,
AuthSign = localAuthResult.Item2
};
_log.LogInformation($"Index {item.Block.Height} of block {item.Block.Hash.Shorten()} of Type {item.Block.BlockType}");
}
catch (Exception e)
{
_log.LogWarning($"Consensus: LocalAuthorizingAsync Exception: {e.Message} BlockIndex: {item.Block.Height}");
result = new AuthorizedMsg
{
From = NodeService.Instance.PosWallet.AccountId,
MsgType = ChatMessageType.AuthorizerPrepare,
BlockHash = item.Block.Hash,
Result = APIResultCodes.UnknownError,
AuthSign = null
};
}
stopwatch.Stop();
if (result.Result == APIResultCodes.Success)
_log.LogInformation($"LocalAuthorizingAsync {item.Block.BlockType} takes {stopwatch.ElapsedMilliseconds} ms with {result.Result}");
else
{
if (result.Result == APIResultCodes.CouldNotFindLatestBlock)
{
_log.LogInformation($"CouldNotFindLatestBlock!! state: {_state.InputMsg.Block.Height}/{_state.InputMsg.Block.Hash} Previous Block Hash: {_state.InputMsg.Block.PreviousHash}");
}
_log.LogError($"LocalAuthorizingAsync takes {stopwatch.ElapsedMilliseconds} ms with {result.Result}");
_log.LogInformation($"LocalAuthorizingAsync state: {_state.InputMsg.Block.Height}/{_state.InputMsg.Block.Hash}");
}
return result;
}
public async Task OnPrePrepareAsync(AuthorizingMsg msg, WaitHandle waitHandle = null)
{
_log.LogInformation($"Receive AuthorizingMsg: {msg.Block.Height}/{msg.Block.Hash}");
_context.OnNodeActive(NodeService.Instance.PosWallet.AccountId); // update billboard
if (msg.Version != LyraGlobal.ProtocolVersion)
{
return;
}
if (_state != null)
{
_log.LogError("State exists.");
return;
}
// first try auth locally
//if(_state == null)
_state = await CreateAuthringStateAsync(msg);
SourceSignedMessage queuedMsg;
while (_outOfOrderedMessages.TryDequeue(out queuedMsg))
{
switch (queuedMsg)
{
case AuthorizedMsg msg1:
await OnPrepareAsync(msg1);
break;
case AuthorizerCommitMsg msg2:
await OnCommitAsync(msg2);
break;
}
}
//_context.Send2P2pNetwork(msg);
_ = Task.Run(async () =>
{
if (waitHandle != null)
await waitHandle.AsTask();
await AuthorizeAsync(msg);
});
}
private async Task AuthorizeAsync(AuthorizingMsg msg)
{
var localAuthResult = await LocalAuthorizingAsync(msg);
_state.AddAuthResult(localAuthResult);
_context.Send2P2pNetwork(localAuthResult);
await CheckAuthorizedAllOkAsync(_state);
}
public async Task OnPrepareAsync(AuthorizedMsg item)
{
if (_state == null)
{
_outOfOrderedMessages.Enqueue(item);
//_log.LogWarning($"OnPrepareAsync: _state null for {item.BlockUIndex}/{item.BlockHash.Shorten()}");
return;
}
//_log.LogInformation($"OnPrepareAsync: {_state.InputMsg.Block.UIndex}/{_state.InputMsg.Block.Index}/{_state.InputMsg.Block.Hash}");
if (_state.T3 == default)
_state.T3 = DateTime.Now;
//if (_activeConsensus.ContainsKey(item.BlockHash))
//{
// var state = _activeConsensus[item.BlockHash];
if (_state.AddAuthResult(item))
await CheckAuthorizedAllOkAsync(_state);
//}
//else
//{
// // maybe outof ordered message
// if (_cleanedConsensus.ContainsKey(item.BlockHash))
// {
// return;
// }
// List<SourceSignedMessage> msgs;
// if (_outOfOrderedMessages.ContainsKey(item.BlockHash))
// msgs = _outOfOrderedMessages[item.BlockHash];
// else
// {
// msgs = new List<SourceSignedMessage>();
// msgs.Add(item);
// }
// msgs.Add(item);
//}
}
private async Task CheckAuthorizedAllOkAsync(AuthState state)
{
// check state
// debug: show all states
if (state.OutputMsgs.Count < state.WinNumber)
{
return;
}
await state.Semaphore.WaitAsync();
try
{
var sb = new StringBuilder();
sb.AppendLine();
var acctId = state.InputMsg.Block is TransactionBlock ? (state.InputMsg.Block as TransactionBlock).AccountID.Shorten() : "";
sb.AppendLine($"* Transaction From Node {acctId} Type: {state.InputMsg.Block.BlockType} Index: {state.InputMsg.Block.Height} Hash: {state.InputMsg.Block.Hash.Shorten()}");
foreach (var msg in state.OutputMsgs.ToList())
{
var seed0 = msg.From == ProtocolSettings.Default.StandbyValidators[0] ? "[seed0]" : "";
string me = "";
if (msg.From == NodeService.Instance.PosWallet.AccountId)
me = "[me]";
var voice = msg.IsSuccess ? "Yay" : "Nay";
var canAuth = ConsensusService.AuthorizerShapshot.Contains(msg.From);
sb.AppendLine($"{voice} {msg.Result} By: {msg.From.Shorten()} CanAuth: {canAuth} {seed0}{me}");
}
_log.LogInformation(sb.ToString());
_log.LogInformation($"state.Consensus is {state.PrepareConsensus}");
if (ConsensusResult.Uncertain != state.PrepareConsensus)
{
_log.LogInformation($"got Semaphore. is it saving? {state.Saving}");
if (state.Saving)
return;
state.Saving = true;
state.T4 = DateTime.Now;
_log.LogInformation($"Saving {state.PrepareConsensus}: {_state.InputMsg.Block.Height}/{_state.InputMsg.Block.Hash}");
var ts = DateTime.Now - state.Created;
if (_context.Stats.Count > 10000)
_context.Stats.RemoveRange(0, 2000);
_context.Stats.Add(new TransStats { ms = (long)ts.TotalMilliseconds, trans = state.InputMsg.Block.BlockType });
var block = state.InputMsg.Block;
// do commit
//block.Authorizations = state.OutputMsgs.Select(a => a.AuthSign).ToList();
var msg = new AuthorizerCommitMsg
{
From = NodeService.Instance.PosWallet.AccountId,
MsgType = ChatMessageType.AuthorizerCommit,
BlockHash = state.InputMsg.Block.Hash,
Consensus = state.PrepareConsensus
};
_context.Send2P2pNetwork(msg);
state.AddCommitedResult(msg);
}
}
catch (Exception ex)
{
_log.LogError($"CheckAuthorizedAllOkAsync: {ex.ToString()}");
}
finally
{
state.Semaphore.Release();
}
}
private async Task CheckCommitedOKAsync()
{
var block = _state.InputMsg?.Block;
if (block == null)
return;
if (_state.CommitConsensus == ConsensusResult.Yay)
{
if (!await BlockChain.Singleton.AddBlockAsync(block))
_log.LogWarning($"Block Save Failed Index: {block.Height}");
else
_log.LogInformation($"Block saved: {block.Height}/{block.Hash}");
// if self result is Nay, need (re)send commited msg here
var myResult = _state.OutputMsgs.FirstOrDefault(a => a.From == NodeService.Instance.PosWallet.AccountId);
if(myResult == null || myResult.Result != APIResultCodes.Success)
{
var msg = new AuthorizerCommitMsg
{
From = NodeService.Instance.PosWallet.AccountId,
MsgType = ChatMessageType.AuthorizerCommit,
BlockHash = _state.InputMsg.Block.Hash,
Consensus = _state.PrepareConsensus
};
_context.Send2P2pNetwork(msg);
}
}
else if (_state.CommitConsensus == ConsensusResult.Nay)
{
}
else
{
return;
}
_state.Done?.Set();
_context.FinishBlock(block.Hash);
if (block is ConsolidationBlock)
{
// get my authorize result
var myResult = _state.OutputMsgs.FirstOrDefault(a => a.From == NodeService.Instance.PosWallet.AccountId);
if (myResult != null && myResult.Result == APIResultCodes.Success && myResult.IsSuccess == (_state.CommitConsensus == ConsensusResult.Yay))
return;
// crap! this node is out of sync.
LyraSystem.Singleton.Consensus.Tell(new ConsensusService.ConsolidateFailed { consolidationBlockHash = block.Hash });
}
}
public async Task OnCommitAsync(AuthorizerCommitMsg item)
{
if (_state == null)
{
_outOfOrderedMessages.Enqueue(item);
//_log.LogWarning($"OnCommit: _state null for {item.BlockHash.Shorten()}");
return;
}
if (_state.T5 == default)
_state.T5 = DateTime.Now;
//if (_activeConsensus.ContainsKey(item.BlockHash))
//{
// var state = _activeConsensus[item.BlockHash];
if(_state.AddCommitedResult(item))
await CheckCommitedOKAsync();
_log.LogInformation($"OnCommit: {_state.CommitMsgs.Count}/{_state.WinNumber} From {item.From.Shorten()}, {_state.InputMsg.Block.Height}/{_state.InputMsg.Block.Hash.Shorten()}");
_context.OnNodeActive(item.From); // track latest activities via billboard
//}
//else
//{
// // maybe outof ordered message
// if (_cleanedConsensus.ContainsKey(item.BlockHash))
// {
// return;
// }
// List<SourceSignedMessage> msgs;
// if (_outOfOrderedMessages.ContainsKey(item.BlockHash))
// msgs = _outOfOrderedMessages[item.BlockHash];
// else
// {
// msgs = new List<SourceSignedMessage>();
// msgs.Add(item);
// }
// msgs.Add(item);
//}
}
}
}
| 37.980176 | 195 | 0.524851 | [
"MIT"
] | wizd/LyraNetwork | Core/Lyra.Core/Decentralize/ConsensusWorker.cs | 17,245 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: MethodRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type WorkbookFunctionsImArgumentRequestBuilder.
/// </summary>
public partial class WorkbookFunctionsImArgumentRequestBuilder : BaseActionMethodRequestBuilder<IWorkbookFunctionsImArgumentRequest>, IWorkbookFunctionsImArgumentRequestBuilder
{
/// <summary>
/// Constructs a new <see cref="WorkbookFunctionsImArgumentRequestBuilder"/>.
/// </summary>
/// <param name="requestUrl">The URL for the request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="inumber">A inumber parameter for the OData method call.</param>
public WorkbookFunctionsImArgumentRequestBuilder(
string requestUrl,
IBaseClient client,
System.Text.Json.JsonDocument inumber)
: base(requestUrl, client)
{
this.SetParameter("inumber", inumber, true);
}
/// <summary>
/// A method used by the base class to construct a request class instance.
/// </summary>
/// <param name="functionUrl">The request URL to </param>
/// <param name="options">The query and header options for the request.</param>
/// <returns>An instance of a specific request class.</returns>
protected override IWorkbookFunctionsImArgumentRequest CreateRequest(string functionUrl, IEnumerable<Option> options)
{
var request = new WorkbookFunctionsImArgumentRequest(functionUrl, this.Client, options);
if (this.HasParameter("inumber"))
{
request.RequestBody.Inumber = this.GetParameter<System.Text.Json.JsonDocument>("inumber");
}
return request;
}
}
}
| 42.818182 | 180 | 0.615711 | [
"MIT"
] | Aliases/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/WorkbookFunctionsImArgumentRequestBuilder.cs | 2,355 | C# |
/*
* PROJECT: Atomix Development
* LICENSE: BSD 3-Clause (LICENSE.md)
* PURPOSE: x86 IMul Instruction
* PROGRAMMERS: Aman Priyadarshi (aman.eureka@gmail.com)
*/
namespace Atomixilc.Machine.x86
{
public class IMul : OnlyDestination
{
public IMul()
: base("imul")
{
}
}
}
| 19.526316 | 61 | 0.525606 | [
"BSD-3-Clause"
] | CatGirlsAreLife/AtomOS | src/Compiler/Atomixilc/Machine/x86/IMul.cs | 373 | C# |
// ┌∩┐(◣_◢)┌∩┐
// \\
// DictionaryExamples.cs (00/00/0000) \\
// Autor: Antonio Mateo (.\Moon Antonio) antoniomt.moon@gmail.com \\
// Descripcion: \\
// Fecha Mod: 00/00/0000 \\
// Ultima Mod: \\
//******************************************************************************\\
#region Librerias
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
#endregion
namespace MoonAntonio
{
public class DictionaryExamples : MonoBehaviour
{
public Dictionary<string, int> stats = new Dictionary<string, int>();
void Start()
{
stats.Add("HP", 10);
stats.Add("MP", 3);
stats.Remove("MP");
if (stats.ContainsKey("HP")) Debug.Log(string.Format("Tienes {0} puntos de golpe restantes", stats["HP"]));
}
}
} | 28.6 | 110 | 0.512821 | [
"MIT"
] | CodeBackDoor/LearnCSharpUnity | LearnCSharpUnity Project/Assets/06.Genericos/DictionaryExamples.cs | 876 | C# |
using System;
using System.IO;
using System.Text.RegularExpressions;
namespace Git.Lfx {
public sealed class LfxConfig {
public static LfxConfig Load(string path = null) {
if (path != null) {
path += LfxConfigFile.FileName;
if (File.Exists(path))
return Load(GitConfig.Load(path));
path = path.GetDir();
}
var gitConfig = GitConfig.Load(path, LfxConfigFile.FileName);
if (gitConfig == null)
return null;
return Load(gitConfig);
}
public static LfxConfig Load(GitConfig gitConfig) {
if (gitConfig == null)
return null;
return new LfxConfig(gitConfig);
}
private readonly LfxConfig m_parent;
private readonly GitConfig m_gitConfig;
private readonly LfxConfigFile m_configFile;
private LfxConfig(GitConfig gitConfig) {
m_gitConfig = gitConfig;
m_configFile = new LfxConfigFile(m_gitConfig.ConfigFile);
if (m_gitConfig.Parent != null)
m_parent = new LfxConfig(m_gitConfig.Parent);
}
private GitConfigValue? TryGetValue(string id) {
GitConfigValue value;
if (!m_gitConfig.TryGetValue(id, out value))
return null;
return value;
}
public GitConfig GitConfig => m_gitConfig;
public LfxConfigFile ConfigFile => m_configFile;
public LfxConfig Parent => m_parent;
public LfxPointerType Type {
get { return m_gitConfig[LfxConfigFile.TypeId].ToEnum<LfxPointerType>(ignoreCase: true); }
}
public string Url => m_gitConfig[LfxConfigFile.UrlId];
public bool HasPattern => m_gitConfig.Contains(LfxConfigFile.PatternId);
public GitConfigValue Pattern => m_gitConfig.GetValue(LfxConfigFile.PatternId);
public bool HasHint => m_gitConfig.Contains(LfxConfigFile.HintId);
public GitConfigValue Hint => m_gitConfig.GetValue(LfxConfigFile.HintId);
public bool HasArgs => m_gitConfig.Contains(LfxConfigFile.ArgsId);
public GitConfigValue Args => m_gitConfig.GetValue(LfxConfigFile.ArgsId);
public override string ToString() => m_gitConfig.ToString();
}
} | 36.578125 | 102 | 0.622811 | [
"MIT"
] | kingces95/LfsEx | Git.Lfx/Config/LfxConfig.cs | 2,343 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Query
{
public partial class RelationalShapedQueryCompilingExpressionVisitor
{
private sealed class CustomShaperCompilingExpressionVisitor : ExpressionVisitor
{
private readonly ParameterExpression _dbDataReaderParameter;
private readonly ParameterExpression _resultCoordinatorParameter;
private readonly bool _tracking;
public CustomShaperCompilingExpressionVisitor(
ParameterExpression dbDataReaderParameter,
ParameterExpression resultCoordinatorParameter,
bool tracking)
{
_dbDataReaderParameter = dbDataReaderParameter;
_resultCoordinatorParameter = resultCoordinatorParameter;
_tracking = tracking;
}
private static readonly MethodInfo _includeReferenceMethodInfo
= typeof(CustomShaperCompilingExpressionVisitor).GetTypeInfo()
.GetDeclaredMethod(nameof(IncludeReference));
private static void IncludeReference<TEntity, TIncludingEntity, TIncludedEntity>(
QueryContext queryContext,
TEntity entity,
TIncludedEntity relatedEntity,
INavigation navigation,
INavigation inverseNavigation,
Action<TIncludingEntity, TIncludedEntity> fixup,
bool trackingQuery)
where TIncludingEntity : TEntity
{
if (entity is TIncludingEntity includingEntity)
{
if (trackingQuery
&& navigation.DeclaringEntityType.FindPrimaryKey() != null)
{
// For non-null relatedEntity StateManager will set the flag
if (relatedEntity == null)
{
queryContext.SetNavigationIsLoaded(includingEntity, navigation);
}
}
else
{
SetIsLoadedNoTracking(includingEntity, navigation);
if (relatedEntity != null)
{
fixup(includingEntity, relatedEntity);
if (inverseNavigation != null
&& !inverseNavigation.IsCollection)
{
SetIsLoadedNoTracking(relatedEntity, inverseNavigation);
}
}
}
}
}
private static readonly MethodInfo _populateCollectionMethodInfo
= typeof(CustomShaperCompilingExpressionVisitor).GetTypeInfo()
.GetDeclaredMethod(nameof(PopulateCollection));
private static void PopulateCollection<TCollection, TElement, TRelatedEntity>(
int collectionId,
QueryContext queryContext,
DbDataReader dbDataReader,
ResultCoordinator resultCoordinator,
Func<QueryContext, DbDataReader, object[]> parentIdentifier,
Func<QueryContext, DbDataReader, object[]> outerIdentifier,
Func<QueryContext, DbDataReader, object[]> selfIdentifier,
IReadOnlyList<ValueComparer> parentIdentifierValueComparers,
IReadOnlyList<ValueComparer> outerIdentifierValueComparers,
IReadOnlyList<ValueComparer> selfIdentifierValueComparers,
Func<QueryContext, DbDataReader, ResultContext, ResultCoordinator, TRelatedEntity> innerShaper)
where TRelatedEntity : TElement
where TCollection : class, ICollection<TElement>
{
var collectionMaterializationContext = resultCoordinator.Collections[collectionId];
if (collectionMaterializationContext.Collection is null)
{
// nothing to materialize since no collection created
return;
}
if (resultCoordinator.HasNext == false)
{
// Outer Enumerator has ended
GenerateCurrentElementIfPending();
return;
}
if (!CompareIdentifiers(outerIdentifierValueComparers,
outerIdentifier(queryContext, dbDataReader), collectionMaterializationContext.OuterIdentifier))
{
// Outer changed so collection has ended. Materialize last element.
GenerateCurrentElementIfPending();
// If parent also changed then this row is now pointing to element of next collection
if (!CompareIdentifiers(parentIdentifierValueComparers,
parentIdentifier(queryContext, dbDataReader), collectionMaterializationContext.ParentIdentifier))
{
resultCoordinator.HasNext = true;
}
return;
}
var innerKey = selfIdentifier(queryContext, dbDataReader);
if (innerKey.Any(e => e == null))
{
// No correlated element
return;
}
if (collectionMaterializationContext.SelfIdentifier != null)
{
if (CompareIdentifiers(selfIdentifierValueComparers,
innerKey, collectionMaterializationContext.SelfIdentifier))
{
// repeated row for current element
// If it is pending materialization then it may have nested elements
if (collectionMaterializationContext.ResultContext.Values != null)
{
ProcessCurrentElementRow();
}
resultCoordinator.ResultReady = false;
return;
}
// Row for new element which is not first element
// So materialize the element
GenerateCurrentElementIfPending();
resultCoordinator.HasNext = null;
collectionMaterializationContext.UpdateSelfIdentifier(innerKey);
}
else
{
// First row for current element
collectionMaterializationContext.UpdateSelfIdentifier(innerKey);
}
ProcessCurrentElementRow();
resultCoordinator.ResultReady = false;
void ProcessCurrentElementRow()
{
var previousResultReady = resultCoordinator.ResultReady;
resultCoordinator.ResultReady = true;
var element = innerShaper(
queryContext, dbDataReader, collectionMaterializationContext.ResultContext, resultCoordinator);
if (resultCoordinator.ResultReady)
{
// related element is materialized
collectionMaterializationContext.ResultContext.Values = null;
((TCollection)collectionMaterializationContext.Collection).Add(element);
}
resultCoordinator.ResultReady &= previousResultReady;
}
void GenerateCurrentElementIfPending()
{
if (collectionMaterializationContext.ResultContext.Values != null)
{
resultCoordinator.HasNext = false;
ProcessCurrentElementRow();
}
collectionMaterializationContext.UpdateSelfIdentifier(null);
}
}
private static readonly MethodInfo _populateIncludeCollectionMethodInfo
= typeof(CustomShaperCompilingExpressionVisitor).GetTypeInfo()
.GetDeclaredMethod(nameof(PopulateIncludeCollection));
private static void PopulateIncludeCollection<TIncludingEntity, TIncludedEntity>(
int collectionId,
QueryContext queryContext,
DbDataReader dbDataReader,
ResultCoordinator resultCoordinator,
Func<QueryContext, DbDataReader, object[]> parentIdentifier,
Func<QueryContext, DbDataReader, object[]> outerIdentifier,
Func<QueryContext, DbDataReader, object[]> selfIdentifier,
IReadOnlyList<ValueComparer> parentIdentifierValueComparers,
IReadOnlyList<ValueComparer> outerIdentifierValueComparers,
IReadOnlyList<ValueComparer> selfIdentifierValueComparers,
Func<QueryContext, DbDataReader, ResultContext, ResultCoordinator, TIncludedEntity> innerShaper,
INavigation inverseNavigation,
Action<TIncludingEntity, TIncludedEntity> fixup,
bool trackingQuery)
{
var collectionMaterializationContext = resultCoordinator.Collections[collectionId];
if (collectionMaterializationContext.Parent is TIncludingEntity entity)
{
if (resultCoordinator.HasNext == false)
{
// Outer Enumerator has ended
GenerateCurrentElementIfPending();
return;
}
if (!CompareIdentifiers(outerIdentifierValueComparers,
outerIdentifier(queryContext, dbDataReader), collectionMaterializationContext.OuterIdentifier))
{
// Outer changed so collection has ended. Materialize last element.
GenerateCurrentElementIfPending();
// If parent also changed then this row is now pointing to element of next collection
if (!CompareIdentifiers(parentIdentifierValueComparers,
parentIdentifier(queryContext, dbDataReader), collectionMaterializationContext.ParentIdentifier))
{
resultCoordinator.HasNext = true;
}
return;
}
var innerKey = selfIdentifier(queryContext, dbDataReader);
if (innerKey.Any(e => e == null))
{
// No correlated element
return;
}
if (collectionMaterializationContext.SelfIdentifier != null)
{
if (CompareIdentifiers(selfIdentifierValueComparers, innerKey, collectionMaterializationContext.SelfIdentifier))
{
// repeated row for current element
// If it is pending materialization then it may have nested elements
if (collectionMaterializationContext.ResultContext.Values != null)
{
ProcessCurrentElementRow();
}
resultCoordinator.ResultReady = false;
return;
}
// Row for new element which is not first element
// So materialize the element
GenerateCurrentElementIfPending();
resultCoordinator.HasNext = null;
collectionMaterializationContext.UpdateSelfIdentifier(innerKey);
}
else
{
// First row for current element
collectionMaterializationContext.UpdateSelfIdentifier(innerKey);
}
ProcessCurrentElementRow();
resultCoordinator.ResultReady = false;
}
void ProcessCurrentElementRow()
{
var previousResultReady = resultCoordinator.ResultReady;
resultCoordinator.ResultReady = true;
var relatedEntity = innerShaper(
queryContext, dbDataReader, collectionMaterializationContext.ResultContext, resultCoordinator);
if (resultCoordinator.ResultReady)
{
// related entity is materialized
collectionMaterializationContext.ResultContext.Values = null;
if (!trackingQuery)
{
fixup(entity, relatedEntity);
if (inverseNavigation != null)
{
SetIsLoadedNoTracking(relatedEntity, inverseNavigation);
}
}
}
resultCoordinator.ResultReady &= previousResultReady;
}
void GenerateCurrentElementIfPending()
{
if (collectionMaterializationContext.ResultContext.Values != null)
{
resultCoordinator.HasNext = false;
ProcessCurrentElementRow();
}
collectionMaterializationContext.UpdateSelfIdentifier(null);
}
}
private static bool CompareIdentifiers(IReadOnlyList<ValueComparer> valueComparers, object[] left, object[] right)
{
if (valueComparers != null)
{
// Ignoring size check on all for perf as they should be same unless bug in code.
for (var i = 0; i < left.Length; i++)
{
if (valueComparers[i] != null
? !valueComparers[i].Equals(left[i], right[i])
: !Equals(left[i], right[i]))
{
return false;
}
}
return true;
}
return StructuralComparisons.StructuralEqualityComparer.Equals(left, right);
}
private static readonly MethodInfo _initializeIncludeCollectionMethodInfo
= typeof(CustomShaperCompilingExpressionVisitor).GetTypeInfo()
.GetDeclaredMethod(nameof(InitializeIncludeCollection));
private static void InitializeIncludeCollection<TParent, TNavigationEntity>(
int collectionId,
QueryContext queryContext,
DbDataReader dbDataReader,
ResultCoordinator resultCoordinator,
TParent entity,
Func<QueryContext, DbDataReader, object[]> parentIdentifier,
Func<QueryContext, DbDataReader, object[]> outerIdentifier,
INavigation navigation,
IClrCollectionAccessor clrCollectionAccessor,
bool trackingQuery)
where TNavigationEntity : TParent
{
object collection = null;
if (entity is TNavigationEntity)
{
if (trackingQuery)
{
queryContext.SetNavigationIsLoaded(entity, navigation);
}
else
{
SetIsLoadedNoTracking(entity, navigation);
}
collection = clrCollectionAccessor.GetOrCreate(entity, forMaterialization: true);
}
var parentKey = parentIdentifier(queryContext, dbDataReader);
var outerKey = outerIdentifier(queryContext, dbDataReader);
var collectionMaterializationContext = new CollectionMaterializationContext(entity, collection, parentKey, outerKey);
resultCoordinator.SetCollectionMaterializationContext(collectionId, collectionMaterializationContext);
}
private static readonly MethodInfo _initializeCollectionMethodInfo
= typeof(CustomShaperCompilingExpressionVisitor).GetTypeInfo()
.GetDeclaredMethod(nameof(InitializeCollection));
private static TCollection InitializeCollection<TElement, TCollection>(
int collectionId,
QueryContext queryContext,
DbDataReader dbDataReader,
ResultCoordinator resultCoordinator,
Func<QueryContext, DbDataReader, object[]> parentIdentifier,
Func<QueryContext, DbDataReader, object[]> outerIdentifier,
IClrCollectionAccessor clrCollectionAccessor)
where TCollection : class, IEnumerable<TElement>
{
var collection = clrCollectionAccessor?.Create() ?? new List<TElement>();
var parentKey = parentIdentifier(queryContext, dbDataReader);
var outerKey = outerIdentifier(queryContext, dbDataReader);
var collectionMaterializationContext = new CollectionMaterializationContext(null, collection, parentKey, outerKey);
resultCoordinator.SetCollectionMaterializationContext(collectionId, collectionMaterializationContext);
return (TCollection)collection;
}
private static void SetIsLoadedNoTracking(object entity, INavigation navigation)
=> ((ILazyLoader)(navigation
.DeclaringEntityType
.GetServiceProperties()
.FirstOrDefault(p => p.ClrType == typeof(ILazyLoader)))
?.GetGetter().GetClrValue(entity))
?.SetLoaded(entity, navigation.Name);
protected override Expression VisitExtension(Expression extensionExpression)
{
Check.NotNull(extensionExpression, nameof(extensionExpression));
if (extensionExpression is IncludeExpression includeExpression)
{
Check.DebugAssert(
!includeExpression.Navigation.IsCollection,
"Only reference include should be present in tree");
var entityClrType = includeExpression.EntityExpression.Type;
var includingClrType = includeExpression.Navigation.DeclaringEntityType.ClrType;
var inverseNavigation = includeExpression.Navigation.Inverse;
var relatedEntityClrType = includeExpression.Navigation.TargetEntityType.ClrType;
if (includingClrType != entityClrType
&& includingClrType.IsAssignableFrom(entityClrType))
{
includingClrType = entityClrType;
}
return Expression.Call(
_includeReferenceMethodInfo.MakeGenericMethod(entityClrType, includingClrType, relatedEntityClrType),
QueryCompilationContext.QueryContextParameter,
// We don't need to visit entityExpression since it is supposed to be a parameterExpression only
includeExpression.EntityExpression,
includeExpression.NavigationExpression,
Expression.Constant(includeExpression.Navigation),
Expression.Constant(inverseNavigation, typeof(INavigation)),
Expression.Constant(
GenerateFixup(
includingClrType, relatedEntityClrType, includeExpression.Navigation, inverseNavigation).Compile()),
Expression.Constant(_tracking));
}
if (extensionExpression is CollectionInitializingExpression collectionInitializingExpression)
{
if (collectionInitializingExpression.Parent != null)
{
// Include case
var entityClrType = collectionInitializingExpression.Parent.Type;
var includingClrType = collectionInitializingExpression.Navigation.DeclaringEntityType.ClrType;
if (includingClrType != entityClrType
&& includingClrType.IsAssignableFrom(entityClrType))
{
includingClrType = entityClrType;
}
return Expression.Call(
_initializeIncludeCollectionMethodInfo.MakeGenericMethod(entityClrType, includingClrType),
Expression.Constant(collectionInitializingExpression.CollectionId),
QueryCompilationContext.QueryContextParameter,
_dbDataReaderParameter,
_resultCoordinatorParameter,
collectionInitializingExpression.Parent,
Expression.Constant(
Expression.Lambda(
collectionInitializingExpression.ParentIdentifier,
QueryCompilationContext.QueryContextParameter,
_dbDataReaderParameter).Compile()),
Expression.Constant(
Expression.Lambda(
collectionInitializingExpression.OuterIdentifier,
QueryCompilationContext.QueryContextParameter,
_dbDataReaderParameter).Compile()),
Expression.Constant(collectionInitializingExpression.Navigation),
Expression.Constant(collectionInitializingExpression.Navigation.GetCollectionAccessor()),
Expression.Constant(_tracking));
}
var collectionClrType = collectionInitializingExpression.Type;
var elementType = collectionClrType.TryGetSequenceType();
return Expression.Call(
_initializeCollectionMethodInfo.MakeGenericMethod(elementType, collectionClrType),
Expression.Constant(collectionInitializingExpression.CollectionId),
QueryCompilationContext.QueryContextParameter,
_dbDataReaderParameter,
_resultCoordinatorParameter,
Expression.Constant(
Expression.Lambda(
collectionInitializingExpression.ParentIdentifier,
QueryCompilationContext.QueryContextParameter,
_dbDataReaderParameter).Compile()),
Expression.Constant(
Expression.Lambda(
collectionInitializingExpression.OuterIdentifier,
QueryCompilationContext.QueryContextParameter,
_dbDataReaderParameter).Compile()),
Expression.Constant(
collectionInitializingExpression.Navigation?.GetCollectionAccessor(),
typeof(IClrCollectionAccessor)));
}
if (extensionExpression is CollectionPopulatingExpression collectionPopulatingExpression)
{
var collectionShaper = collectionPopulatingExpression.Parent;
var relatedEntityClrType = ((LambdaExpression)collectionShaper.InnerShaper).ReturnType;
if (collectionPopulatingExpression.IsInclude)
{
var entityClrType = collectionShaper.Navigation.DeclaringEntityType.ClrType;
var inverseNavigation = collectionShaper.Navigation.Inverse;
return Expression.Call(
_populateIncludeCollectionMethodInfo.MakeGenericMethod(entityClrType, relatedEntityClrType),
Expression.Constant(collectionShaper.CollectionId),
QueryCompilationContext.QueryContextParameter,
_dbDataReaderParameter,
_resultCoordinatorParameter,
Expression.Constant(
Expression.Lambda(
collectionShaper.ParentIdentifier,
QueryCompilationContext.QueryContextParameter,
_dbDataReaderParameter).Compile()),
Expression.Constant(
Expression.Lambda(
collectionShaper.OuterIdentifier,
QueryCompilationContext.QueryContextParameter,
_dbDataReaderParameter).Compile()),
Expression.Constant(
Expression.Lambda(
collectionShaper.SelfIdentifier,
QueryCompilationContext.QueryContextParameter,
_dbDataReaderParameter).Compile()),
Expression.Constant(collectionShaper.ParentIdentifierValueComparers, typeof(IReadOnlyList<ValueComparer>)),
Expression.Constant(collectionShaper.OuterIdentifierValueComparers, typeof(IReadOnlyList<ValueComparer>)),
Expression.Constant(collectionShaper.SelfIdentifierValueComparers, typeof(IReadOnlyList<ValueComparer>)),
Expression.Constant(((LambdaExpression)Visit(collectionShaper.InnerShaper)).Compile()),
Expression.Constant(inverseNavigation, typeof(INavigation)),
Expression.Constant(
GenerateFixup(
entityClrType, relatedEntityClrType, collectionShaper.Navigation, inverseNavigation).Compile()),
Expression.Constant(_tracking));
}
var collectionType = collectionPopulatingExpression.Type;
var elementType = collectionType.TryGetSequenceType();
return Expression.Call(
_populateCollectionMethodInfo.MakeGenericMethod(collectionType, elementType, relatedEntityClrType),
Expression.Constant(collectionShaper.CollectionId),
QueryCompilationContext.QueryContextParameter,
_dbDataReaderParameter,
_resultCoordinatorParameter,
Expression.Constant(
Expression.Lambda(
collectionShaper.ParentIdentifier,
QueryCompilationContext.QueryContextParameter,
_dbDataReaderParameter).Compile()),
Expression.Constant(
Expression.Lambda(
collectionShaper.OuterIdentifier,
QueryCompilationContext.QueryContextParameter,
_dbDataReaderParameter).Compile()),
Expression.Constant(
Expression.Lambda(
collectionShaper.SelfIdentifier,
QueryCompilationContext.QueryContextParameter,
_dbDataReaderParameter).Compile()),
Expression.Constant(collectionShaper.ParentIdentifierValueComparers, typeof(IReadOnlyList<ValueComparer>)),
Expression.Constant(collectionShaper.OuterIdentifierValueComparers, typeof(IReadOnlyList<ValueComparer>)),
Expression.Constant(collectionShaper.SelfIdentifierValueComparers, typeof(IReadOnlyList<ValueComparer>)),
Expression.Constant(((LambdaExpression)Visit(collectionShaper.InnerShaper)).Compile()));
}
if (extensionExpression is GroupByShaperExpression)
{
throw new InvalidOperationException(RelationalStrings.ClientGroupByNotSupported);
}
return base.VisitExtension(extensionExpression);
}
private static LambdaExpression GenerateFixup(
Type entityType,
Type relatedEntityType,
INavigation navigation,
INavigation inverseNavigation)
{
var entityParameter = Expression.Parameter(entityType);
var relatedEntityParameter = Expression.Parameter(relatedEntityType);
var expressions = new List<Expression>
{
navigation.IsCollection
? AddToCollectionNavigation(entityParameter, relatedEntityParameter, navigation)
: AssignReferenceNavigation(entityParameter, relatedEntityParameter, navigation)
};
if (inverseNavigation != null)
{
expressions.Add(
inverseNavigation.IsCollection
? AddToCollectionNavigation(relatedEntityParameter, entityParameter, inverseNavigation)
: AssignReferenceNavigation(relatedEntityParameter, entityParameter, inverseNavigation));
}
return Expression.Lambda(Expression.Block(typeof(void), expressions), entityParameter, relatedEntityParameter);
}
private static Expression AssignReferenceNavigation(
ParameterExpression entity,
ParameterExpression relatedEntity,
INavigation navigation)
{
return entity.MakeMemberAccess(navigation.GetMemberInfo(forMaterialization: true, forSet: true)).Assign(relatedEntity);
}
private static Expression AddToCollectionNavigation(
ParameterExpression entity,
ParameterExpression relatedEntity,
INavigation navigation)
=> Expression.Call(
Expression.Constant(navigation.GetCollectionAccessor()),
_collectionAccessorAddMethodInfo,
entity,
relatedEntity,
Expression.Constant(true));
private static readonly MethodInfo _collectionAccessorAddMethodInfo
= typeof(IClrCollectionAccessor).GetTypeInfo()
.GetDeclaredMethod(nameof(IClrCollectionAccessor.Add));
}
}
}
| 51.222576 | 136 | 0.55309 | [
"Apache-2.0"
] | IGx89/efcore | src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.CustomShaperCompilingExpressionVisitor.cs | 32,219 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.ExcelApi
{
/// <summary>
/// Partial WorksheetFunction StDev_S
/// </summary>
partial class WorksheetFunction : COMObject
{
#region Methods
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
/// <param name="arg23">optional object arg23</param>
/// <param name="arg24">optional object arg24</param>
/// <param name="arg25">optional object arg25</param>
/// <param name="arg26">optional object arg26</param>
/// <param name="arg27">optional object arg27</param>
/// <param name="arg28">optional object arg28</param>
/// <param name="arg29">optional object arg29</param>
/// <param name="arg30">optional object arg30</param>
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22, object arg23, object arg24, object arg25, object arg26, object arg27, object arg28, object arg29, object arg30)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29, arg30 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", arg1);
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", arg1, arg2);
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", arg1, arg2, arg3);
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", arg1, arg2, arg3, arg4);
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
/// <param name="arg23">optional object arg23</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22, object arg23)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
/// <param name="arg23">optional object arg23</param>
/// <param name="arg24">optional object arg24</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22, object arg23, object arg24)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
/// <param name="arg23">optional object arg23</param>
/// <param name="arg24">optional object arg24</param>
/// <param name="arg25">optional object arg25</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22, object arg23, object arg24, object arg25)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
/// <param name="arg23">optional object arg23</param>
/// <param name="arg24">optional object arg24</param>
/// <param name="arg25">optional object arg25</param>
/// <param name="arg26">optional object arg26</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22, object arg23, object arg24, object arg25, object arg26)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
/// <param name="arg23">optional object arg23</param>
/// <param name="arg24">optional object arg24</param>
/// <param name="arg25">optional object arg25</param>
/// <param name="arg26">optional object arg26</param>
/// <param name="arg27">optional object arg27</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22, object arg23, object arg24, object arg25, object arg26, object arg27)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
/// <param name="arg23">optional object arg23</param>
/// <param name="arg24">optional object arg24</param>
/// <param name="arg25">optional object arg25</param>
/// <param name="arg26">optional object arg26</param>
/// <param name="arg27">optional object arg27</param>
/// <param name="arg28">optional object arg28</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22, object arg23, object arg24, object arg25, object arg26, object arg27, object arg28)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28 });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="arg1">object arg1</param>
/// <param name="arg2">optional object arg2</param>
/// <param name="arg3">optional object arg3</param>
/// <param name="arg4">optional object arg4</param>
/// <param name="arg5">optional object arg5</param>
/// <param name="arg6">optional object arg6</param>
/// <param name="arg7">optional object arg7</param>
/// <param name="arg8">optional object arg8</param>
/// <param name="arg9">optional object arg9</param>
/// <param name="arg10">optional object arg10</param>
/// <param name="arg11">optional object arg11</param>
/// <param name="arg12">optional object arg12</param>
/// <param name="arg13">optional object arg13</param>
/// <param name="arg14">optional object arg14</param>
/// <param name="arg15">optional object arg15</param>
/// <param name="arg16">optional object arg16</param>
/// <param name="arg17">optional object arg17</param>
/// <param name="arg18">optional object arg18</param>
/// <param name="arg19">optional object arg19</param>
/// <param name="arg20">optional object arg20</param>
/// <param name="arg21">optional object arg21</param>
/// <param name="arg22">optional object arg22</param>
/// <param name="arg23">optional object arg23</param>
/// <param name="arg24">optional object arg24</param>
/// <param name="arg25">optional object arg25</param>
/// <param name="arg26">optional object arg26</param>
/// <param name="arg27">optional object arg27</param>
/// <param name="arg28">optional object arg28</param>
/// <param name="arg29">optional object arg29</param>
[CustomMethod]
[SupportByVersion("Excel", 14, 15, 16)]
public Double StDev_S(object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20, object arg21, object arg22, object arg23, object arg24, object arg25, object arg26, object arg27, object arg28, object arg29)
{
return Factory.ExecuteDoubleMethodGet(this, "StDev_S", new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26, arg27, arg28, arg29 });
}
#endregion
}
}
| 59.539642 | 440 | 0.616924 | [
"MIT"
] | DominikPalo/NetOffice | Source/Excel/DispatchInterfaces/WorksheetFunction.StDev_S.cs | 46,562 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using ConvenienceSystemDataModel;
using System.Collections.ObjectModel;
namespace ConvenienceSystemApp.pages
{
//public partial class ProductsPage : ContentPage
public partial class ProductsPage : ContentPage
{
private List<String> products = new List<string> ();
ObservableCollection<Product> productCollection = new ObservableCollection<Product>();
public ProductsPage (ProductsPageViewModel vm)
{
InitializeComponent ();
BindingContext = vm;
productListView.ItemTapped += productListView_ItemTapped;
AbortButton.Clicked += (object sender, EventArgs e) => Navigation.PopAsync();
BuyButton.Clicked += OnBuyClicked;
}
async void productListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
// Just Add to the ViewModel
((ProductsPageViewModel)this.BindingContext).IsBusy = true;
((ProductsPageViewModel)this.BindingContext).AddProductSelection(((ProductsPageViewModel.ProductsViewModel)e.Item));
((ProductsPageViewModel)this.BindingContext).IsBusy = false;
}
async void OnBuyClicked(object sender, EventArgs e)
{
// Execute on ViewModel
((ProductsPageViewModel)this.BindingContext).IsBusy = true;
// Only buy if there are items in the cart..
if (String.IsNullOrEmpty(((ProductsPageViewModel)this.BindingContext).SelectedProductsString))
Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
{
DisplayAlert("Error", "Bitte zuerst Produkte auswählen!", "OK");
});
bool success = await ((ProductsPageViewModel)this.BindingContext).BuyProductsAsync();
// On error, inform to user
if (!success)
{
/*Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
{
DisplayAlert("Error", "Kauf konnte nciht getätigt werden. Bitte später erneut versuchen. Falls das problem länger besteht, bitte melden!", "OK");
});*/
App.LastBuy = LastBuyState.FAILED;
((ProductsPageViewModel)this.BindingContext).IsBusy = false;
return;
}
// No error, Inform User and go back
((ProductsPageViewModel)this.BindingContext).IsBusy = false;
/*Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
{
DisplayAlert("Success", "Kauf erfolgreich!", "OK");
});*/
App.LastBuy = LastBuyState.SUCCESS;
bool succ = await DataManager.GetAllDataAsync();
Navigation.PopAsync();
}
}
}
| 33.602273 | 170 | 0.60602 | [
"MIT"
] | auxua/ConvenienceSystem2 | ConvenienceSystemApp/ConvenienceSystemApp/pages/ProductsPage.xaml.cs | 2,963 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using MarauderEngine.Entity;
using MarauderEngine.Graphics;
using Microsoft.Xna.Framework.Graphics;
namespace MarauderEditor.CustomComponents
{
public class AssetBrowser : ListView
{
public static AssetBrowser Instance;
public struct Asset
{
public string Key;
public Bitmap Bitmap;
}
public AssetBrowser(Control parent)
{
Instance = this;
Parent = parent;
BackColor = ColorScheme.ComponentColor;
ForeColor = Color.White;
BorderStyle = BorderStyle.None;
Font = new Font("Calibri", 12, FontStyle.Regular);
Height = 250;
//Anchor = AnchorStyles.Bottom;
View = View.Tile;
//var label = new Label();
//label.Text = "AssetBrowser";
//label.Parent = this;
//label.Location = new Point(10, -10);
//label.Size = new Size(100, 24);
//label.ForeColor = Color.White;
//label.BackColor = Color.Transparent;
this.ItemSelectionChanged += (sender, args) =>
{
EntityProperties.Instance.LoadEntity((args.Item as EntityViewItem).Entity.EntityData );
if (TransformMovement.Instance != null)
{
TransformMovement.Instance.SetBrush((args.Item as EntityViewItem));
}
};
}
public void LoadEntities(Assembly gameAssembly)
{
int i = 0;
ImageList imageList = new ImageList();
imageList.ImageSize = new Size(64, 64);
View = View.LargeIcon;
LargeImageList = imageList;
var prefabImage = Bitmap.FromFile("Images/MarauderLogo.png");
foreach (Type type in gameAssembly.GetTypes())
{
if (type.IsSubclassOf(typeof(Entity)) && !type.IsAbstract)
{
Console.WriteLine(type.DeclaringType);
EntityViewItem lvi = new EntityViewItem(type);
lvi.ImageIndex = i;
imageList.Images.Add(type.Name, prefabImage);
Items.Add(lvi);
i++;
}
}
}
public void LoadContent()
{
Console.WriteLine("loading content");
List<Asset> bitmaps = new List<Asset>();
foreach (KeyValuePair<string, object> key in TextureManager.ContentDictionary)
{
if (key.Value is Texture2D)
{
bitmaps.Add(new Asset()
{
Key = key.Key,
Bitmap = ConvertToBitmap(key.Key)
});
}
}
AddContent(bitmaps);
}
public void AddContent(string key)
{
Items.Add(key);
}
public void AddContent(List<Asset> bitmaps)
{
ImageList imageList = new ImageList();
imageList.ImageSize = new Size(64,64);
View = View.LargeIcon;
LargeImageList = imageList;
var prefabImage = Bitmap.FromFile("Images/MarauderLogo.png");
int i = 0;
foreach (var image in bitmaps)
{
ListViewItem lvi = new ListViewItem();
lvi.ImageIndex = i;
lvi.ToolTipText = "Test";
lvi.Text = image.Key;
Items.Add(lvi);
imageList.Images.Add(image.Key, prefabImage);
Console.WriteLine("adding imgae");
i++;
}
Refresh();
}
public Bitmap ConvertToBitmap(string key)
{
MemoryStream memoryStream = new MemoryStream();
TextureManager.GetContent<Texture2D>(key).SaveAsPng(memoryStream,
TextureManager.GetContent<Texture2D>(key).Width,
TextureManager.GetContent<Texture2D>(key).Height);
return new Bitmap(memoryStream);
}
}
}
| 29.659864 | 103 | 0.508945 | [
"MIT"
] | Dankerprouduct/MarauderEngine | MarauderEditor/CustomComponents/AssetBrowser.cs | 4,362 | C# |
// Generated on 12/11/2014 19:02:04
using System;
using System.Collections.Generic;
using System.Linq;
using BlueSheep.Common.IO;
namespace BlueSheep.Common.Protocol.Types
{
public class FightOptionsInformations
{
public new const short ID = 20;
public virtual short TypeId
{
get { return ID; }
}
public bool isSecret;
public bool isRestrictedToPartyOnly;
public bool isClosed;
public bool isAskingForHelp;
public FightOptionsInformations()
{
}
public virtual void Serialize(BigEndianWriter writer)
{
byte _loc2_ = 0;
_loc2_ = BooleanByteWrapper.SetFlag(_loc2_,0,this.isSecret);
_loc2_ = BooleanByteWrapper.SetFlag(_loc2_,1,this.isRestrictedToPartyOnly);
_loc2_ = BooleanByteWrapper.SetFlag(_loc2_,2,this.isClosed);
_loc2_ = BooleanByteWrapper.SetFlag(_loc2_,3,this.isAskingForHelp);
writer.WriteByte(_loc2_);
}
public virtual void Deserialize(BigEndianReader reader)
{
byte _loc2_ = reader.ReadByte();
this.isSecret = BooleanByteWrapper.GetFlag(_loc2_,0);
this.isRestrictedToPartyOnly = BooleanByteWrapper.GetFlag(_loc2_,1);
this.isClosed = BooleanByteWrapper.GetFlag(_loc2_,2);
this.isAskingForHelp = BooleanByteWrapper.GetFlag(_loc2_,3);
}
}
} | 16.871795 | 84 | 0.705167 | [
"MIT"
] | Sadikk/BlueSheep | BlueSheep/Common/Protocol/types/game/context/fight/FightOptionsInformations.cs | 1,316 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//[assembly: AssemblyConfiguration("")]
//[assembly: AssemblyCompany("")]
//[assembly: AssemblyProduct("TypeScriptBuilder")]
//[assembly: AssemblyTrademark("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
//[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
//[assembly: Guid("bb258769-d1d0-494e-92d3-943d4da4edb1")]
| 41.95 | 84 | 0.772348 | [
"MIT"
] | Obviuse/TypeScriptBuilder | src/TypeScriptBuilder/Properties/AssemblyInfo.cs | 841 | C# |
namespace LeetCode.P349
{
using System.Collections.Generic;
public class Solution
{
public int[] Intersection(int[] nums1, int[] nums2)
{
var hashset = new HashSet<int>(nums1);
var result = new List<int>();
for (var i = 0; hashset.Count != 0 && i < nums2.Length; i++)
{
if (hashset.Remove(nums2[i])) result.Add(nums2[i]);
}
return result.ToArray();
}
}
}
| 22.181818 | 72 | 0.495902 | [
"MIT"
] | Zhangwei-WU/MyLeetcodeSolutions | LeetCode/P349-Intersection-of-Two-Arrays.cs | 490 | C# |
// Copyright 2004-2010 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace NVelocity.Runtime
{
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Commons.Collections;
using Directive;
using Log;
using NVelocity.Exception;
using NVelocity.Runtime.Parser.Node;
using NVelocity.Util.Introspection;
using Resource;
using Util;
/// <summary>
/// This is the Runtime system for Velocity. It is the
/// single access point for all functionality in Velocity.
/// It adheres to the mediator pattern and is the only
/// structure that developers need to be familiar with
/// in order to get Velocity to perform.
///
/// The Runtime will also cooperate with external
/// systems like Turbine. Runtime properties can
/// set and then the Runtime is initialized.
///
/// Turbine for example knows where the templates
/// are to be loaded from, and where the velocity
/// log file should be placed.
///
/// So in the case of Velocity cooperating with Turbine
/// the code might look something like the following:
///
/// <code>
/// Runtime.setProperty(Runtime.FILE_RESOURCE_LOADER_PATH, templatePath);
/// Runtime.setProperty(Runtime.RUNTIME_LOG, pathToVelocityLog);
/// Runtime.init();
/// </code>
///
/// <pre>
/// -----------------------------------------------------------------------
/// N O T E S O N R U N T I M E I N I T I A L I Z A T I O N
/// -----------------------------------------------------------------------
/// Runtime.init()
///
/// If Runtime.init() is called by itself the Runtime will
/// initialize with a set of default values.
/// -----------------------------------------------------------------------
/// Runtime.init(String/Properties)
///
/// In this case the default velocity properties are layed down
/// first to provide a solid base, then any properties provided
/// in the given properties object will override the corresponding
/// default property.
/// -----------------------------------------------------------------------
/// </pre>
///
/// </summary>
public class RuntimeInstance : IRuntimeServices
{
private DefaultTraceListener debugOutput = new DefaultTraceListener();
/// <summary>
/// VelocimacroFactory object to manage VMs
/// </summary>
private VelocimacroFactory vmFactory = null;
/// <summary>
/// The Runtime parser pool
/// </summary>
private SimplePool<Parser.Parser> parserPool;
/// <summary>
/// Indicate whether the Runtime has been fully initialized.
/// </summary>
private bool initialized;
/// <summary>
/// These are the properties that are laid down over top
/// of the default properties when requested.
/// </summary>
private ExtendedProperties overridingProperties = null;
/// <summary>
/// Object that houses the configuration options for
/// the velocity runtime. The ExtendedProperties object allows
/// the convenient retrieval of a subset of properties.
/// For example all the properties for a resource loader
/// can be retrieved from the main ExtendedProperties object
/// using something like the following:
///
/// <code>
/// ExtendedProperties loaderConfiguration =
/// configuration.subset(loaderID);
/// </code>
///
/// And a configuration is a lot more convenient to deal
/// with then conventional properties objects, or Maps.
/// </summary>
private readonly ExtendedProperties configuration;
private IResourceManager resourceManager = null;
/// <summary>
/// Each runtime instance has it's own introspector
/// to ensure that each instance is completely separate.
/// </summary>
private readonly Introspector introspector = null;
/// <summary>
/// Opaque reference to something specified by the
/// application for use in application supplied/specified
/// pluggable components.
/// </summary>
private readonly Hashtable applicationAttributes = null;
private IUberspect uberSpect;
private IDirectiveManager directiveManager;
public RuntimeInstance()
{
// logSystem = new PrimordialLogSystem();
configuration = new ExtendedProperties();
// create a VM factory, resource manager
// and introspector
vmFactory = new VelocimacroFactory(this);
// make a new introspector and initialize it
introspector = new Introspector(this);
// and a store for the application attributes
applicationAttributes = new Hashtable();
}
public ExtendedProperties Configuration
{
get { return configuration; }
set
{
if (overridingProperties == null)
{
overridingProperties = value;
}
else
{
// Avoid possible ConcurrentModificationException
if (overridingProperties != value)
{
overridingProperties.Combine(value);
}
}
}
}
public Introspector Introspector
{
get { return introspector; }
}
public void Init()
{
lock(this)
{
if (initialized == false)
{
initializeProperties();
initializeLogger();
initializeResourceManager();
initializeDirectives();
initializeParserPool();
initializeIntrospection();
// initialize the VM Factory. It will use the properties
// accessible from Runtime, so keep this here at the end.
vmFactory.InitVelocimacro();
initialized = true;
}
}
}
/// <summary>
/// Gets the classname for the Uberspect introspection package and
/// instantiates an instance.
/// </summary>
private void initializeIntrospection()
{
String rm = GetString(RuntimeConstants.UBERSPECT_CLASSNAME);
if (rm != null && rm.Length > 0)
{
Object o;
try
{
o = SupportClass.CreateNewInstance(Type.GetType(rm));
}
catch(System.Exception)
{
String err =
string.Format(
"The specified class for Uberspect ({0}) does not exist (or is not accessible to the current classlaoder.", rm);
Error(err);
throw new System.Exception(err);
}
if (!(o is IUberspect))
{
String err =
string.Format(
"The specified class for Uberspect ({0}) does not implement org.apache.velocity.util.introspector.Uberspect. Velocity not initialized correctly.",
rm);
Error(err);
throw new System.Exception(err);
}
uberSpect = (IUberspect) o;
if (uberSpect is UberspectLoggable)
{
((UberspectLoggable) uberSpect).RuntimeLogger = this;
}
uberSpect.Init();
}
else
{
// someone screwed up. Lets not fool around...
String err =
"It appears that no class was specified as the Uberspect. Please ensure that all configuration information is correct.";
Error(err);
throw new System.Exception(err);
}
}
/// <summary>
/// Initializes the Velocity Runtime with properties file.
/// The properties file may be in the file system proper,
/// or the properties file may be in the classpath.
/// </summary>
private void setDefaultProperties()
{
try
{
// TODO: this was modified in v1.4 to use the classloader
configuration.Load(
Assembly.GetExecutingAssembly().GetManifestResourceStream(RuntimeConstants.DEFAULT_RUNTIME_PROPERTIES));
}
catch(System.Exception ex)
{
debugOutput.WriteLine(string.Format("Cannot get NVelocity Runtime default properties!\n{0}", ex.Message));
debugOutput.Flush();
}
}
/// <summary>
/// Allows an external system to set a property in
/// the Velocity Runtime.
/// </summary>
/// <param name="key">property key </param>
/// <param name="value">property value</param>
public void SetProperty(String key, Object value)
{
if (overridingProperties == null)
{
overridingProperties = new ExtendedProperties();
}
overridingProperties.SetProperty(key, value);
}
/// <summary>
/// Add a property to the configuration. If it already
/// exists then the value stated here will be added
/// to the configuration entry.
/// <remarks>
/// For example, if
/// <c>resource.loader = file</c>
/// is already present in the configuration and you
/// <c>addProperty("resource.loader", "classpath")</c>
///
/// Then you will end up with a <see cref="IList"/> like the
/// following:
///
/// <c>["file", "classpath"]</c>
/// </remarks>
/// </summary>
/// <param name="key">key</param>
/// <param name="value">value</param>
public void AddProperty(String key, Object value)
{
if (overridingProperties == null)
{
overridingProperties = new ExtendedProperties();
}
overridingProperties.AddProperty(key, value);
}
/// <summary>
/// Clear the values pertaining to a particular
/// property.
/// </summary>
/// <param name="key">key of property to clear</param>
public void ClearProperty(String key)
{
if (overridingProperties != null)
{
overridingProperties.ClearProperty(key);
}
}
/// <summary>
/// Allows an external caller to get a property.
/// <remarks>
/// The calling routine is required to know the type, as this routine
/// will return an Object, as that is what properties can be.
/// </remarks>
/// </summary>
/// <param name="key">property to return</param>
public Object GetProperty(String key)
{
return configuration.GetProperty(key);
}
/// <summary>
/// Initialize Velocity properties, if the default
/// properties have not been laid down first then
/// do so. Then proceed to process any overriding
/// properties. Laying down the default properties
/// gives a much greater chance of having a
/// working system.
/// </summary>
private void initializeProperties()
{
// Always lay down the default properties first as
// to provide a solid base.
if (configuration.IsInitialized() == false)
{
setDefaultProperties();
}
if (overridingProperties != null)
{
configuration.Combine(overridingProperties);
}
}
/// <summary>
/// Initialize the Velocity Runtime with a Properties
/// object.
/// </summary>
/// <param name="p">Properties</param>
public void Init(ExtendedProperties p)
{
overridingProperties = ExtendedProperties.ConvertProperties(p);
Init();
}
/// <summary>
/// Initialize the Velocity Runtime with the name of
/// ExtendedProperties object.
/// </summary>
/// <param name="configurationFile">Properties</param>
public void Init(String configurationFile)
{
overridingProperties = new ExtendedProperties(configurationFile);
Init();
}
private void initializeResourceManager()
{
// Which resource manager?
IResourceManager rmInstance = (IResourceManager)
applicationAttributes[RuntimeConstants.RESOURCE_MANAGER_CLASS];
String rm = GetString(RuntimeConstants.RESOURCE_MANAGER_CLASS);
if (rmInstance == null && rm != null && rm.Length > 0)
{
// if something was specified, then make one.
// if that isn't a ResourceManager, consider
// this a huge error and throw
Object o;
try
{
Type rmType = Type.GetType(rm.Replace(';', ','));
o = Activator.CreateInstance(rmType);
}
catch(System.Exception ex)
{
String err = string.Format("The specified class for ResourceManager ({0}) does not exist.", rm);
Error(err);
throw new System.Exception(err, ex);
}
if (!(o is IResourceManager))
{
String err =
string.Format(
"The specified class for ResourceManager ({0}) does not implement ResourceManager. NVelocity not initialized correctly.",
rm);
Error(err);
throw new System.Exception(err);
}
resourceManager = (IResourceManager) o;
resourceManager.Initialize(this);
}
else if (rmInstance != null)
{
resourceManager = rmInstance;
resourceManager.Initialize(this);
}
else
{
// someone screwed up. Lets not fool around...
String err =
"It appears that no class was specified as the ResourceManager. Please ensure that all configuration information is correct.";
Error(err);
throw new System.Exception(err);
}
}
/// <summary> Initialize the Velocity logging system.
/// *
/// @throws Exception
/// </summary>
private void initializeLogger()
{
/*
* Initialize the logger. We will eventually move all
* logging into the logging manager.
*/
// if (logSystem is PrimordialLogSystem)
// {
// PrimordialLogSystem pls = (PrimordialLogSystem) logSystem;
// // logSystem = LogManager.createLogSystem(this);
// logSystem = new NullLogSystem();
//
// /*
// * in the event of failure, lets do something to let it
// * limp along.
// */
// if (logSystem == null)
// {
// logSystem = new NullLogSystem();
// }
// else
// {
// pls.DumpLogMessages(logSystem);
// }
// }
}
/// <summary> This methods initializes all the directives
/// that are used by the Velocity Runtime. The
/// directives to be initialized are listed in
/// the RUNTIME_DEFAULT_DIRECTIVES properties
/// file.
///
/// @throws Exception
/// </summary>
private void initializeDirectives()
{
initializeDirectiveManager();
/*
* Initialize the runtime directive table.
* This will be used for creating parsers.
*/
// runtimeDirectives = new Hashtable();
ExtendedProperties directiveProperties = new ExtendedProperties();
/*
* Grab the properties file with the list of directives
* that we should initialize.
*/
try
{
directiveProperties.Load(
Assembly.GetExecutingAssembly().GetManifestResourceStream(RuntimeConstants.DEFAULT_RUNTIME_DIRECTIVES));
}
catch(System.Exception ex)
{
throw new System.Exception(
string.Format(
"Error loading directive.properties! Something is very wrong if these properties aren't being located. Either your Velocity distribution is incomplete or your Velocity jar file is corrupted!\n{0}",
ex.Message));
}
/*
* Grab all the values of the properties. These
* are all class names for example:
*
* NVelocity.Runtime.Directive.Foreach
*/
IEnumerator directiveClasses = directiveProperties.Values.GetEnumerator();
while(directiveClasses.MoveNext())
{
String directiveClass = (String) directiveClasses.Current;
// loadDirective(directiveClass);
directiveManager.Register(directiveClass);
}
/*
* now the user's directives
*/
String[] userdirective = configuration.GetStringArray("userdirective");
for(int i = 0; i < userdirective.Length; i++)
{
// loadDirective(userdirective[i]);
directiveManager.Register(userdirective[i]);
}
}
private void initializeDirectiveManager()
{
String directiveManagerTypeName = configuration.GetString("directive.manager");
if (directiveManagerTypeName == null)
{
throw new System.Exception("Looks like there's no 'directive.manager' configured. NVelocity can't go any further");
}
directiveManagerTypeName = directiveManagerTypeName.Replace(';', ',');
Type dirMngType = Type.GetType(directiveManagerTypeName, false, false);
if (dirMngType == null)
{
throw new System.Exception(
String.Format("The type {0} could not be resolved", directiveManagerTypeName));
}
directiveManager = (IDirectiveManager) Activator.CreateInstance(dirMngType);
}
/// <summary> Initializes the Velocity parser pool.
/// This still needs to be implemented.
/// </summary>
private void initializeParserPool()
{
int numParsers = GetInt(RuntimeConstants.PARSER_POOL_SIZE, RuntimeConstants.NUMBER_OF_PARSERS);
parserPool = new SimplePool<Parser.Parser>(numParsers);
for(int i = 0; i < numParsers; i++)
{
parserPool.put(CreateNewParser());
}
}
/// <summary> Returns a JavaCC generated Parser.
/// </summary>
/// <returns>Parser javacc generated parser
/// </returns>
public Parser.Parser CreateNewParser()
{
Parser.Parser parser = new Parser.Parser(this);
parser.Directives = directiveManager;
return parser;
}
/// <summary>
/// Parse the input and return the root of
/// AST node structure.
/// <remarks>
/// In the event that it runs out of parsers in the
/// pool, it will create and let them be GC'd
/// dynamically, logging that it has to do that. This
/// is considered an exceptional condition. It is
/// expected that the user will set the
/// <c>PARSER_POOL_SIZE</c> property appropriately for their
/// application. We will revisit this.
/// </remarks>
/// </summary>
/// <param name="reader">inputstream retrieved by a resource loader</param>
/// <param name="templateName">name of the template being parsed</param>
public SimpleNode Parse(TextReader reader, String templateName)
{
// do it and dump the VM namespace for this template
return Parse(reader, templateName, true);
}
/// <summary>
/// Parse the input and return the root of the AST node structure.
/// </summary>
/// <param name="reader">inputstream retrieved by a resource loader</param>
/// <param name="templateName">name of the template being parsed</param>
/// <param name="dumpNamespace">flag to dump the Velocimacro namespace for this template</param>
public SimpleNode Parse(TextReader reader, String templateName, bool dumpNamespace)
{
SimpleNode ast = null;
Parser.Parser parser = (Parser.Parser) parserPool.get();
bool madeNew = false;
if (parser == null)
{
// if we couldn't get a parser from the pool
// make one and log it.
Error(
"Runtime : ran out of parsers. Creating new. Please increment the parser.pool.size property. The current value is too small.");
parser = CreateNewParser();
if (parser != null)
{
madeNew = true;
}
}
// now, if we have a parser
if (parser == null)
{
Error("Runtime : ran out of parsers and unable to create more.");
}
else
{
try
{
// dump namespace if we are told to. Generally, you want to
// do this - you don't in special circumstances, such as
// when a VM is getting init()-ed & parsed
if (dumpNamespace)
{
DumpVMNamespace(templateName);
}
ast = parser.Parse(reader, templateName);
}
finally
{
// if this came from the pool, then put back
if (!madeNew)
{
parserPool.put(parser);
}
}
}
return ast;
}
/// <summary>
/// Returns a <code>Template</code> from the resource manager.
/// This method assumes that the character encoding of the
/// template is set by the <code>input.encoding</code>
/// property. The default is "ISO-8859-1"
/// </summary>
/// <param name="name">The file name of the desired template.
/// </param>
/// <returns>The template.</returns>
/// <exception cref="ResourceNotFoundException">
/// if template not found from any available source
/// </exception>
/// <exception cref="ParseErrorException">
/// if template cannot be parsed due to syntax (or other) error.
/// </exception>
/// <exception cref="Exception">
/// if an error occurs in template initialization
/// </exception>
public Template GetTemplate(String name)
{
return GetTemplate(name, GetString(RuntimeConstants.INPUT_ENCODING, RuntimeConstants.ENCODING_DEFAULT));
}
/// <summary>
/// Returns a <code>Template</code> from the resource manager
/// </summary>
/// <param name="name">The name of the desired template.</param>
/// <param name="encoding">Character encoding of the template</param>
/// <returns>The template.</returns>
/// <exception cref="ResourceNotFoundException">
/// if template not found from any available source.
/// </exception>
/// <exception cref="ParseErrorException">
/// if template cannot be parsed due to syntax (or other) error.
/// </exception>
/// <exception cref="Exception">
/// if an error occurs in template initialization
/// </exception>
public Template GetTemplate(String name, String encoding)
{
return (Template) resourceManager.GetResource(name, ResourceType.Template, encoding);
}
/// <summary>
/// Returns a static content resource from the
/// resource manager. Uses the current value
/// if <c>INPUT_ENCODING</c> as the character encoding.
/// </summary>
/// <param name="name">Name of content resource to get</param>
/// <returns>ContentResource object ready for use</returns>
/// <exception cref="ResourceNotFoundException">
/// if template not found from any available source.
/// </exception>
public ContentResource GetContent(String name)
{
// the encoding is irrelevant as we don't do any conversation
// the bytestream should be dumped to the output stream
return GetContent(name, GetString(RuntimeConstants.INPUT_ENCODING, RuntimeConstants.ENCODING_DEFAULT));
}
/// <summary>
/// Returns a static content resource from the
/// resource manager.
/// </summary>
/// <param name="name">Name of content resource to get</param>
/// <param name="encoding">Character encoding to use</param>
/// <returns>ContentResource object ready for use</returns>
/// <exception cref="ResourceNotFoundException">
/// if template not found from any available source.
/// </exception>
public ContentResource GetContent(String name, String encoding)
{
return (ContentResource) resourceManager.GetResource(name, ResourceType.Content, encoding);
}
/// <summary>
/// Determines is a template exists, and returns name of the loader that
/// provides it. This is a slightly less hokey way to support
/// the <c>Velocity.templateExists()</c> utility method, which was broken
/// when per-template encoding was introduced. We can revisit this.
/// </summary>
/// <param name="resourceName">Name of template or content resource</param>
/// <returns>class name of loader than can provide it</returns>
public String GetLoaderNameForResource(String resourceName)
{
return resourceManager.GetLoaderNameForResource(resourceName);
}
/// <summary>
/// Added this to check and make sure that the configuration
/// is initialized before trying to get properties from it.
/// This occurs when there are errors during initialization
/// and the default properties have yet to be layed down.
/// </summary>
private bool showStackTrace()
{
if (configuration.IsInitialized())
{
return GetBoolean(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, false);
}
else
{
return false;
}
}
/// <summary>
/// Handle logging.
/// </summary>
/// <param name="level">log level</param>
/// <param name="message">message to log</param>
private void Log(LogLevel level, Object message)
{
// String output = message.ToString();
// just log it, as we are guaranteed now to have some
// kind of logger - save the if()
// logSystem.LogVelocityMessage(level, output);
}
/// <summary>
/// Log a warning message.
/// </summary>
/// <param name="message">message to log</param>
public void Warn(Object message)
{
Log(LogLevel.Warn, message);
}
/// <summary>
/// Log an info message.
/// </summary>
/// <param name="message">message to log</param>
public void Info(Object message)
{
Log(LogLevel.Info, message);
}
/// <summary>
/// Log an error message.
/// </summary>
/// <param name="message">message to log</param>
public void Error(Object message)
{
Log(LogLevel.Error, message);
}
/// <summary>
/// Log a debug message.
/// </summary>
/// <param name="message">message to log</param>
public void Debug(Object message)
{
Log(LogLevel.Debug, message);
}
/// <summary>
/// String property accessor method with default to hide the
/// configuration implementation.
/// </summary>
/// <param name="key">key property key</param>
/// <param name="defaultValue">default value to return if key not found in resource manager.</param>
/// <returns>String value of key or default</returns>
public String GetString(String key, String defaultValue)
{
return configuration.GetString(key, defaultValue);
}
/// <summary>
/// Returns the appropriate VelocimacroProxy object if strVMname
/// is a valid current Velocimacro.
/// </summary>
/// <param name="vmName">Name of velocimacro requested</param>
/// <param name="templateName">Name of template</param>
/// <returns>VelocimacroProxy</returns>
public Directive.Directive GetVelocimacro(String vmName, String templateName)
{
return vmFactory.GetVelocimacro(vmName, templateName);
}
/// <summary>
/// Adds a new Velocimacro. Usually called by Macro only while parsing.
/// </summary>
/// <param name="name">Name of velocimacro</param>
/// <param name="macro">String form of macro body</param>
/// <param name="argArray">Array of strings, containing the #macro() arguments. the 0th is the name.</param>
/// <param name="sourceTemplate">Name of template</param>
/// <returns>
/// True if added, false if rejected for some
/// reason (either parameters or permission settings)
/// </returns>
public bool AddVelocimacro(String name, String macro, String[] argArray, String sourceTemplate)
{
return vmFactory.AddVelocimacro(name, macro, argArray, sourceTemplate);
}
/// <summary>
/// Checks to see if a VM exists
/// </summary>
/// <param name="vmName">Name of velocimacro</param>
/// <param name="templateName">Name of template</param>
/// <returns>
/// True if VM by that name exists, false if not
/// </returns>
public bool IsVelocimacro(String vmName, String templateName)
{
return vmFactory.IsVelocimacro(vmName, templateName);
}
/// <summary>
/// Tells the vmFactory to dump the specified namespace.
/// This is to support clearing the VM list when in
/// <c>inline-VM-local-scope</c> mode.
/// </summary>
public bool DumpVMNamespace(String ns)
{
return vmFactory.DumpVMNamespace(ns);
}
/* --------------------------------------------------------------------
* R U N T I M E A C C E S S O R M E T H O D S
* --------------------------------------------------------------------
* These are the getXXX() methods that are a simple wrapper
* around the configuration object. This is an attempt
* to make a the Velocity Runtime the single access point
* for all things Velocity, and allow the Runtime to
* adhere as closely as possible the the Mediator pattern
* which is the ultimate goal.
* --------------------------------------------------------------------
*/
/// <summary>
/// String property accessor method to hide the configuration implementation
/// </summary>
/// <param name="key">property key</param>
/// <returns>value of key or null</returns>
public String GetString(String key)
{
return configuration.GetString(key);
}
/// <summary>
/// Int property accessor method to hide the configuration implementation.
/// </summary>
/// <param name="key">property key</param>
/// <returns>value</returns>
public int GetInt(String key)
{
return configuration.GetInt(key);
}
/// <summary>
/// Int property accessor method to hide the configuration implementation.
/// </summary>
/// <param name="key">property key</param>
/// <param name="defaultValue">default value</param>
/// <returns>value</returns>
public int GetInt(String key, int defaultValue)
{
return configuration.GetInt(key, defaultValue);
}
/// <summary>
/// Boolean property accessor method to hide the configuration implementation.
/// </summary>
/// <param name="key">property key</param>
/// <param name="def">default value if property not found</param>
/// <returns>boolean value of key or default value</returns>
public bool GetBoolean(String key, bool def)
{
return configuration.GetBoolean(key, def);
}
/// <summary>
/// Return the velocity runtime configuration object.
/// </summary>
/// <returns>
/// ExtendedProperties configuration object which houses
/// the velocity runtime properties.
/// </returns>
public Object GetApplicationAttribute(Object key)
{
return applicationAttributes[key];
}
public Object SetApplicationAttribute(Object key, Object o)
{
return applicationAttributes[key] = o;
}
/// <summary>
/// Return the Introspector for this instance
/// </summary>
public IUberspect Uberspect
{
get { return uberSpect; }
}
}
} | 29.867147 | 203 | 0.664115 | [
"Apache-2.0"
] | Telligent/NVelocity | src/NVelocity/Runtime/RuntimeInstance.cs | 29,001 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DancingGoat.Helpers.Extensions
{
public class DateTimeFormatterParameters
{
public string FormatCharacter { get; set; }
}
} | 20 | 51 | 0.7375 | [
"MIT"
] | FunkyGhost/cloud-sample-app-net | DancingGoat/Helpers/Extensions/DateTimeFormatterParameters.cs | 242 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace EPPlusTool.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.3.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 36.148148 | 151 | 0.563525 | [
"MIT"
] | HZ-GeLiang/EpplusHelper | EPPlusHelperTool/Properties/Settings.Designer.cs | 1,084 | C# |
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Routing;
using LightPlugin.Core;
using LightPlugin.Core.Caching;
using LightPlugin.Services.Cms;
//using LightPlugin.Web.Infrastructure.Cache;
//using LightPlugin.Web.Models.Cms;
using WebUI.Models.Cms;
namespace WebUI.Controllers
{
public partial class WidgetController : Controller
{
#region Fields
private readonly IWidgetService _widgetService;
//private readonly IStoreContext _storeContext;
private readonly ICacheManager _cacheManager;
#endregion
#region Constructors
public WidgetController()
{
this._widgetService = new WidgetService(new LightPlugin.Core.Plugins.PluginFinder(), new LightPlugin.Core.Domain.Cms.WidgetSettings());
//this._storeContext = storeContext;
this._cacheManager = new PerRequestCacheManager(HttpContext);
}
#endregion
#region Methods
[ChildActionOnly]
public ActionResult WidgetsByZone(string widgetZone, object additionalData = null)
{
try
{
var cacheKey = string.Format("Nop.pres.widget-{0}-{1}", 1, widgetZone);
//var cacheModel = _cacheManager.Get(cacheKey, () =>
//{
// //model
// var model = new List<RenderWidgetModel>();
// var widgets = _widgetService.LoadActiveWidgetsByWidgetZone(widgetZone);
// foreach (var widget in widgets)
// {
// var widgetModel = new RenderWidgetModel();
// string actionName;
// string controllerName;
// RouteValueDictionary routeValues;
// widget.GetDisplayWidgetRoute(widgetZone, out actionName, out controllerName, out routeValues);
// widgetModel.ActionName = actionName;
// widgetModel.ControllerName = controllerName;
// widgetModel.RouteValues = routeValues;
// model.Add(widgetModel);
// }
// return model;
//});
var model = new List<RenderWidgetModel>();
var widgets = _widgetService.LoadActiveWidgetsByWidgetZone(widgetZone);
foreach (var widget in widgets)
{
var widgetModel = new RenderWidgetModel();
string actionName;
string controllerName;
RouteValueDictionary routeValues;
widget.GetDisplayWidgetRoute(widgetZone, out actionName, out controllerName, out routeValues);
widgetModel.ActionName = actionName;
widgetModel.ControllerName = controllerName;
widgetModel.RouteValues = routeValues;
model.Add(widgetModel);
}
//no data?
if (model.Count == 0)
return Content("");
//"RouteValues" property of widget models depends on "additionalData".
//We need to clone the cached model before modifications (the updated one should not be cached)
var clonedModel = new List<RenderWidgetModel>();
foreach (var widgetModel in model)
{
var clonedWidgetModel = new RenderWidgetModel();
clonedWidgetModel.ActionName = widgetModel.ActionName;
clonedWidgetModel.ControllerName = widgetModel.ControllerName;
if (widgetModel.RouteValues != null)
clonedWidgetModel.RouteValues = new RouteValueDictionary(widgetModel.RouteValues);
if (additionalData != null)
{
if (clonedWidgetModel.RouteValues == null)
clonedWidgetModel.RouteValues = new RouteValueDictionary();
clonedWidgetModel.RouteValues.Add("additionalData", additionalData);
}
clonedModel.Add(clonedWidgetModel);
}
return PartialView(clonedModel);
}
catch (System.Exception ex)
{
}
return null;
}
#endregion
}
}
| 36.422764 | 147 | 0.552455 | [
"Apache-2.0"
] | yiyungent/TES | src/WebUI/Controllers/WidgetController.cs | 4,482 | C# |
using UnityEngine;
using System.Collections.Generic;
// Empty namespace declaration to avoid errors in the free version
// Which does not have any classes in the RVO namespace
namespace Pathfinding.RVO {}
namespace Pathfinding {
using Pathfinding.Jobs;
using Pathfinding.Util;
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
#if UNITY_5_0
/// <summary>Used in Unity 5.0 since the HelpURLAttribute was first added in Unity 5.1</summary>
public class HelpURLAttribute : Attribute {
}
#endif
[System.Serializable]
/// <summary>Stores editor colors</summary>
public class AstarColor {
public Color _SolidColor;
public Color _UnwalkableNode;
public Color _BoundsHandles;
public Color _ConnectionLowLerp;
public Color _ConnectionHighLerp;
public Color _MeshEdgeColor;
/// <summary>
/// Holds user set area colors.
/// Use GetAreaColor to get an area color
/// </summary>
public Color[] _AreaColors;
public static Color SolidColor = new Color(30/255f, 102/255f, 201/255f, 0.9F);
public static Color UnwalkableNode = new Color(1, 0, 0, 0.5F);
public static Color BoundsHandles = new Color(0.29F, 0.454F, 0.741F, 0.9F);
public static Color ConnectionLowLerp = new Color(0, 1, 0, 0.5F);
public static Color ConnectionHighLerp = new Color(1, 0, 0, 0.5F);
public static Color MeshEdgeColor = new Color(0, 0, 0, 0.5F);
private static Color[] AreaColors = new Color[1];
public static int ColorHash () {
var hash = SolidColor.GetHashCode() ^ UnwalkableNode.GetHashCode() ^ BoundsHandles.GetHashCode() ^ ConnectionLowLerp.GetHashCode() ^ ConnectionHighLerp.GetHashCode() ^ MeshEdgeColor.GetHashCode();
for (int i = 0; i < AreaColors.Length; i++) hash = 7*hash ^ AreaColors[i].GetHashCode();
return hash;
}
/// <summary>
/// Returns an color for an area, uses both user set ones and calculated.
/// If the user has set a color for the area, it is used, but otherwise the color is calculated using AstarMath.IntToColor
/// See: <see cref="RemappedAreaColors"/>
/// </summary>
public static Color GetAreaColor (uint area) {
if (area >= AreaColors.Length) return AstarMath.IntToColor((int)area, 1F);
return AreaColors[(int)area];
}
/// <summary>
/// Returns an color for a tag, uses both user set ones and calculated.
/// If the user has set a color for the tag, it is used, but otherwise the color is calculated using AstarMath.IntToColor
/// See: <see cref="AreaColors"/>
/// </summary>
public static Color GetTagColor (uint tag) {
if (tag >= AreaColors.Length) return AstarMath.IntToColor((int)tag, 1F);
return AreaColors[(int)tag];
}
/// <summary>
/// Pushes all local variables out to static ones.
/// This is done because that makes it so much easier to access the colors during Gizmo rendering
/// and it has a positive performance impact as well (gizmo rendering is hot code).
/// It is a bit ugly though, but oh well.
/// </summary>
public void PushToStatic (AstarPath astar) {
_AreaColors = _AreaColors ?? new Color[1];
SolidColor = _SolidColor;
UnwalkableNode = _UnwalkableNode;
BoundsHandles = _BoundsHandles;
ConnectionLowLerp = _ConnectionLowLerp;
ConnectionHighLerp = _ConnectionHighLerp;
MeshEdgeColor = _MeshEdgeColor;
AreaColors = _AreaColors;
}
public AstarColor () {
// Set default colors
_SolidColor = new Color(30/255f, 102/255f, 201/255f, 0.9F);
_UnwalkableNode = new Color(1, 0, 0, 0.5F);
_BoundsHandles = new Color(0.29F, 0.454F, 0.741F, 0.9F);
_ConnectionLowLerp = new Color(0, 1, 0, 0.5F);
_ConnectionHighLerp = new Color(1, 0, 0, 0.5F);
_MeshEdgeColor = new Color(0, 0, 0, 0.5F);
}
}
/// <summary>
/// Returned by graph ray- or linecasts containing info about the hit.
/// This is the return value by the <see cref="Pathfinding.IRaycastableGraph.Linecast"/> methods.
/// Some members will also be initialized even if nothing was hit, see the individual member descriptions for more info.
///
/// [Open online documentation to see images]
/// </summary>
public struct GraphHitInfo {
/// <summary>
/// Start of the line/ray.
/// Note that the point passed to the Linecast method will be clamped to the closest point on the navmesh.
/// </summary>
public Vector3 origin;
/// <summary>
/// Hit point.
/// In case no obstacle was hit then this will be set to the endpoint of the line.
/// </summary>
public Vector3 point;
/// <summary>
/// Node which contained the edge which was hit.
/// If the linecast did not hit anything then this will be set to the last node along the line's path (the one which contains the endpoint).
///
/// For layered grid graphs the linecast will return true (i.e: no free line of sight) if when walking the graph we ended up at X,Z coordinate for the end node
/// even if end node was on a different level (e.g the floor below or above in a building). In this case no node edge was really hit so this field will still be null.
/// </summary>
public GraphNode node;
/// <summary>
/// Where the tangent starts. <see cref="tangentOrigin"/> and <see cref="tangent"/> together actually describes the edge which was hit.
/// [Open online documentation to see images]
/// </summary>
public Vector3 tangentOrigin;
/// <summary>
/// Tangent of the edge which was hit.
/// [Open online documentation to see images]
/// </summary>
public Vector3 tangent;
/// <summary>Distance from <see cref="origin"/> to <see cref="point"/></summary>
public float distance {
get {
return (point-origin).magnitude;
}
}
public GraphHitInfo (Vector3 point) {
tangentOrigin = Vector3.zero;
origin = Vector3.zero;
this.point = point;
node = null;
tangent = Vector3.zero;
}
}
/// <summary>Nearest node constraint. Constrains which nodes will be returned by the <see cref="AstarPath.GetNearest"/> function</summary>
public class NNConstraint {
/// <summary>
/// Graphs treated as valid to search on.
/// This is a bitmask meaning that bit 0 specifies whether or not the first graph in the graphs list should be able to be included in the search,
/// bit 1 specifies whether or not the second graph should be included and so on.
/// <code>
/// // Enables the first and third graphs to be included, but not the rest
/// myNNConstraint.graphMask = (1 << 0) | (1 << 2);
/// </code>
/// <code>
/// GraphMask mask1 = GraphMask.FromGraphName("My Grid Graph");
/// GraphMask mask2 = GraphMask.FromGraphName("My Other Grid Graph");
///
/// NNConstraint nn = NNConstraint.Default;
///
/// nn.graphMask = mask1 | mask2;
///
/// // Find the node closest to somePoint which is either in 'My Grid Graph' OR in 'My Other Grid Graph'
/// var info = AstarPath.active.GetNearest(somePoint, nn);
/// </code>
///
/// Note: This does only affect which nodes are returned from a <see cref="AstarPath.GetNearest"/> call, if a valid graph is connected to an invalid graph using a node link then it might be searched anyway.
///
/// See: <see cref="AstarPath.GetNearest"/>
/// See: <see cref="SuitableGraph"/>
/// See: bitmasks (view in online documentation for working links)
/// </summary>
public GraphMask graphMask = -1;
/// <summary>Only treat nodes in the area <see cref="area"/> as suitable. Does not affect anything if <see cref="area"/> is less than 0 (zero)</summary>
public bool constrainArea;
/// <summary>Area ID to constrain to. Will not affect anything if less than 0 (zero) or if <see cref="constrainArea"/> is false</summary>
public int area = -1;
/// <summary>Constrain the search to only walkable or unwalkable nodes depending on <see cref="walkable"/>.</summary>
public bool constrainWalkability = true;
/// <summary>
/// Only search for walkable or unwalkable nodes if <see cref="constrainWalkability"/> is enabled.
/// If true, only walkable nodes will be searched for, otherwise only unwalkable nodes will be searched for.
/// Does not affect anything if <see cref="constrainWalkability"/> if false.
/// </summary>
public bool walkable = true;
/// <summary>
/// if available, do an XZ check instead of checking on all axes.
/// The navmesh/recast graph supports this.
///
/// This can be important on sloped surfaces. See the image below in which the closest point for each blue point is queried for:
/// [Open online documentation to see images]
///
/// The navmesh/recast graphs also contain a global option for this: <see cref="Pathfinding.NavmeshBase.nearestSearchOnlyXZ"/>.
/// </summary>
public bool distanceXZ;
/// <summary>
/// Sets if tags should be constrained.
/// See: <see cref="tags"/>
/// </summary>
public bool constrainTags = true;
/// <summary>
/// Nodes which have any of these tags set are suitable.
/// This is a bitmask, i.e bit 0 indicates that tag 0 is good, bit 3 indicates tag 3 is good etc.
/// See: <see cref="constrainTags"/>
/// See: <see cref="graphMask"/>
/// See: bitmasks (view in online documentation for working links)
/// </summary>
public int tags = -1;
/// <summary>
/// Constrain distance to node.
/// Uses distance from <see cref="AstarPath.maxNearestNodeDistance"/>.
/// If this is false, it will completely ignore the distance limit.
///
/// If there are no suitable nodes within the distance limit then the search will terminate with a null node as a result.
/// Note: This value is not used in this class, it is used by the AstarPath.GetNearest function.
/// </summary>
public bool constrainDistance = true;
/// <summary>
/// Returns whether or not the graph conforms to this NNConstraint's rules.
/// Note that only the first 31 graphs are considered using this function.
/// If the <see cref="graphMask"/> has bit 31 set (i.e the last graph possible to fit in the mask), all graphs
/// above index 31 will also be considered suitable.
/// </summary>
public virtual bool SuitableGraph (int graphIndex, NavGraph graph) {
return graphMask.Contains(graphIndex);
}
/// <summary>Returns whether or not the node conforms to this NNConstraint's rules</summary>
public virtual bool Suitable (GraphNode node) {
if (constrainWalkability && node.Walkable != walkable) return false;
if (constrainArea && area >= 0 && node.Area != area) return false;
if (constrainTags && ((tags >> (int)node.Tag) & 0x1) == 0) return false;
return true;
}
/// <summary>
/// The default NNConstraint.
/// Equivalent to new NNConstraint ().
/// This NNConstraint has settings which works for most, it only finds walkable nodes
/// and it constrains distance set by A* Inspector -> Settings -> Max Nearest Node Distance
/// </summary>
public static NNConstraint Default {
get {
return new NNConstraint();
}
}
/// <summary>Returns a constraint which does not filter the results</summary>
public static NNConstraint None {
get {
return new NNConstraint {
constrainWalkability = false,
constrainArea = false,
constrainTags = false,
constrainDistance = false,
graphMask = -1,
};
}
}
/// <summary>Default constructor. Equals to the property <see cref="Default"/></summary>
public NNConstraint () {
}
}
/// <summary>
/// A special NNConstraint which can use different logic for the start node and end node in a path.
/// A PathNNConstraint can be assigned to the Path.nnConstraint field, the path will first search for the start node, then it will call <see cref="SetStart"/> and proceed with searching for the end node (nodes in the case of a MultiTargetPath).\n
/// The default PathNNConstraint will constrain the end point to lie inside the same area as the start point.
/// </summary>
public class PathNNConstraint : NNConstraint {
public static new PathNNConstraint Default {
get {
return new PathNNConstraint {
constrainArea = true
};
}
}
/// <summary>Called after the start node has been found. This is used to get different search logic for the start and end nodes in a path</summary>
public virtual void SetStart (GraphNode node) {
if (node != null) {
area = (int)node.Area;
} else {
constrainArea = false;
}
}
}
/// <summary>
/// Internal result of a nearest node query.
/// See: NNInfo
/// </summary>
public struct NNInfoInternal {
/// <summary>
/// Closest node found.
/// This node is not necessarily accepted by any NNConstraint passed.
/// See: constrainedNode
/// </summary>
public GraphNode node;
/// <summary>
/// Optional to be filled in.
/// If the search will be able to find the constrained node without any extra effort it can fill it in.
/// </summary>
public GraphNode constrainedNode;
/// <summary>The position clamped to the closest point on the <see cref="node"/>.</summary>
public Vector3 clampedPosition;
/// <summary>Clamped position for the optional constrainedNode</summary>
public Vector3 constClampedPosition;
public NNInfoInternal (GraphNode node) {
this.node = node;
constrainedNode = null;
clampedPosition = Vector3.zero;
constClampedPosition = Vector3.zero;
UpdateInfo();
}
/// <summary>Updates <see cref="clampedPosition"/> and <see cref="constClampedPosition"/> from node positions</summary>
public void UpdateInfo () {
clampedPosition = node != null ? (Vector3)node.position : Vector3.zero;
constClampedPosition = constrainedNode != null ? (Vector3)constrainedNode.position : Vector3.zero;
}
}
/// <summary>Result of a nearest node query</summary>
public struct NNInfo {
/// <summary>Closest node</summary>
public readonly GraphNode node;
/// <summary>
/// Closest point on the navmesh.
/// This is the query position clamped to the closest point on the <see cref="node"/>.
/// </summary>
public readonly Vector3 position;
/// <summary>
/// Closest point on the navmesh.
/// Deprecated: This field has been renamed to <see cref="position"/>
/// </summary>
[System.Obsolete("This field has been renamed to 'position'")]
public Vector3 clampedPosition {
get {
return position;
}
}
public NNInfo (NNInfoInternal internalInfo) {
node = internalInfo.node;
position = internalInfo.clampedPosition;
}
public static explicit operator Vector3(NNInfo ob) {
return ob.position;
}
public static explicit operator GraphNode(NNInfo ob) {
return ob.node;
}
}
/// <summary>
/// Progress info for e.g a progressbar.
/// Used by the scan functions in the project
/// See: <see cref="AstarPath.ScanAsync"/>
/// </summary>
public struct Progress {
/// <summary>Current progress as a value between 0 and 1</summary>
public readonly float progress;
/// <summary>Description of what is currently being done</summary>
public readonly string description;
public Progress (float progress, string description) {
this.progress = progress;
this.description = description;
}
public Progress MapTo (float min, float max, string prefix = null) {
return new Progress(Mathf.Lerp(min, max, progress), prefix + description);
}
public override string ToString () {
return progress.ToString("0.0") + " " + description;
}
}
/// <summary>Graphs which can be updated during runtime</summary>
public interface IUpdatableGraph {
/// <summary>
/// Updates an area using the specified <see cref="GraphUpdateObject"/>.
///
/// Notes to implementators.
/// This function should (in order):
/// -# Call o.WillUpdateNode on the GUO for every node it will update, it is important that this is called BEFORE any changes are made to the nodes.
/// -# Update walkabilty using special settings such as the usePhysics flag used with the GridGraph.
/// -# Call Apply on the GUO for every node which should be updated with the GUO.
/// -# Update connectivity info if appropriate (GridGraphs updates connectivity, but most other graphs don't since then the connectivity cannot be recovered later).
/// </summary>
void UpdateArea(GraphUpdateObject o);
/// <summary>
/// May be called on the Unity thread before starting the update.
/// See: CanUpdateAsync
/// </summary>
void UpdateAreaInit(GraphUpdateObject o);
/// <summary>
/// May be called on the Unity thread after executing the update.
/// See: CanUpdateAsync
/// </summary>
void UpdateAreaPost(GraphUpdateObject o);
GraphUpdateThreading CanUpdateAsync(GraphUpdateObject o);
}
/// <summary>
/// Represents a collection of settings used to update nodes in a specific region of a graph.
/// See: AstarPath.UpdateGraphs
/// See: graph-updates (view in online documentation for working links)
/// </summary>
public class GraphUpdateObject {
/// <summary>
/// The bounds to update nodes within.
/// Defined in world space.
/// </summary>
public Bounds bounds;
/// <summary>
/// Controlls if a flood fill will be carried out after this GUO has been applied.
/// Disabling this can be used to gain a performance boost, but use with care.
/// If you are sure that a GUO will not modify walkability or connections. You can set this to false.
/// For example when only updating penalty values it can save processing power when setting this to false. Especially on large graphs.
/// Note: If you set this to false, even though it does change e.g walkability, it can lead to paths returning that they failed even though there is a path,
/// or the try to search the whole graph for a path even though there is none, and will in the processes use wast amounts of processing power.
///
/// If using the basic GraphUpdateObject (not a derived class), a quick way to check if it is going to need a flood fill is to check if <see cref="modifyWalkability"/> is true or <see cref="updatePhysics"/> is true.
///
/// Deprecated: Not necessary anymore
/// </summary>
[System.Obsolete("Not necessary anymore")]
public bool requiresFloodFill { set {} }
/// <summary>
/// Use physics checks to update nodes.
/// When updating a grid graph and this is true, the nodes' position and walkability will be updated using physics checks
/// with settings from "Collision Testing" and "Height Testing".
///
/// When updating a PointGraph, setting this to true will make it re-evaluate all connections in the graph which passes through the <see cref="bounds"/>.
/// This has no effect when updating GridGraphs if <see cref="modifyWalkability"/> is turned on.
///
/// On RecastGraphs, having this enabled will trigger a complete recalculation of all tiles intersecting the bounds.
/// This is quite slow (but powerful). If you only want to update e.g penalty on existing nodes, leave it disabled.
/// </summary>
public bool updatePhysics = true;
/// <summary>
/// Reset penalties to their initial values when updating grid graphs and <see cref="updatePhysics"/> is true.
/// If you want to keep old penalties even when you update the graph you may want to disable this option.
///
/// The images below shows two overlapping graph update objects, the right one happened to be applied before the left one. They both have updatePhysics = true and are
/// set to increase the penalty of the nodes by some amount.
///
/// The first image shows the result when resetPenaltyOnPhysics is false. Both penalties are added correctly.
/// [Open online documentation to see images]
///
/// This second image shows when resetPenaltyOnPhysics is set to true. The first GUO is applied correctly, but then the second one (the left one) is applied
/// and during its updating, it resets the penalties first and then adds penalty to the nodes. The result is that the penalties from both GUOs are not added together.
/// The green patch in at the border is there because physics recalculation (recalculation of the position of the node, checking for obstacles etc.) affects a slightly larger
/// area than the original GUO bounds because of the Grid Graph -> Collision Testing -> Diameter setting (it is enlarged by that value). So some extra nodes have their penalties reset.
///
/// [Open online documentation to see images]
///
/// \bug Not working with burst
/// </summary>
public bool resetPenaltyOnPhysics = true;
/// <summary>
/// Update Erosion for GridGraphs.
/// When enabled, erosion will be recalculated for grid graphs
/// after the GUO has been applied.
///
/// In the below image you can see the different effects you can get with the different values.\n
/// The first image shows the graph when no GUO has been applied. The blue box is not identified as an obstacle by the graph, the reason
/// there are unwalkable nodes around it is because there is a height difference (nodes are placed on top of the box) so erosion will be applied (an erosion value of 2 is used in this graph).
/// The orange box is identified as an obstacle, so the area of unwalkable nodes around it is a bit larger since both erosion and collision has made
/// nodes unwalkable.\n
/// The GUO used simply sets walkability to true, i.e making all nodes walkable.
///
/// [Open online documentation to see images]
///
/// When updateErosion=True, the reason the blue box still has unwalkable nodes around it is because there is still a height difference
/// so erosion will still be applied. The orange box on the other hand has no height difference and all nodes are set to walkable.\n
/// \n
/// When updateErosion=False, all nodes walkability are simply set to be walkable in this example.
///
/// See: Pathfinding.GridGraph
///
/// \bug Not working with burst
/// </summary>
public bool updateErosion = true;
/// <summary>
/// NNConstraint to use.
/// The Pathfinding.NNConstraint.SuitableGraph function will be called on the NNConstraint to enable filtering of which graphs to update.\n
/// Note: As the Pathfinding.NNConstraint.SuitableGraph function is A* Pathfinding Project Pro only, this variable doesn't really affect anything in the free version.
/// </summary>
public NNConstraint nnConstraint = NNConstraint.None;
/// <summary>
/// Penalty to add to the nodes.
/// A penalty of 1000 is equivalent to the cost of moving 1 world unit.
/// </summary>
public int addPenalty;
/// <summary>If true, all nodes' walkable variable will be set to <see cref="setWalkability"/></summary>
public bool modifyWalkability;
/// <summary>If <see cref="modifyWalkability"/> is true, the nodes' walkable variable will be set to this value</summary>
public bool setWalkability;
/// <summary>If true, all nodes' tag will be set to <see cref="setTag"/></summary>
public bool modifyTag;
/// <summary>If <see cref="modifyTag"/> is true, all nodes' tag will be set to this value</summary>
public int setTag;
/// <summary>
/// Track which nodes are changed and save backup data.
/// Used internally to revert changes if needed.
/// </summary>
public bool trackChangedNodes;
/// <summary>
/// Nodes which were updated by this GraphUpdateObject.
/// Will only be filled if <see cref="trackChangedNodes"/> is true.
/// Note: It might take a few frames for graph update objects to be applied.
/// If you need this info immediately, use <see cref="AstarPath.FlushGraphUpdates"/>.
/// </summary>
public List<GraphNode> changedNodes;
private List<uint> backupData;
private List<Int3> backupPositionData;
/// <summary>
/// A shape can be specified if a bounds object does not give enough precision.
/// Note that if you set this, you should set the bounds so that it encloses the shape
/// because the bounds will be used as an initial fast check for which nodes that should
/// be updated.
/// </summary>
public GraphUpdateShape shape;
/// <summary>
/// Should be called on every node which is updated with this GUO before it is updated.
/// See: <see cref="trackChangedNodes"/>
/// </summary>
/// <param name="node">The node to save fields for. If null, nothing will be done</param>
public virtual void WillUpdateNode (GraphNode node) {
if (trackChangedNodes && node != null) {
if (changedNodes == null) { changedNodes = ListPool<GraphNode>.Claim(); backupData = ListPool<uint>.Claim(); backupPositionData = ListPool<Int3>.Claim(); }
changedNodes.Add(node);
backupPositionData.Add(node.position);
backupData.Add(node.Penalty);
backupData.Add(node.Flags);
#if !ASTAR_NO_GRID_GRAPH
var gridNode = node as GridNode;
if (gridNode != null) backupData.Add(gridNode.InternalGridFlags);
#endif
}
}
/// <summary>
/// Reverts penalties and flags (which includes walkability) on every node which was updated using this GUO.
/// Data for reversion is only saved if <see cref="trackChangedNodes"/> is true.
///
/// Note: Not all data is saved. The saved data includes: penalties, walkability, tags, area, position and for grid graphs (not layered) it also includes connection data.
///
/// This method modifies the graph. So it must be called inside while it is safe to modify the graph, for example inside a work item as shown in the example below.
///
/// \miscsnippets MiscSnippets.cs GraphUpdateObject.RevertFromBackup
///
/// See: blocking (view in online documentation for working links)
/// See: <see cref="Pathfinding.PathUtilities.UpdateGraphsNoBlock"/>
/// </summary>
public virtual void RevertFromBackup () {
if (trackChangedNodes) {
if (changedNodes == null) return;
int counter = 0;
for (int i = 0; i < changedNodes.Count; i++) {
changedNodes[i].Penalty = backupData[counter];
counter++;
// Restore the flags, but not the HierarchicalNodeIndex as that could screw up some internal datastructures
var tmp = changedNodes[i].HierarchicalNodeIndex;
changedNodes[i].Flags = backupData[counter];
changedNodes[i].HierarchicalNodeIndex = tmp;
counter++;
#if !ASTAR_NO_GRID_GRAPH
var gridNode = changedNodes[i] as GridNode;
if (gridNode != null) {
gridNode.InternalGridFlags = (ushort)backupData[counter];
counter++;
}
#endif
changedNodes[i].position = backupPositionData[i];
changedNodes[i].SetConnectivityDirty();
}
ListPool<GraphNode>.Release(ref changedNodes);
ListPool<uint>.Release(ref backupData);
ListPool<Int3>.Release(ref backupPositionData);
} else {
throw new System.InvalidOperationException("Changed nodes have not been tracked, cannot revert from backup. Please set trackChangedNodes to true before applying the update.");
}
}
/// <summary>Updates the specified node using this GUO's settings</summary>
public virtual void Apply (GraphNode node) {
if (shape == null || shape.Contains(node)) {
//Update penalty and walkability
node.Penalty = (uint)(node.Penalty+addPenalty);
if (modifyWalkability) {
node.Walkable = setWalkability;
}
//Update tags
if (modifyTag) node.Tag = (uint)setTag;
}
}
/// <summary>Provides burst-readable data to a graph update job</summary>
public struct GraphUpdateData {
public NativeArray<Vector3> nodePositions;
public NativeArray<uint> nodePenalties;
public NativeArray<bool> nodeWalkable;
public NativeArray<int> nodeTags;
};
/// <summary>Helper for iterating through the nodes that should be updated</summary>
public interface INodeIndexMapper {
int Count { get; }
int this[int index] { get; }
}
/// <summary>Job for applying a graph update object</summary>
[BurstCompile]
public struct JobGraphUpdate<T> : IJob where T : INodeIndexMapper {
public T mapper;
public GraphUpdateShape.BurstShape shape;
public NativeArray<Vector3> nodePositions;
public NativeArray<uint> nodePenalties;
public NativeArray<bool> nodeWalkable;
public NativeArray<int> nodeTags;
public Bounds bounds;
public int penaltyDelta;
public bool modifyWalkability;
public bool walkabilityValue;
public bool modifyTag;
public int tagValue;
public void Execute () {
for (int i = 0; i < mapper.Count; i++) {
var node = mapper[i];
if (bounds.Contains(nodePositions[node]) && shape.Contains(nodePositions[node])) {
nodePenalties[node] += (uint)penaltyDelta;
if (modifyWalkability) nodeWalkable[node] = walkabilityValue;
if (modifyTag) nodeTags[node] = tagValue;
}
}
}
};
/// <summary>
/// Update a set of nodes using this GUO's settings.
/// This is far more efficient since it can utilize the Burst compiler.
///
/// This method may be called by graph generators instead of the <see cref="Apply"/> method to update the graph more efficiently.
/// </summary>
public virtual void ApplyJob<T>(T mapper, GraphUpdateData data, JobDependencyTracker dependencyTracker) where T : INodeIndexMapper {
new JobGraphUpdate<T> {
mapper = mapper,
shape = shape != null ? new GraphUpdateShape.BurstShape(shape, Allocator.Persistent) : GraphUpdateShape.BurstShape.Everything,
nodePositions = data.nodePositions,
nodePenalties = data.nodePenalties,
nodeWalkable = data.nodeWalkable,
nodeTags = data.nodeTags,
bounds = bounds,
penaltyDelta = addPenalty,
modifyWalkability = modifyWalkability,
walkabilityValue = setWalkability,
modifyTag = modifyTag,
tagValue = setTag,
}.Schedule(dependencyTracker);
}
public GraphUpdateObject () {
}
/// <summary>Creates a new GUO with the specified bounds</summary>
public GraphUpdateObject (Bounds b) {
bounds = b;
}
}
/// <summary>Graph which has a well defined transformation from graph space to world space</summary>
public interface ITransformedGraph {
GraphTransform transform { get; }
}
/// <summary>Graph which supports the Linecast method</summary>
public interface IRaycastableGraph {
bool Linecast(Vector3 start, Vector3 end);
bool Linecast(Vector3 start, Vector3 end, GraphNode hint);
bool Linecast(Vector3 start, Vector3 end, GraphNode hint, out GraphHitInfo hit);
bool Linecast(Vector3 start, Vector3 end, GraphNode hint, out GraphHitInfo hit, List<GraphNode> trace);
}
/// <summary>
/// Integer Rectangle.
/// Works almost like UnityEngine.Rect but with integer coordinates
/// </summary>
[System.Serializable]
public struct IntRect {
public int xmin, ymin, xmax, ymax;
public IntRect (int xmin, int ymin, int xmax, int ymax) {
this.xmin = xmin;
this.xmax = xmax;
this.ymin = ymin;
this.ymax = ymax;
}
public bool Contains (int x, int y) {
return !(x < xmin || y < ymin || x > xmax || y > ymax);
}
public bool Contains (IntRect other) {
return xmin <= other.xmin && xmax >= other.xmax && ymin <= other.ymin && ymax >= other.ymax;
}
public int Width {
get {
return xmax-xmin+1;
}
}
public int Height {
get {
return ymax-ymin+1;
}
}
/// <summary>
/// Returns if this rectangle is valid.
/// An invalid rect could have e.g xmin > xmax.
/// Rectangles are valid iff they contain at least one point.
/// </summary>
public bool IsValid () {
return xmin <= xmax && ymin <= ymax;
}
public static bool operator == (IntRect a, IntRect b) {
return a.xmin == b.xmin && a.xmax == b.xmax && a.ymin == b.ymin && a.ymax == b.ymax;
}
public static bool operator != (IntRect a, IntRect b) {
return a.xmin != b.xmin || a.xmax != b.xmax || a.ymin != b.ymin || a.ymax != b.ymax;
}
public override bool Equals (System.Object obj) {
if (!(obj is IntRect)) return false;
var rect = (IntRect)obj;
return xmin == rect.xmin && xmax == rect.xmax && ymin == rect.ymin && ymax == rect.ymax;
}
public override int GetHashCode () {
return xmin*131071 ^ xmax*3571 ^ ymin*3109 ^ ymax*7;
}
/// <summary>
/// Returns the intersection rect between the two rects.
/// The intersection rect is the area which is inside both rects.
/// If the rects do not have an intersection, an invalid rect is returned.
/// See: IsValid
/// </summary>
public static IntRect Intersection (IntRect a, IntRect b) {
return new IntRect(
System.Math.Max(a.xmin, b.xmin),
System.Math.Max(a.ymin, b.ymin),
System.Math.Min(a.xmax, b.xmax),
System.Math.Min(a.ymax, b.ymax)
);
}
/// <summary>Returns if the two rectangles intersect each other</summary>
public static bool Intersects (IntRect a, IntRect b) {
return !(a.xmin > b.xmax || a.ymin > b.ymax || a.xmax < b.xmin || a.ymax < b.ymin);
}
/// <summary>
/// Returns a new rect which contains both input rects.
/// This rectangle may contain areas outside both input rects as well in some cases.
/// </summary>
public static IntRect Union (IntRect a, IntRect b) {
return new IntRect(
System.Math.Min(a.xmin, b.xmin),
System.Math.Min(a.ymin, b.ymin),
System.Math.Max(a.xmax, b.xmax),
System.Math.Max(a.ymax, b.ymax)
);
}
/// <summary>Returns a new IntRect which is expanded to contain the point</summary>
public IntRect ExpandToContain (int x, int y) {
return new IntRect(
System.Math.Min(xmin, x),
System.Math.Min(ymin, y),
System.Math.Max(xmax, x),
System.Math.Max(ymax, y)
);
}
/// <summary>Returns a new IntRect which has been moved by an offset</summary>
public IntRect Offset (Int2 offset) {
return new IntRect(xmin + offset.x, ymin + offset.y, xmax + offset.x, ymax + offset.y);
}
/// <summary>Returns a new rect which is expanded by range in all directions.</summary>
/// <param name="range">How far to expand. Negative values are permitted.</param>
public IntRect Expand (int range) {
return new IntRect(xmin-range,
ymin-range,
xmax+range,
ymax+range
);
}
public override string ToString () {
return "[x: "+xmin+"..."+xmax+", y: " + ymin +"..."+ymax+"]";
}
/// <summary>Draws some debug lines representing the rect</summary>
public void DebugDraw (GraphTransform transform, Color color) {
Vector3 p1 = transform.Transform(new Vector3(xmin, 0, ymin));
Vector3 p2 = transform.Transform(new Vector3(xmin, 0, ymax));
Vector3 p3 = transform.Transform(new Vector3(xmax, 0, ymax));
Vector3 p4 = transform.Transform(new Vector3(xmax, 0, ymin));
Debug.DrawLine(p1, p2, color);
Debug.DrawLine(p2, p3, color);
Debug.DrawLine(p3, p4, color);
Debug.DrawLine(p4, p1, color);
}
}
/// <summary>
/// Holds a bitmask of graphs.
/// This bitmask can hold up to 32 graphs.
///
/// The bitmask can be converted to and from integers implicitly.
///
/// <code>
/// GraphMask mask1 = GraphMask.FromGraphName("My Grid Graph");
/// GraphMask mask2 = GraphMask.FromGraphName("My Other Grid Graph");
///
/// NNConstraint nn = NNConstraint.Default;
///
/// nn.graphMask = mask1 | mask2;
///
/// // Find the node closest to somePoint which is either in 'My Grid Graph' OR in 'My Other Grid Graph'
/// var info = AstarPath.active.GetNearest(somePoint, nn);
/// </code>
///
/// See: bitmasks (view in online documentation for working links)
/// </summary>
[System.Serializable]
public struct GraphMask {
/// <summary>Bitmask representing the mask</summary>
public int value;
/// <summary>A mask containing every graph</summary>
public static GraphMask everything { get { return new GraphMask(-1); } }
public GraphMask (int value) {
this.value = value;
}
public static implicit operator int(GraphMask mask) {
return mask.value;
}
public static implicit operator GraphMask (int mask) {
return new GraphMask(mask);
}
/// <summary>Combines two masks to form the intersection between them</summary>
public static GraphMask operator & (GraphMask lhs, GraphMask rhs) {
return new GraphMask(lhs.value & rhs.value);
}
/// <summary>Combines two masks to form the union of them</summary>
public static GraphMask operator | (GraphMask lhs, GraphMask rhs) {
return new GraphMask(lhs.value | rhs.value);
}
/// <summary>Inverts the mask</summary>
public static GraphMask operator ~ (GraphMask lhs) {
return new GraphMask(~lhs.value);
}
/// <summary>True if this mask contains the graph with the given graph index</summary>
public bool Contains (int graphIndex) {
return ((value >> graphIndex) & 1) != 0;
}
/// <summary>A bitmask containing the given graph</summary>
public static GraphMask FromGraph (NavGraph graph) {
return 1 << (int)graph.graphIndex;
}
public override string ToString () {
return value.ToString();
}
/// <summary>
/// A bitmask containing the first graph with the given name.
/// <code>
/// GraphMask mask1 = GraphMask.FromGraphName("My Grid Graph");
/// GraphMask mask2 = GraphMask.FromGraphName("My Other Grid Graph");
///
/// NNConstraint nn = NNConstraint.Default;
///
/// nn.graphMask = mask1 | mask2;
///
/// // Find the node closest to somePoint which is either in 'My Grid Graph' OR in 'My Other Grid Graph'
/// var info = AstarPath.active.GetNearest(somePoint, nn);
/// </code>
/// </summary>
public static GraphMask FromGraphName (string graphName) {
var graph = AstarData.active.data.FindGraph(g => g.name == graphName);
if (graph == null) throw new System.ArgumentException("Could not find any graph with the name '" + graphName + "'");
return FromGraph(graph);
}
}
#region Delegates
/* Delegate with on Path object as parameter.
* This is used for callbacks when a path has finished calculation.\n
* Example function:
* \snippet MiscSnippets.cs OnPathDelegate
*/
public delegate void OnPathDelegate(Path p);
public delegate void OnGraphDelegate(NavGraph graph);
public delegate void OnScanDelegate(AstarPath script);
/// <summary>Deprecated:</summary>
public delegate void OnScanStatus(Progress progress);
#endregion
#region Enums
[System.Flags]
public enum GraphUpdateThreading {
/// <summary>
/// Call UpdateArea in the unity thread.
/// This is the default value.
/// Not compatible with SeparateThread.
/// </summary>
UnityThread = 0,
/// <summary>Call UpdateArea in a separate thread. Not compatible with UnityThread.</summary>
SeparateThread = 1 << 0,
/// <summary>Calls UpdateAreaInit in the Unity thread before everything else</summary>
UnityInit = 1 << 1,
/// <summary>
/// Calls UpdateAreaPost in the Unity thread after everything else.
/// This is used together with SeparateThread to apply the result of the multithreaded
/// calculations to the graph without modifying it at the same time as some other script
/// might be using it (e.g calling GetNearest).
/// </summary>
UnityPost = 1 << 2,
/// <summary>Combination of SeparateThread and UnityInit</summary>
SeparateAndUnityInit = SeparateThread | UnityInit
}
/// <summary>How path results are logged by the system</summary>
public enum PathLog {
/// <summary>Does not log anything. This is recommended for release since logging path results has a performance overhead.</summary>
None,
/// <summary>Logs basic info about the paths</summary>
Normal,
/// <summary>Includes additional info</summary>
Heavy,
/// <summary>Same as heavy, but displays the info in-game using GUI</summary>
InGame,
/// <summary>Same as normal, but logs only paths which returned an error</summary>
OnlyErrors
}
/// <summary>
/// How to estimate the cost of moving to the destination during pathfinding.
///
/// The heuristic is the estimated cost from the current node to the target.
/// The different heuristics have roughly the same performance except not using any heuristic at all (<see cref="None)"/>
/// which is usually significantly slower.
///
/// In the image below you can see a comparison of the different heuristic options for an 8-connected grid and
/// for a 4-connected grid.
/// Note that all paths within the green area will all have the same length. The only difference between the heuristics
/// is which of those paths of the same length that will be chosen.
/// Note that while the Diagonal Manhattan and Manhattan options seem to behave very differently on an 8-connected grid
/// they only do it in this case because of very small rounding errors. Usually they behave almost identically on 8-connected grids.
///
/// [Open online documentation to see images]
///
/// Generally for a 4-connected grid graph the Manhattan option should be used as it is the true distance on a 4-connected grid.
/// For an 8-connected grid graph the Diagonal Manhattan option is the mathematically most correct option, however the Euclidean option
/// is often preferred, especially if you are simplifying the path afterwards using modifiers.
///
/// For any graph that is not grid based the Euclidean option is the best one to use.
///
/// See: <a href="https://en.wikipedia.org/wiki/A*_search_algorithm">Wikipedia: A* search_algorithm</a>
/// </summary>
public enum Heuristic {
/// <summary>Manhattan distance. See: https://en.wikipedia.org/wiki/Taxicab_geometry</summary>
Manhattan,
/// <summary>
/// Manhattan distance, but allowing diagonal movement as well.
/// Note: This option is currently hard coded for the XZ plane. It will be equivalent to Manhattan distance if you try to use it in the XY plane (i.e for a 2D game).
/// </summary>
DiagonalManhattan,
/// <summary>Ordinary distance. See: https://en.wikipedia.org/wiki/Euclidean_distance</summary>
Euclidean,
/// <summary>
/// Use no heuristic at all.
/// This reduces the pathfinding algorithm to Dijkstra's algorithm.
/// This is usually significantly slower compared to using a heuristic, which is why the A* algorithm is usually preferred over Dijkstra's algorithm.
/// You may have to use this if you have a very non-standard graph. For example a world with a <a href="https://en.wikipedia.org/wiki/Wraparound_(video_games)">wraparound playfield</a> (think Civilization or Asteroids) and you have custom links
/// with a zero cost from one end of the map to the other end. Usually the A* algorithm wouldn't find the wraparound links because it wouldn't think to look in that direction.
/// See: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
/// </summary>
None
}
/// <summary>How to visualize the graphs in the editor</summary>
public enum GraphDebugMode {
/// <summary>Draw the graphs with a single solid color</summary>
SolidColor,
/// <summary>
/// Use the G score of the last calculated paths to color the graph.
/// The G score is the cost from the start node to the given node.
/// See: https://en.wikipedia.org/wiki/A*_search_algorithm
/// </summary>
G,
/// <summary>
/// Use the H score (heuristic) of the last calculated paths to color the graph.
/// The H score is the estimated cost from the current node to the target.
/// See: https://en.wikipedia.org/wiki/A*_search_algorithm
/// </summary>
H,
/// <summary>
/// Use the F score of the last calculated paths to color the graph.
/// The F score is the G score + the H score, or in other words the estimated cost total cost of the path.
/// See: https://en.wikipedia.org/wiki/A*_search_algorithm
/// </summary>
F,
/// <summary>
/// Use the penalty of each node to color the graph.
/// This does not show penalties added by tags.
/// See: graph-updates (view in online documentation for working links)
/// See: <see cref="Pathfinding.GraphNode.Penalty"/>
/// </summary>
Penalty,
/// <summary>
/// Visualize the connected components of the graph.
/// A node with a given color can reach any other node with the same color.
///
/// See: <see cref="Pathfinding.HierarchicalGraph"/>
/// See: https://en.wikipedia.org/wiki/Connected_component_(graph_theory)
/// </summary>
Areas,
/// <summary>
/// Use the tag of each node to color the graph.
/// See: tags (view in online documentation for working links)
/// See: <see cref="Pathfinding.GraphNode.Tag"/>
/// </summary>
Tags,
/// <summary>
/// Visualize the hierarchical graph structure of the graph.
/// This is mostly for internal use.
/// See: <see cref="Pathfinding.HierarchicalGraph"/>
/// </summary>
HierarchicalNode,
}
/// <summary>Number of threads to use</summary>
public enum ThreadCount {
AutomaticLowLoad = -1,
AutomaticHighLoad = -2,
None = 0,
One = 1,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight
}
/// <summary>Internal state of a path in the pipeline</summary>
public enum PathState {
Created = 0,
PathQueue = 1,
Processing = 2,
ReturnQueue = 3,
Returned = 4
}
/// <summary>State of a path request</summary>
public enum PathCompleteState {
/// <summary>
/// The path has not been calculated yet.
/// See: <see cref="Pathfinding.Path.IsDone()"/>
/// </summary>
NotCalculated = 0,
/// <summary>
/// The path calculation is done, but it failed.
/// See: <see cref="Pathfinding.Path.error"/>
/// </summary>
Error = 1,
/// <summary>The path has been successfully calculated</summary>
Complete = 2,
/// <summary>
/// The path has been calculated, but only a partial path could be found.
/// See: <see cref="Pathfinding.ABPath.calculatePartial"/>
/// </summary>
Partial = 3,
}
/// <summary>What to do when the character is close to the destination</summary>
public enum CloseToDestinationMode {
/// <summary>The character will stop as quickly as possible when within endReachedDistance (field that exist on most movement scripts) units from the destination</summary>
Stop,
/// <summary>The character will continue to the exact position of the destination</summary>
ContinueToExactDestination,
}
/// <summary>Indicates the side of a line that a point lies on</summary>
public enum Side : byte {
/// <summary>The point lies exactly on the line</summary>
Colinear = 0,
/// <summary>The point lies on the left side of the line</summary>
Left = 1,
/// <summary>The point lies on the right side of the line</summary>
Right = 2
}
public enum InspectorGridHexagonNodeSize {
/// <summary>Value is the distance between two opposing sides in the hexagon</summary>
Width,
/// <summary>Value is the distance between two opposing vertices in the hexagon</summary>
Diameter,
/// <summary>Value is the raw node size of the grid</summary>
NodeSize
}
public enum InspectorGridMode {
Grid,
IsometricGrid,
Hexagonal,
Advanced
}
/// <summary>
/// Determines which direction the agent moves in.
/// For 3D games you most likely want the ZAxisIsForward option as that is the convention for 3D games.
/// For 2D games you most likely want the YAxisIsForward option as that is the convention for 2D games.
/// </summary>
public enum OrientationMode {
ZAxisForward,
YAxisForward,
}
#endregion
}
namespace Pathfinding.Util {
/// <summary>Prevents code stripping. See: https://docs.unity3d.com/Manual/ManagedCodeStripping.html</summary>
public class PreserveAttribute : System.Attribute {
}
}
| 38.219691 | 247 | 0.698331 | [
"Apache-2.0"
] | Aspekt1024/LittleDrones | Assets/Standard Assets/AstarPathfindingProject/Core/astarclasses.cs | 46,972 | C# |
using Newtonsoft.Json;
namespace Couchbase.Configuration.Server.Serialization
{
internal sealed class SystemStats
{
[JsonProperty("cpu_utilization_rate")]
public double CpuUtilizationRate { get; set; }
[JsonProperty("swap_total")]
public int SwapTotal { get; set; }
[JsonProperty("swap_used")]
public int SwapUsed { get; set; }
}
}
#region [ License information ]
/* ************************************************************
*
* @author Couchbase <info@couchbase.com>
* @copyright 2014 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ************************************************************/
#endregion | 32.128205 | 78 | 0.60814 | [
"Apache-2.0"
] | 4thOffice/couchbase-net-client | Src/Couchbase/Configuration/Server/Serialization/SystemStats.cs | 1,255 | C# |
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Steeltoe.Discovery.Eureka;
using Steeltoe.Discovery.Eureka.AppInfo;
using Thrifty.MicroServices.Client.Pooling;
using Thrifty.MicroServices.Commons;
using Thrifty.MicroServices.Ribbon;
using Thrifty.MicroServices.Ribbon.Rules;
using Thrifty.Nifty.Client;
using Thrifty.Services;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading.Tasks;
using Thrifty.Codecs;
namespace Thrifty.MicroServices.Client
{
public partial class ThriftyClient : IDisposable
{
private static readonly ModuleBuilder ModuleBuilder;
private static readonly MethodInfo GetMethodFromHandle = typeof(MethodBase).GetMethod("GetMethodFromHandle", new[] { typeof(RuntimeMethodHandle) });
private static readonly MethodInfo CallMethodInfo = typeof(Func<ThriftyClient, MethodInfo, ClientSslConfig, Ribbon.Server, string, string, object[], object>).GetMethod("Invoke");
private static readonly ConstructorInfo DebuggerBrowsableConstructor = typeof(DebuggerBrowsableAttribute).GetConstructor(new[] { typeof(DebuggerBrowsableState) });
static ThriftyClient()
{
var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Thrifty.MicroServices.DynamicAssembly"),
AssemblyBuilderAccess.Run);
ModuleBuilder = assemblyBuilder.DefineDynamicModule("<main>");
}
private readonly ILogger _logger;
private readonly IPing _swiftyPing;
private readonly Lazy<HashedWheelEvictionTimer> _timeoutTimer;
private readonly ThriftyClientOptions _swiftyClientOptions;
private readonly IServerStatusCollector _collector = new DefaultServerStatusCollector();
private readonly ConcurrentDictionary<MethodInfo, Func<object, object[], object>> _methodCache = new ConcurrentDictionary<MethodInfo, Func<object, object[], object>>();
private readonly ConcurrentDictionary<Type, Func<ThriftyClient, Ribbon.Server, string, string, ClientSslConfig, object>> _proxyCreater = new ConcurrentDictionary<Type, Func<ThriftyClient, Ribbon.Server, string, string, ClientSslConfig, object>>();
private readonly Dictionary<LoadBalanceKey, LoadBalancerCommand> _balancerCommands = new Dictionary<LoadBalanceKey, LoadBalancerCommand>();
private static readonly ConcurrentDictionary<LoadBalanceKey, object> Syncs = new ConcurrentDictionary<LoadBalanceKey, object>();
private volatile bool _disposed;
private IClientConnectionPool _channelPools;
private ThriftClientManager _thriftClientManager;
public ThriftyClient(ThriftyClientOptions swiftyClientOptions)
{
_swiftyClientOptions = swiftyClientOptions ?? new ThriftyClientOptions();
var loggerFactory = _swiftyClientOptions.LoggerFactory;
_logger = loggerFactory?.CreateLogger(typeof(ThriftyClient)) ?? NullLogger.Instance;
_thriftClientManager = new ThriftClientManager(new ThriftCodecManager(),
new NiftyClient(swiftyClientOptions.NettyClientConfig ?? new NettyClientConfig(), _swiftyClientOptions.LoggerFactory),
Enumerable.Empty<ThriftClientEventHandler>(), loggerFactory: _swiftyClientOptions.LoggerFactory);
_swiftyPing = new ThriftyPing(_thriftClientManager);
_timeoutTimer = new Lazy<HashedWheelEvictionTimer>(() =>
{
var timer = Utils.Timer;
return new HashedWheelEvictionTimer(timer);
}, true);
_channelPools = swiftyClientOptions.ConnectionPoolEnabled ?
new NiftyClientChannelPool(_thriftClientManager, _timeoutTimer.Value, swiftyClientOptions)
: (IClientConnectionPool)new NoneClientChannelPool(_thriftClientManager, swiftyClientOptions);
if (_swiftyClientOptions.EurekaEnabled)
{
var eureka = _swiftyClientOptions.Eureka;
DiscoveryManager.Instance.Initialize(eureka, loggerFactory);
var interval = eureka.RegistryFetchIntervalSeconds * 1000 / 2;//TODO last的事件处理
_timeoutTimer.Value.Schedule(this.RefreshServers, TimeSpan.FromMilliseconds(interval));
}
}
private void RefreshServers()
{
var all = _balancerCommands.ToArray();
var count = all.Length;
for (var i = 0; i < count; i++)
{
var item = all[i];
var vipAddress = item.Key.VipAddress;
var balancer = item.Value.LoadBalancer;
var servers = DiscoveryManager.Instance.Client
.GetInstancesByVipAddress(vipAddress, _swiftyClientOptions.Secure)
.Select(ins => new DiscoveryEnabledServer(ins, _swiftyClientOptions.Secure,
_swiftyClientOptions.Eureka.AddressUsage) as Ribbon.Server).ToList();
balancer.AddServers(servers);
}
}
private static bool CircuitTrippingException(Exception e)
{
return false;
}
private static bool RetriableException(Exception exception, bool sameServer)
{
if (exception is ThriftyTransportException) return true;
return false;
}
private LoadBalancerCommand GetCommand(LoadBalanceKey key)
{
if (_swiftyClientOptions.Eureka == null)
{
return null;
}
if (_balancerCommands.TryGetValue(key, out LoadBalancerCommand x))
{
return x;
}
lock (Syncs.GetOrAdd(key, k => new object()))
{
if (_balancerCommands.TryGetValue(key, out LoadBalancerCommand command))
{
return command;
}
var version = key.Version;
var vipAddress = key.VipAddress;
var rule = new FilterableRule(new VersionAffinityFilter(version));
var eureka = _swiftyClientOptions.Eureka;
var balancer = LoadBalancerBuilder.NewBuilder()
.WithPing(_swiftyPing)
.WithPingStrategy(_swiftyClientOptions.PingStrategy)
.WithRule(rule)
.Build($"{vipAddress}:{version}", eureka.RegistryFetchIntervalSeconds * 1000 / 2);
var collector = new DefaultServerStatusCollector();
var retryHandler = new DefaultRetryHandler(
_swiftyClientOptions.RetriesSameServer,
_swiftyClientOptions.RetriesNextServer,
_swiftyClientOptions.RetryEnabled,
CircuitTrippingException,
RetriableException);
command = new LoadBalancerCommand(balancer, collector, retryHandler, null);
var servers = DiscoveryManager.Instance.Client
.GetInstancesByVipAddress(vipAddress, _swiftyClientOptions.Secure)
.Where(ins => ins.Status == InstanceStatus.UP)
.Select(ins => new DiscoveryEnabledServer(ins, _swiftyClientOptions.Secure, _swiftyClientOptions.Eureka.AddressUsage) as Ribbon.Server)
.ToList();
balancer.AddServers(servers);
_balancerCommands.Add(key, command);
return command;
}
}
private object GetStub(ThriftyRequest request, ChannelKey key, INiftyClientChannel channel)
{
var method = request.Method;
var service = method.DeclaringType;
var client = _thriftClientManager.CreateClient(channel, service, $"{service.Name }{key}", _swiftyClientOptions.EventHandlers);
request.Stub = client;
request.ChannelKey = key;
return client;
}
[DebuggerHidden]
private static Func<object, object[], object> CreateFunc(MethodInfo method)
{
var p1 = Expression.Parameter(typeof(object));
var p2 = Expression.Parameter(typeof(object[]));
var type = method.DeclaringType;
if (type == null)
{
throw new NotSupportedException("not supported the Type with no DeclaringType");
}
var instance = Expression.Convert(p1, type);
var parameters = method.GetParameters();
Expression[] paramExpressions = new Expression[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
var parameter = parameters[i];
var arrayIndex = Expression.ArrayIndex(p2, Expression.Constant(i));
paramExpressions[i] = Expression.Convert(arrayIndex, parameter.ParameterType);
}
var methodCall = Expression.Call(instance, method, paramExpressions);
Expression<Func<object, object[], object>> result;
if (method.ReturnType != typeof(void))
{
var convert = Expression.Convert(methodCall, typeof(object));
result = Expression.Lambda<Func<object, object[], object>>(convert, p1, p2);
}
else
{
var block = Expression.Block(methodCall, Expression.Constant(null));
result = Expression.Lambda<Func<object, object[], object>>(block, p1, p2);
}
return result.Compile();
}
[DebuggerHidden]
private ThriftyResponse Execute(ThriftyRequest request, Ribbon.Server server, ClientSslConfig sslConfig)
{
var func = _methodCache.GetOrAdd(request.Method, CreateFunc);
_logger.LogDebug(new EventId(0, "ThriftyClient"), $"use {server}");
var discoveryEnabledServer = server as DiscoveryEnabledServer;
var host = discoveryEnabledServer == null ? server.Host : discoveryEnabledServer.InstanceInfo.IpAddr;
var port = discoveryEnabledServer?.Port ?? server.Port;
var address = string.Compare("localhost", host, StringComparison.OrdinalIgnoreCase) == 0
? IPAddress.Loopback
: IPAddress.Parse(host);
var key = new ChannelKey(new IPEndPoint(address, port), sslConfig,
request.ConnectTimeout, request.ReveiveTimeout, request.WriteTimeout, request.ReadTimeout);
using (var channel = new PooledClientChannel(this._channelPools, key))
{
var proxy = GetStub(request, key, channel);
var result = func(proxy, request.Args);
return new ThriftyResponse(result, true);
}
}
[DebuggerHidden]
private ThriftyResponse RibbonCall(ThriftyRequest request, ClientSslConfig sslConfig, Ribbon.Server server, string version, string vipAddress)
{
if (server != null)
{
return Execute(request, server, sslConfig);
}
var command = GetCommand(new LoadBalanceKey(version, vipAddress));
if (command == null)
{
throw new ThriftyException("need config Eureka");
}
return command.Submit(s =>
{
var result = Execute(request, s, sslConfig);
return Task.FromResult(result);
}).GetAwaiter().GetResult();
}
//[DebuggerHidden]
private object Call(MethodInfo method, ClientSslConfig sslConfig, Ribbon.Server server, string version, string vipAddress, object[] args)
{
var request = new ThriftyRequest(_swiftyClientOptions.RetryEnabled,
_swiftyClientOptions.RetriesNextServer, _swiftyClientOptions.RetriesSameServer,
_swiftyClientOptions.ReadTimeoutMilliseconds, _swiftyClientOptions.WriteTimeoutMilliseconds,
_swiftyClientOptions.ReceiveTimeoutMilliseconds,
_swiftyClientOptions.ConnectTimeoutMilliseconds, args, method);
var response = RibbonCall(request, sslConfig, server, version, vipAddress);
return response.Payload;
}
[DebuggerHidden]
private T InnerCreate<T>(string version, string vipAddress, Ribbon.Server server, ClientSslConfig sslConfig) where T : class
{
this.ThrowIfDisposed();
var type = typeof(T);
if (!type.GetTypeInfo().IsInterface)
throw new NotSupportedException($"{type} must be an interface");
var proxy = FakeProxy<T>.Create(this, server, version, vipAddress, sslConfig);
return proxy;
}
[DebuggerHidden]
private object InnerCreate(Type type, string version, string vipAddress, Ribbon.Server server, ClientSslConfig sslConfig)
{
this.ThrowIfDisposed();
if (!type.GetTypeInfo().IsInterface)
throw new ThriftyException($"swifty service must be an interface, but '{type}' was not.");
return _proxyCreater.GetOrAdd(type, t =>
{
var fullType = typeof(FakeProxy<>).MakeGenericType(t);
var method = fullType.GetMethod("Create", new[] { typeof(ThriftyClient), typeof(Ribbon.Server), typeof(string), typeof(string), typeof(ClientSslConfig) });
var p1 = Expression.Parameter(typeof(ThriftyClient));
var p2 = Expression.Parameter(typeof(Ribbon.Server));
var p3 = Expression.Parameter(typeof(string));
var p4 = Expression.Parameter(typeof(string));
var p5 = Expression.Parameter(typeof(ClientSslConfig));
var call = Expression.Call(method, p1, p2, p3, p4, p5);
var lambda = Expression.Lambda<Func<ThriftyClient, Ribbon.Server, string, string, ClientSslConfig, object>>(call, p1, p2, p3, p4, p5).Compile();
return lambda;
})(this, server, version, vipAddress, sslConfig);
}
public T Create<T>(string version, string vipAddress, ClientSslConfig ssl = null) where T : class => InnerCreate<T>(version, vipAddress, null, ssl);
public T Create<T>(string hostAndPort, ClientSslConfig ssl = null) where T : class => InnerCreate<T>(null, null, new Ribbon.Server(hostAndPort), ssl);
public object Create(Type type, string version, string vipAddress, ClientSslConfig sslConfig = null) => InnerCreate(type, version, vipAddress, null, sslConfig);
public object Create(Type type, string hostAndPort, ClientSslConfig sslConfig = null) => InnerCreate(type, null, null, new Ribbon.Server(hostAndPort), sslConfig);
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
}
public void Dispose()
{
if (_disposed)
{
_disposed = true;
if (_timeoutTimer.IsValueCreated)
{
_timeoutTimer.Value.Dispose();
}
_channelPools?.Dispose();
_thriftClientManager?.Dispose();
_channelPools = null;
_thriftClientManager = null;
}
}
}
}
| 45.421512 | 255 | 0.63104 | [
"Apache-2.0"
] | DavidAlphaFox/Thrifty | src/Thrifty.MicroServices/Client/ThriftyClient.cs | 15,637 | C# |
using System;
using System.Buffers;
using System.Net.Http;
using System.Runtime.InteropServices;
using Bedrock.Framework.Infrastructure;
namespace Bedrock.Framework.Protocols
{
public class Http1RequestMessageWriter : IMessageWriter<HttpRequestMessage>
{
private ReadOnlySpan<byte> Http11 => new byte[] { (byte)'H', (byte)'T', (byte)'T', (byte)'P', (byte)'/', (byte)'1', (byte)'.', (byte)'1' };
private ReadOnlySpan<byte> NewLine => new byte[] { (byte)'\r', (byte)'\n' };
private ReadOnlySpan<byte> Space => new byte[] { (byte)' ' };
public void WriteMessage(HttpRequestMessage message, IBufferWriter<byte> output)
{
var writer = new BufferWriter<IBufferWriter<byte>>(output);
writer.WriteAsciiNoValidation(message.Method.Method);
writer.Write(Space);
// REVIEW: This isn't right
writer.WriteAsciiNoValidation(message.RequestUri.ToString());
writer.Write(Space);
writer.Write(Http11);
writer.Write(NewLine);
var colon = (byte)':';
foreach (var header in message.Headers)
{
foreach (var value in header.Value)
{
writer.WriteAsciiNoValidation(header.Key);
writer.Write(MemoryMarshal.CreateReadOnlySpan(ref colon, 1));
writer.Write(Space);
writer.WriteAsciiNoValidation(value);
writer.Write(NewLine);
}
}
if (message.Content != null)
{
foreach (var header in message.Content.Headers)
{
foreach (var value in header.Value)
{
writer.WriteAsciiNoValidation(header.Key);
writer.Write(MemoryMarshal.CreateReadOnlySpan(ref colon, 1));
writer.Write(Space);
writer.WriteAsciiNoValidation(value);
writer.Write(NewLine);
}
}
}
writer.Write(NewLine);
writer.Commit();
}
}
}
| 36.783333 | 147 | 0.534209 | [
"MIT"
] | ChadJessup/BedrockFramework | src/Bedrock.Framework.Experimental/Protocols/Http1RequestMessageWriter.cs | 2,209 | C# |
using MediatR;
using Opdex.Platform.Application.Abstractions.Commands.Addresses;
using Opdex.Platform.Infrastructure.Abstractions.Clients.CirrusFullNodeApi.Queries.Tokens;
using Opdex.Platform.Infrastructure.Abstractions.Data.Commands.Addresses;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Opdex.Platform.Application.Handlers.Addresses.Balances;
public class MakeAddressBalanceCommandHandler : IRequestHandler<MakeAddressBalanceCommand, ulong>
{
private readonly IMediator _mediator;
public MakeAddressBalanceCommandHandler(IMediator mediator)
{
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
}
public async Task<ulong> Handle(MakeAddressBalanceCommand request, CancellationToken cancellationToken)
{
var balance = await _mediator.Send(new CallCirrusGetSrcTokenBalanceQuery(request.Token, request.AddressBalance.Owner, request.BlockHeight));
request.AddressBalance.SetBalance(balance, request.BlockHeight);
return await _mediator.Send(new PersistAddressBalanceCommand(request.AddressBalance));
}
} | 40.178571 | 148 | 0.808889 | [
"MIT"
] | Opdex/opdex-v1-api | src/Opdex.Platform.Application/Handlers/Addresses/Balances/MakeAddressBalanceCommandHandler.cs | 1,125 | C# |
namespace ZendeskApi_v2.Models.Constants
{
public static class TicketFieldTypes
{
public const string Text = "text";
public const string Textarea = "textarea";
public const string Checkbox = "checkbox";
public const string Date = "date";
public const string Integer = "integer";
public const string Decimal = "decimal";
public const string Regexp = "regexp";
public const string Tagger = "tagger";
}
} | 34.714286 | 55 | 0.62963 | [
"Apache-2.0"
] | ClaudineL/ZendeskApi_v2 | src/ZendeskApi_v2/Models/Constants/TicketFieldTypes.cs | 486 | C# |
using Microsoft.AspNetCore.Identity;
namespace ComponentsWebAssembly_CSharp.Server.Models;
public class ApplicationUser : IdentityUser
{
}
| 17.75 | 53 | 0.838028 | [
"MIT"
] | 3ejki/aspnetcore | src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Models/ApplicationUser.cs | 144 | C# |
//========= Copyright 2016-2021, HTC Corporation. All rights reserved. ===========
using UnityEngine;
using HTC.UnityPlugin.Vive;
#if UNITY_2017_2_OR_NEWER
using UnityEngine.XR;
#else
using XRSettings = UnityEngine.VR.VRSettings;
using XRDevice = UnityEngine.VR.VRDevice;
#endif
namespace HTC.UnityPlugin.VRModuleManagement
{
public sealed partial class UnityEngineVRModule : VRModule.ModuleBase
{
public override int moduleOrder { get { return (int)DefaultModuleOrder.UnityNativeVR; } }
public override int moduleIndex { get { return (int)VRModuleSelectEnum.UnityNativeVR; } }
#if !UNITY_2020_1_OR_NEWER
private static KeyCode[] s_keyCodes = new KeyCode[]
{
KeyCode.JoystickButton0,
KeyCode.JoystickButton1,
KeyCode.JoystickButton2,
KeyCode.JoystickButton3,
KeyCode.JoystickButton4,
KeyCode.JoystickButton5,
KeyCode.JoystickButton6,
KeyCode.JoystickButton7,
KeyCode.JoystickButton8,
KeyCode.JoystickButton9,
KeyCode.JoystickButton10,
KeyCode.JoystickButton11,
KeyCode.JoystickButton12,
KeyCode.JoystickButton13,
KeyCode.JoystickButton14,
KeyCode.JoystickButton15,
KeyCode.JoystickButton16,
KeyCode.JoystickButton17,
KeyCode.JoystickButton18,
KeyCode.JoystickButton19,
};
private static string[] s_axisNames = new string[]
{
"HTC_VIU_UnityAxis1",
"HTC_VIU_UnityAxis2",
"HTC_VIU_UnityAxis3",
"HTC_VIU_UnityAxis4",
"HTC_VIU_UnityAxis5",
"HTC_VIU_UnityAxis6",
"HTC_VIU_UnityAxis7",
"HTC_VIU_UnityAxis8",
"HTC_VIU_UnityAxis9",
"HTC_VIU_UnityAxis10",
"HTC_VIU_UnityAxis11",
"HTC_VIU_UnityAxis12",
"HTC_VIU_UnityAxis13",
"HTC_VIU_UnityAxis14",
"HTC_VIU_UnityAxis15",
"HTC_VIU_UnityAxis16",
"HTC_VIU_UnityAxis17",
"HTC_VIU_UnityAxis18",
"HTC_VIU_UnityAxis19",
"HTC_VIU_UnityAxis20",
"HTC_VIU_UnityAxis21",
"HTC_VIU_UnityAxis22",
"HTC_VIU_UnityAxis23",
"HTC_VIU_UnityAxis24",
"HTC_VIU_UnityAxis25",
"HTC_VIU_UnityAxis26",
"HTC_VIU_UnityAxis27",
};
public static bool GetUnityButton(int id)
{
return Input.GetKey(s_keyCodes[id]);
}
public static float GetUnityAxis(int id)
{
return Input.GetAxisRaw(s_axisNames[id - 1]);
}
#if UNITY_EDITOR
public static int GetUnityAxisCount() { return s_axisNames.Length; }
public static string GetUnityAxisNameByIndex(int index) { return s_axisNames[index]; }
public static int GetUnityAxisIdByIndex(int index) { return index + 1; }
#endif
public override bool ShouldActiveModule() { return VIUSettings.activateUnityNativeVRModule && XRSettings.enabled; }
public override void Update()
{
// set physics update rate to vr render rate
if (VRModule.lockPhysicsUpdateRateToRenderFrequency && Time.timeScale > 0.0f)
{
// FIXME: VRDevice.refreshRate returns zero in Unity 5.6.0 or older version
#if UNITY_5_6_OR_NEWER
Time.fixedDeltaTime = 1f / XRDevice.refreshRate;
#else
Time.fixedDeltaTime = 1f / 90f;
#endif
}
}
private static void UpdateLeftControllerInput(IVRModuleDeviceState prevState, IVRModuleDeviceStateRW currState)
{
switch (currState.deviceModel)
{
case VRModuleDeviceModel.ViveCosmosControllerLeft:
case VRModuleDeviceModel.ViveController:
Update_L_Vive(prevState, currState);
break;
case VRModuleDeviceModel.OculusQuestControllerLeft:
case VRModuleDeviceModel.OculusGoController:
case VRModuleDeviceModel.OculusTouchLeft:
Update_L_OculusTouch(prevState, currState);
break;
case VRModuleDeviceModel.KnucklesLeft:
case VRModuleDeviceModel.IndexControllerLeft:
Update_L_Knuckles(prevState, currState);
break;
case VRModuleDeviceModel.WMRControllerLeft:
Update_L_MicrosoftMR(prevState, currState);
break;
}
}
private static void UpdateRightControllerInput(IVRModuleDeviceState prevState, IVRModuleDeviceStateRW currState)
{
switch (currState.deviceModel)
{
case VRModuleDeviceModel.ViveCosmosControllerRight:
case VRModuleDeviceModel.ViveController:
Update_R_Vive(prevState, currState);
break;
case VRModuleDeviceModel.OculusQuestControllerRight:
case VRModuleDeviceModel.OculusGoController:
case VRModuleDeviceModel.OculusTouchRight:
Update_R_OculusTouch(prevState, currState);
break;
case VRModuleDeviceModel.KnucklesRight:
case VRModuleDeviceModel.IndexControllerRight:
Update_R_Knuckles(prevState, currState);
break;
case VRModuleDeviceModel.WMRControllerRight:
Update_R_MicrosoftMR(prevState, currState);
break;
}
}
private static void Update_L_Vive(IVRModuleDeviceState prevState, IVRModuleDeviceStateRW currState)
{
var primaryButtonPress = GetUnityButton(3);
var menuPress = GetUnityButton(2);
var padPress = GetUnityButton(8);
var triggerTouch = GetUnityButton(14);
var padTouch = GetUnityButton(16);
var padX = GetUnityAxis(1);
var padY = GetUnityAxis(2);
var trigger = GetUnityAxis(9);
var grip = GetUnityAxis(11);
currState.SetButtonPress(VRModuleRawButton.A, primaryButtonPress);
currState.SetButtonPress(VRModuleRawButton.ApplicationMenu, menuPress);
currState.SetButtonPress(VRModuleRawButton.Grip, grip >= 1.0f);
currState.SetButtonPress(VRModuleRawButton.Touchpad, padPress);
currState.SetButtonPress(VRModuleRawButton.Trigger, AxisToPress(prevState.GetButtonPress(VRModuleRawButton.Trigger), trigger, 0.55f, 0.45f));
currState.SetButtonTouch(VRModuleRawButton.Touchpad, padTouch);
currState.SetButtonTouch(VRModuleRawButton.Trigger, triggerTouch);
currState.SetAxisValue(VRModuleRawAxis.TouchpadX, padX);
currState.SetAxisValue(VRModuleRawAxis.TouchpadY, -padY);
currState.SetAxisValue(VRModuleRawAxis.Trigger, trigger);
}
private static void Update_R_Vive(IVRModuleDeviceState prevState, IVRModuleDeviceStateRW currState)
{
var primaryButtonPress = GetUnityButton(1);
var menuPress = GetUnityButton(0);
var padPress = GetUnityButton(9);
var triggerTouch = GetUnityButton(15);
var padTouch = GetUnityButton(17);
var padX = GetUnityAxis(4);
var padY = GetUnityAxis(5);
var trigger = GetUnityAxis(10);
var grip = GetUnityAxis(12);
currState.SetButtonPress(VRModuleRawButton.A, primaryButtonPress);
currState.SetButtonPress(VRModuleRawButton.ApplicationMenu, menuPress);
currState.SetButtonPress(VRModuleRawButton.Touchpad, padPress);
currState.SetButtonPress(VRModuleRawButton.Trigger, AxisToPress(prevState.GetButtonPress(VRModuleRawButton.Trigger), trigger, 0.55f, 0.45f));
currState.SetButtonPress(VRModuleRawButton.Grip, grip >= 1.0f);
currState.SetButtonTouch(VRModuleRawButton.Touchpad, padTouch);
currState.SetButtonTouch(VRModuleRawButton.Trigger, triggerTouch);
currState.SetAxisValue(VRModuleRawAxis.TouchpadX, padX);
currState.SetAxisValue(VRModuleRawAxis.TouchpadY, -padY);
currState.SetAxisValue(VRModuleRawAxis.Trigger, trigger);
}
private static void Update_L_OculusTouch(IVRModuleDeviceState prevState, IVRModuleDeviceStateRW currState)
{
var startPress = GetUnityButton(6);
var xPress = GetUnityButton(2);
var yPress = GetUnityButton(3);
var stickPress = GetUnityButton(8);
var gripPress = GetUnityButton(4);
var xTouch = GetUnityButton(12);
var yTouch = GetUnityButton(13);
var triggerTouch = GetUnityButton(14);
var stickTouch = GetUnityButton(16);
var stickX = GetUnityAxis(1);
var stickY = GetUnityAxis(2);
var trigger = GetUnityAxis(9);
var grip = GetUnityAxis(11);
currState.SetButtonPress(VRModuleRawButton.System, startPress);
currState.SetButtonPress(VRModuleRawButton.ApplicationMenu, yPress);
currState.SetButtonPress(VRModuleRawButton.A, xPress);
currState.SetButtonPress(VRModuleRawButton.Touchpad, stickPress);
currState.SetButtonPress(VRModuleRawButton.Trigger, AxisToPress(prevState.GetButtonPress(VRModuleRawButton.Trigger), trigger, 0.55f, 0.45f));
currState.SetButtonPress(VRModuleRawButton.Grip, gripPress);
currState.SetButtonPress(VRModuleRawButton.CapSenseGrip, gripPress);
currState.SetButtonTouch(VRModuleRawButton.ApplicationMenu, yTouch);
currState.SetButtonTouch(VRModuleRawButton.A, xTouch);
currState.SetButtonTouch(VRModuleRawButton.Touchpad, stickTouch);
currState.SetButtonTouch(VRModuleRawButton.Trigger, triggerTouch);
currState.SetButtonTouch(VRModuleRawButton.Grip, grip >= 0.05f);
currState.SetButtonTouch(VRModuleRawButton.CapSenseGrip, grip >= 0.05f);
currState.SetAxisValue(VRModuleRawAxis.TouchpadX, stickX);
currState.SetAxisValue(VRModuleRawAxis.TouchpadY, -stickY);
currState.SetAxisValue(VRModuleRawAxis.Trigger, trigger);
currState.SetAxisValue(VRModuleRawAxis.CapSenseGrip, grip);
}
private static void Update_R_OculusTouch(IVRModuleDeviceState prevState, IVRModuleDeviceStateRW currState)
{
var aPress = GetUnityButton(0);
var bPress = GetUnityButton(1);
var stickPress = GetUnityButton(9);
var gripPress = GetUnityButton(5);
var aTouch = GetUnityButton(10);
var bTouch = GetUnityButton(11);
var triggerTouch = GetUnityButton(15);
var stickTouch = GetUnityButton(17);
var stickX = GetUnityAxis(4);
var stickY = GetUnityAxis(5);
var trigger = GetUnityAxis(10);
var grip = GetUnityAxis(12);
currState.SetButtonPress(VRModuleRawButton.ApplicationMenu, bPress);
currState.SetButtonPress(VRModuleRawButton.A, aPress);
currState.SetButtonPress(VRModuleRawButton.Touchpad, stickPress);
currState.SetButtonPress(VRModuleRawButton.Trigger, AxisToPress(prevState.GetButtonPress(VRModuleRawButton.Trigger), trigger, 0.55f, 0.45f));
currState.SetButtonPress(VRModuleRawButton.Grip, gripPress);
currState.SetButtonPress(VRModuleRawButton.CapSenseGrip, gripPress);
currState.SetButtonTouch(VRModuleRawButton.ApplicationMenu, bTouch);
currState.SetButtonTouch(VRModuleRawButton.A, aTouch);
currState.SetButtonTouch(VRModuleRawButton.Touchpad, stickTouch);
currState.SetButtonTouch(VRModuleRawButton.Trigger, triggerTouch);
currState.SetButtonTouch(VRModuleRawButton.Grip, grip >= 0.05f);
currState.SetButtonTouch(VRModuleRawButton.CapSenseGrip, grip >= 0.05f);
currState.SetAxisValue(VRModuleRawAxis.TouchpadX, stickX);
currState.SetAxisValue(VRModuleRawAxis.TouchpadY, -stickY);
currState.SetAxisValue(VRModuleRawAxis.Trigger, trigger);
currState.SetAxisValue(VRModuleRawAxis.CapSenseGrip, grip);
}
private static void Update_L_Knuckles(IVRModuleDeviceState prevState, IVRModuleDeviceStateRW currState)
{
var innerPress = GetUnityButton(2);
var outerPress = GetUnityButton(3);
var padPress = GetUnityButton(8);
var triggerTouch = GetUnityButton(14);
var padTouch = GetUnityButton(16);
var padX = GetUnityAxis(1);
var padY = GetUnityAxis(2);
var trigger = GetUnityAxis(9);
var grip = GetUnityAxis(11);
var index = GetUnityAxis(20);
var middle = GetUnityAxis(22);
var ring = GetUnityAxis(24);
var pinky = GetUnityAxis(26);
currState.SetButtonPress(VRModuleRawButton.ApplicationMenu, outerPress);
currState.SetButtonPress(VRModuleRawButton.A, innerPress);
currState.SetButtonPress(VRModuleRawButton.Touchpad, padPress);
currState.SetButtonPress(VRModuleRawButton.Trigger, AxisToPress(prevState.GetButtonPress(VRModuleRawButton.Trigger), trigger, 0.55f, 0.45f));
currState.SetButtonPress(VRModuleRawButton.Grip, grip >= 1.0f);
currState.SetButtonTouch(VRModuleRawButton.Touchpad, padTouch);
currState.SetButtonTouch(VRModuleRawButton.Trigger, triggerTouch);
currState.SetAxisValue(VRModuleRawAxis.TouchpadX, padX);
currState.SetAxisValue(VRModuleRawAxis.TouchpadY, -padY);
currState.SetAxisValue(VRModuleRawAxis.Trigger, trigger);
currState.SetAxisValue(VRModuleRawAxis.CapSenseGrip, grip);
currState.SetAxisValue(VRModuleRawAxis.IndexCurl, index);
currState.SetAxisValue(VRModuleRawAxis.MiddleCurl, middle);
currState.SetAxisValue(VRModuleRawAxis.RingCurl, ring);
currState.SetAxisValue(VRModuleRawAxis.PinkyCurl, pinky);
}
private static void Update_R_Knuckles(IVRModuleDeviceState prevState, IVRModuleDeviceStateRW currState)
{
var innerPress = GetUnityButton(0);
var outerPress = GetUnityButton(1);
var padPress = GetUnityButton(9);
var triggerTouch = GetUnityButton(15);
var padTouch = GetUnityButton(17);
var padX = GetUnityAxis(4);
var padY = GetUnityAxis(5);
var trigger = GetUnityAxis(10);
var grip = GetUnityAxis(12);
var index = GetUnityAxis(21);
var middle = GetUnityAxis(23);
var ring = GetUnityAxis(25);
var pinky = GetUnityAxis(27);
currState.SetButtonPress(VRModuleRawButton.ApplicationMenu, outerPress);
currState.SetButtonPress(VRModuleRawButton.A, innerPress);
currState.SetButtonPress(VRModuleRawButton.Touchpad, padPress);
currState.SetButtonPress(VRModuleRawButton.Trigger, AxisToPress(prevState.GetButtonPress(VRModuleRawButton.Trigger), trigger, 0.55f, 0.45f));
currState.SetButtonPress(VRModuleRawButton.Grip, grip >= 1.0f);
currState.SetButtonTouch(VRModuleRawButton.Touchpad, padTouch);
currState.SetButtonTouch(VRModuleRawButton.Trigger, triggerTouch);
currState.SetAxisValue(VRModuleRawAxis.TouchpadX, padX);
currState.SetAxisValue(VRModuleRawAxis.TouchpadY, -padY);
currState.SetAxisValue(VRModuleRawAxis.Trigger, trigger);
currState.SetAxisValue(VRModuleRawAxis.CapSenseGrip, grip);
currState.SetAxisValue(VRModuleRawAxis.IndexCurl, index);
currState.SetAxisValue(VRModuleRawAxis.MiddleCurl, middle);
currState.SetAxisValue(VRModuleRawAxis.RingCurl, ring);
currState.SetAxisValue(VRModuleRawAxis.PinkyCurl, pinky);
}
private static void Update_L_MicrosoftMR(IVRModuleDeviceState prevState, IVRModuleDeviceStateRW currState)
{
var menuPress = GetUnityButton(2);
var padPress = GetUnityButton(8);
var triggerPress = GetUnityButton(14);
var padTouch = GetUnityButton(16);
var stickX = GetUnityAxis(1);
var stickY = GetUnityAxis(2);
var trigger = GetUnityAxis(9);
var grip = GetUnityAxis(11);
var padX = GetUnityAxis(17);
var padY = GetUnityAxis(18);
currState.SetButtonPress(VRModuleRawButton.ApplicationMenu, menuPress);
currState.SetButtonPress(VRModuleRawButton.Touchpad, padPress);
currState.SetButtonPress(VRModuleRawButton.Trigger, triggerPress);
currState.SetButtonPress(VRModuleRawButton.Grip, grip >= 1f);
currState.SetButtonTouch(VRModuleRawButton.Touchpad, padTouch);
currState.SetButtonTouch(VRModuleRawButton.Trigger, AxisToPress(prevState.GetButtonPress(VRModuleRawButton.Trigger), trigger, 0.25f, 0.20f));
currState.SetAxisValue(VRModuleRawAxis.TouchpadX, padX);
currState.SetAxisValue(VRModuleRawAxis.TouchpadY, -padY);
currState.SetAxisValue(VRModuleRawAxis.Trigger, trigger);
currState.SetAxisValue(VRModuleRawAxis.JoystickX, stickX);
currState.SetAxisValue(VRModuleRawAxis.JoystickY, -stickY);
}
private static void Update_R_MicrosoftMR(IVRModuleDeviceState prevState, IVRModuleDeviceStateRW currState)
{
var menuPress = GetUnityButton(0);
var padPress = GetUnityButton(9);
var triggerPress = GetUnityButton(15);
var padTouch = GetUnityButton(17);
var stickX = GetUnityAxis(4);
var stickY = GetUnityAxis(5);
var trigger = GetUnityAxis(10);
var grip = GetUnityAxis(12);
var padX = GetUnityAxis(19);
var padY = GetUnityAxis(20);
currState.SetButtonPress(VRModuleRawButton.ApplicationMenu, menuPress);
currState.SetButtonPress(VRModuleRawButton.Touchpad, padPress);
currState.SetButtonPress(VRModuleRawButton.Trigger, triggerPress);
currState.SetButtonPress(VRModuleRawButton.Grip, grip >= 1f);
currState.SetButtonTouch(VRModuleRawButton.Touchpad, padTouch);
currState.SetButtonTouch(VRModuleRawButton.Trigger, AxisToPress(prevState.GetButtonPress(VRModuleRawButton.Trigger), trigger, 0.25f, 0.20f));
currState.SetAxisValue(VRModuleRawAxis.TouchpadX, padX);
currState.SetAxisValue(VRModuleRawAxis.TouchpadY, -padY);
currState.SetAxisValue(VRModuleRawAxis.Trigger, trigger);
currState.SetAxisValue(VRModuleRawAxis.JoystickX, stickX);
currState.SetAxisValue(VRModuleRawAxis.JoystickY, -stickY);
}
#endif
}
} | 46.460241 | 153 | 0.653908 | [
"MIT"
] | CharlesCai123/Wearable-MultiCamera-System | Assets/HTC.UnityPlugin/VRModule/Modules/UnityEngineVRModule.cs | 19,283 | C# |
// Copyright 2017 Carnegie Mellon University. All Rights Reserved. See LICENSE.md file for terms.
using System;
using System.Threading;
using System.Threading.Tasks;
using Ghosts.Api.Models;
using Ghosts.Api.Services;
using Microsoft.AspNetCore.Mvc;
namespace Ghosts.Api.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
[ResponseCache(Duration = 5)]
public class MachinesController : Controller
{
private readonly IMachineService _service;
public MachinesController(IMachineService service)
{
_service = service;
}
/// <summary>
/// Gets machines matching the provided query value
/// </summary>
/// <param name="q">Query</param>
/// <param name="ct">Cancellation Token</param>
/// <returns>Machine information</returns>
[HttpGet]
public async Task<IActionResult> GetMachines(string q, CancellationToken ct)
{
var list = await _service.GetAsync(q, ct);
if (list == null) return NotFound();
return Ok(list);
}
/// <summary>
/// Gets all machines in the system
/// (warning: this may be a large amount of data based on the size of your range)
/// </summary>
/// <param name="ct">Cancellation Token</param>
/// <returns>All machine records</returns>
[HttpGet]
[Route("list")]
public IActionResult GetList(CancellationToken ct)
{
return Ok(_service.GetList());
}
/// <summary>
/// Gets a specific machine by its Guid
/// </summary>
/// <param name="id">Machine Guid</param>
/// <param name="ct">Cancellation Token</param>
/// <returns>Machine record</returns>
[HttpGet("{id}")]
public async Task<IActionResult> GetMachine([FromRoute] Guid id, CancellationToken ct)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
var machine = await _service.GetByIdAsync(id, ct);
if (machine.Id == Guid.Empty) return NotFound();
return Ok(machine);
}
/// <summary>
/// Updates a machine's information
/// </summary>
/// <param name="machine">The machine record to update</param>
/// <param name="ct">Cancellation Token</param>
/// <returns>The updated machine record</returns>
[HttpPut("{id}")]
public async Task<IActionResult> PutMachine([FromBody] Machine machine, CancellationToken ct)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
if (machine.Id == Guid.Empty) return BadRequest();
await _service.UpdateAsync(machine, ct);
return NoContent();
}
/// <summary>
/// Create a machine on the range
/// (warning: GHOSTS cannot control this machine unless its client later checks in with the same information created here)
/// </summary>
/// <param name="machine">The machine to create</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> PostMachine([FromBody] Machine machine, CancellationToken ct)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
var id = await _service.CreateAsync(machine, ct);
return CreatedAtAction("GetMachine", new {id}, machine);
}
/// <summary>
/// Deletes a machine (warning: If the machine later checks in, the record will be re-created)
/// </summary>
/// <param name="id">The Id of the machine to delete</param>
/// <param name="ct">Cancellation Token</param>
/// <returns>204 No Content</returns>
[HttpDelete("{id}")]
[ResponseCache(Duration = 0)]
public async Task<IActionResult> DeleteMachine([FromRoute] Guid id, CancellationToken ct)
{
if (!ModelState.IsValid || id == Guid.Empty) return BadRequest(ModelState);
await _service.DeleteAsync(id, ct);
return NoContent();
}
/// <summary>
/// Runs a command on a specific machine
/// </summary>
/// <param name="id">The machine to run the command upon</param>
/// <param name="command">The command to run</param>
/// <param name="ct">Cancellation Token</param>
/// <returns>The machine response</returns>
[HttpPost("{id}/command")]
public IActionResult Command([FromRoute] Guid id, string command, CancellationToken ct)
{
if (!ModelState.IsValid || id == Guid.Empty) return BadRequest(ModelState);
try
{
var response = _service.SendCommand(id, command, ct).Result;
return Ok(response);
}
catch (Exception exc)
{
return Json(exc);
}
}
/// <summary>
/// Lists the activity for a given machine
/// </summary>
/// <param name="id">The machine to get activity for</param>
/// <param name="ct">Cancellation Token</param>
/// <returns>The activity history for the requested machine</returns>
[HttpGet("{id}/activity")]
public async Task<IActionResult> Activity([FromRoute] Guid id, CancellationToken ct)
{
if (!ModelState.IsValid || id == Guid.Empty) return BadRequest(ModelState);
try
{
var response = await _service.GetActivity(id, ct);
return Ok(response);
}
catch (Exception exc)
{
return Json(exc);
}
}
}
} | 35.773006 | 131 | 0.573315 | [
"BSD-3-Clause"
] | 1reduviidae/GHOSTS | src/Ghosts.Api/Controllers/MachinesController.cs | 5,833 | C# |
using NUnit.Framework;
using System.Collections.Generic;
using System.Linq;
public class ProviderControllerTests
{
private IProviderController providerController;
[SetUp]
public void SetUp()
{
IEnergyRepository energyRepository = new EnergyRepository();
this.providerController = new ProviderController(energyRepository);
}
[Test]
public void RegisterMethodValidation()
{
this.providerController.Register(new List<string>() { "Pressure", "40", "20" });
this.providerController.Register(new List<string>() { "Solar", "60", "30" });
Assert.That(this.providerController.Entities.Count, Is.EqualTo(2));
}
[Test]
public void ProduceMethodShouldProduceEnergyCorrectly()
{
this.providerController.Register(new List<string> { "Pressure", "40", "100" });
this.providerController.Register(new List<string> { "Solar", "80", "100" });
this.providerController.Produce();
double energyProduced = this.providerController.TotalEnergyProduced;
Assert.AreEqual(300, energyProduced);
}
[Test]
public void ProduceMethodShouldBrokeProviders()
{
this.providerController.Register(new List<string> { "Pressure", "10", "100" });
this.providerController.Register(new List<string> { "Solar", "10", "100" });
this.providerController.Register(new List<string> { "Standart", "10", "100" });
for (int i = 0; i <= 10; i++)
{
this.providerController.Produce();
}
int expectedCount = 1;
int actualCount = this.providerController.Entities.Count;
Assert.AreEqual(expectedCount, actualCount);
}
[Test]
public void ReapirMethodValidation()
{
this.providerController.Register(new List<string>() { "Pressure", "40", "20" });
IEntity provider = this.providerController.Entities.First();
double expectedDurability = provider.Durability;
double reapairValue = 150;
providerController.Repair(reapairValue);
double actualDurability = provider.Durability;
Assert.AreNotEqual(expectedDurability, actualDurability);
}
}
| 30.068493 | 88 | 0.658314 | [
"MIT"
] | NaskoVasilev/CSharp-OOP-Advanced | Retake Exam-7 September 2017/ProviderControllerTests/ProviderControllerTests.cs | 2,197 | C# |
using Workstation.ServiceModel.Ua;
namespace JR.P262605.HMI.UI.TypeLibrary
{
[DataTypeId("ns=4;s=Wafer")]
[BinaryEncodingId("nsu=urn:BeckhoffAutomation:Ua:PLC1;s=<StructuredDataType>:Wafer__DefaultBinary")]
public class Wafer : IEncodable
{
public Wafer()
{
}
public int Status { get; set; }
public int CurrentStation { get; set; }
public int CurrentSlot { get; set; }
public int HomeStation { get; set; }
public int HomeSlot { get; set; }
public int HomeNest { get; set; }
public int ProcessStep { get; set; }
public string CarrierID { get; set; } = string.Empty;
public string ScribeID { get; set; } = string.Empty;
public double Thickness { get; set; }
public int Notch { get; set; }
public int Size { get; set; }
public string BottomOCRCode { get; set; } = string.Empty;
public string TopOCRCode { get; set; } = string.Empty;
public double PowerBefore { get; set; }
public double PowerAfter { get; set; }
public void Decode(IDecoder decoder)
{
Status = decoder.ReadInt32(nameof(Status));
CurrentStation = decoder.ReadInt32(nameof(CurrentStation));
CurrentSlot = decoder.ReadInt32(nameof(CurrentSlot));
HomeStation = decoder.ReadInt32(nameof(HomeStation));
HomeSlot = decoder.ReadInt32(nameof(HomeSlot));
HomeNest = decoder.ReadInt32(nameof(HomeNest));
ProcessStep = decoder.ReadInt32(nameof(ProcessStep));
CarrierID = decoder.ReadString(nameof(CarrierID));
ScribeID = decoder.ReadString(nameof(ScribeID));
Thickness = decoder.ReadDouble(nameof(Thickness));
Notch = decoder.ReadInt32(nameof(Notch));
Size = decoder.ReadInt32(nameof(Size));
BottomOCRCode = decoder.ReadString(nameof(BottomOCRCode));
TopOCRCode = decoder.ReadString(nameof(TopOCRCode));
PowerBefore = decoder.ReadDouble(nameof(PowerBefore));
PowerAfter = decoder.ReadDouble(nameof(PowerAfter));
}
public void Encode(IEncoder encoder)
{
encoder.WriteInt32(nameof(Status), Status);
encoder.WriteInt32(nameof(CurrentStation), CurrentStation);
encoder.WriteInt32(nameof(CurrentSlot), CurrentSlot);
encoder.WriteInt32(nameof(HomeStation), HomeStation);
encoder.WriteInt32(nameof(HomeSlot), HomeSlot);
encoder.WriteInt32(nameof(HomeNest), HomeNest);
encoder.WriteInt32(nameof(ProcessStep), ProcessStep);
encoder.WriteString(nameof(CarrierID), CarrierID);
encoder.WriteString(nameof(ScribeID), ScribeID);
encoder.WriteDouble(nameof(Thickness), Thickness);
encoder.WriteInt32(nameof(Notch), Notch);
encoder.WriteInt32(nameof(Size), Size);
encoder.WriteString(nameof(BottomOCRCode), BottomOCRCode);
encoder.WriteString(nameof(TopOCRCode), TopOCRCode);
encoder.WriteDouble(nameof(PowerBefore), PowerBefore);
encoder.WriteDouble(nameof(PowerAfter), PowerAfter);
}
}
} | 46.185714 | 104 | 0.632849 | [
"MIT"
] | RoddenLab/HMI-Demo | JR.P262605.HMI/UI/TypeLibrary/Wafer.cs | 3,235 | C# |
using System;
using AllureCSharpCommons.AllureModel;
namespace AllureCSharpCommons.AllureModel
{
public partial class parameter
{
public parameter() { }
public parameter(string name, string value, parameterkind kind)
{
nameField = name;
valueField = value;
kindField = kind;
}
}
public partial class description
{
public description(descriptiontype type, string value)
{
typeField = type;
valueField = value;
}
}
public partial class label
{
public label() { }
public label(string name, string value)
{
nameField = name;
valueField = value;
}
}
public partial class attachment
{
public attachment() { }
public attachment(string title, string source, string type, int size)
{
titleField = title;
sourceField = source;
typeField = type;
sizeField = size;
}
}
public partial class step
{
public step() { }
public step(string name, string title, long start, status status)
{
nameField = name;
titleField = title;
startField = start;
statusField = status;
}
}
public partial class failure
{
public failure() { }
public failure(string message)
: this(message, null) { }
public failure(string message, string stacktrace)
{
messageField = message;
stacktraceField = stacktrace;
}
}
}
| 21.151899 | 77 | 0.530221 | [
"Apache-2.0"
] | Orasi/allure-csharp-commons | AllureCSharpCommons/AllureModel/AllureModelExtensions.cs | 1,673 | C# |
using System;
namespace Demo.App.Views
{
public sealed partial class RepositoryDetailsView
{
public RepositoryDetailsView()
{
InitializeComponent();
}
}
}
| 15.769231 | 53 | 0.6 | [
"MIT"
] | derekjwilliams/talks | ndc-sydney-2017/Demo.App/Views/RepositoryDetailsView.xaml.cs | 207 | C# |
namespace Vodamep.ReportBase
{
public interface ICountryPerson : INamedPerson
{
string Country { get; }
}
} | 18.285714 | 50 | 0.648438 | [
"MIT"
] | lizardwine/Vodamep | src/Vodamep/ReportBase/ICountryPerson.cs | 130 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.AI.Translation.Document.Models;
using Azure.Core;
using Azure.Core.Pipeline;
namespace Azure.AI.Translation.Document
{
/// <summary> Tracks the status of a long-running operation for translating documents. </summary>
public class DocumentTranslationOperation : PageableOperation<DocumentStatusResult>
{
// TODO: Respect retry after #19442
private readonly TimeSpan DefaultPollingInterval = TimeSpan.FromSeconds(30);
/// <summary>Provides communication with the Translator Cognitive Service through its REST API.</summary>
private readonly DocumentTranslationRestClient _serviceClient;
/// <summary>Provides tools for exception creation in case of failure.</summary>
private readonly ClientDiagnostics _diagnostics;
/// <summary>
/// The date time when the translation operation was created.
/// </summary>
public virtual DateTimeOffset CreatedOn => _createdOn;
/// <summary>
/// The date time when the translation operation's status was last updated.
/// </summary>
public virtual DateTimeOffset LastModified => _lastModified;
/// <summary>
/// The current status of the translation operation.
/// </summary>
public virtual DocumentTranslationStatus Status => _status;
/// <summary>
/// Total number of expected translated documents.
/// </summary>
public virtual int DocumentsTotal => _documentsTotal;
/// <summary>
/// Number of documents failed to translate.
/// </summary>
public virtual int DocumentsFailed => _documentsFailed;
/// <summary>
/// Number of documents translated successfully.
/// </summary>
public virtual int DocumentsSucceeded => _documentsSucceeded;
/// <summary>
/// Number of documents in progress.
/// </summary>
public virtual int DocumentsInProgress => _documentsInProgress;
/// <summary>
/// Number of documents in queue for translation.
/// </summary>
public virtual int DocumentsNotStarted => _documentsNotStarted;
/// <summary>
/// Number of documents canceled.
/// </summary>
public virtual int DocumentsCanceled => _documentsCanceled;
private int _documentsTotal;
private int _documentsFailed;
private int _documentsSucceeded;
private int _documentsInProgress;
private int _documentsNotStarted;
private int _documentsCanceled;
private DateTimeOffset _createdOn;
private DateTimeOffset _lastModified;
private DocumentTranslationStatus _status;
/// <summary>
/// Gets an ID representing the translation operation that can be used to poll for the status
/// of the long-running operation.
/// </summary>
public override string Id { get; }
/// <summary>
/// Final result of the long-running operation.
/// </summary>
/// <remarks>
/// This property can be accessed only after the operation completes successfully (HasValue is true).
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public override AsyncPageable<DocumentStatusResult> Value => GetValuesAsync();
/// <summary>
/// <c>true</c> if the long-running operation has completed. Otherwise, <c>false</c>.
/// </summary>
private bool _hasCompleted;
/// <summary>
/// <c>true</c> if the long-running operation has a value. Otherwise, <c>false</c>.
/// </summary>
private bool _hasValue;
/// <summary>
/// Returns true if the long-running operation completed.
/// </summary>
public override bool HasCompleted => _hasCompleted;
private RequestFailedException _requestFailedException;
/// <summary>
/// The last HTTP response received from the server. <c>null</c> until the first response is received.
/// </summary>
private Response _response;
/// <summary>
/// The last Retry-After Header value from the last HTTP response received from the server. <c>null</c> until the first response is received.
/// </summary>
private int? _retryAfterHeaderValue;
/// <summary>
/// Provides the results for the first page.
/// </summary>
private Page<DocumentStatusResult> _firstPage;
/// <summary>
/// Returns true if the long-running operation completed successfully and has produced final result (accessible by Value property).
/// </summary>
public override bool HasValue => _hasValue;
/// <summary>
/// Protected constructor to allow mocking.
/// </summary>
protected DocumentTranslationOperation()
{ }
/// <summary>
/// Initializes a new instance of the <see cref="DocumentTranslationOperation"/> class.
/// </summary>
/// <param name="translationId">The translation ID of this operation.</param>
/// <param name="client">The client used to check for completion.</param>
public DocumentTranslationOperation(string translationId, DocumentTranslationClient client)
{
var parsedTranslationId = ClientCommon.ValidateModelId(translationId, nameof(translationId));
Id = parsedTranslationId.ToString();
_serviceClient = client._serviceRestClient;
_diagnostics = client._clientDiagnostics;
}
/// <summary>
/// Initializes a new instance of the <see cref="DocumentTranslationOperation"/> class.
/// </summary>
/// <param name="serviceClient">The client for communicating with the Translator Cognitive Service through its REST API.</param>
/// <param name="diagnostics">The client diagnostics for exception creation in case of failure.</param>
/// <param name="operationLocation">The address of the long-running operation. It can be obtained from the response headers upon starting the operation.</param>
internal DocumentTranslationOperation(DocumentTranslationRestClient serviceClient, ClientDiagnostics diagnostics, string operationLocation)
{
_serviceClient = serviceClient;
_diagnostics = diagnostics;
Id = operationLocation.Split('/').Last();
}
/// <summary>
/// The last HTTP response received from the server.
/// </summary>
/// <remarks>
/// The last response returned from the server during the lifecycle of this instance.
/// An instance of <see cref="DocumentTranslationOperation"/> sends requests to a server in UpdateStatusAsync, UpdateStatus, and other methods.
/// Responses from these requests can be accessed using GetRawResponse.
/// </remarks>
public override Response GetRawResponse() => _response;
/// <summary>
/// Calls the server to get updated status of the long-running operation.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> used for the service call.</param>
/// <returns>The HTTP response received from the server.</returns>
/// <remarks>
/// This operation will update the value returned from GetRawResponse and might update HasCompleted, HasValue, and Value.
/// </remarks>
public override Response UpdateStatus(CancellationToken cancellationToken = default) =>
UpdateStatusAsync(false, cancellationToken).EnsureCompleted();
/// <summary>
/// Calls the server to get updated status of the long-running operation.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> used for the service call.</param>
/// <returns>The HTTP response received from the server.</returns>
/// <remarks>
/// This operation will update the value returned from GetRawResponse and might update HasCompleted, HasValue, and Value.
/// </remarks>
public override async ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default) =>
await UpdateStatusAsync(true, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Periodically calls the server till the long-running operation completes.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> used for the periodical service calls.</param>
/// <returns>The last HTTP response received from the server.</returns>
/// <remarks>
/// This method will periodically call UpdateStatusAsync till HasCompleted is true.
/// An API call is then made to retrieve the status of the documents.
/// </remarks>
public override ValueTask<Response<AsyncPageable<DocumentStatusResult>>> WaitForCompletionAsync(CancellationToken cancellationToken = default) =>
WaitForCompletionAsync(DefaultPollingInterval, cancellationToken);
/// <summary>
/// Periodically calls the server till the long-running operation completes.
/// </summary>
/// <param name="pollingInterval">
/// The interval between status requests to the server.
/// The interval can change based on information returned from the server.
/// For example, the server might communicate to the client that there is not reason to poll for status change sooner than some time.
/// </param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> used for the periodical service calls.</param>
/// <returns>The last HTTP response received from the server.</returns>
/// <remarks>
/// This method will periodically call UpdateStatusAsync till HasCompleted is true.
/// An API call is then made to retrieve the status of the documents.
/// </remarks>
public async override ValueTask<Response<AsyncPageable<DocumentStatusResult>>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default)
{
while (true)
{
await UpdateStatusAsync(cancellationToken).ConfigureAwait(false);
if (!HasCompleted)
{
pollingInterval = _retryAfterHeaderValue.HasValue ? TimeSpan.FromSeconds(_retryAfterHeaderValue.Value) : pollingInterval;
await Task.Delay(pollingInterval, cancellationToken).ConfigureAwait(false);
}
else
{
var response = await _serviceClient.GetDocumentsStatusAsync(new Guid(Id), cancellationToken: cancellationToken).ConfigureAwait(false);
_firstPage = Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
_hasValue = true;
async Task<Page<DocumentStatusResult>> NextPageFunc(string nextLink, int? pageSizeHint)
{
// TODO: diagnostics scope?
try
{
var response = await _serviceClient.GetDocumentsStatusNextPageAsync(nextLink, new Guid(Id), cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception)
{
throw;
}
}
var result = PageableHelpers.CreateAsyncEnumerable(_ => Task.FromResult(_firstPage), NextPageFunc);
return Response.FromValue(result, response);
}
}
}
/// <summary>
/// Calls the server to get updated status of the long-running operation.
/// </summary>
/// <param name="async">When <c>true</c>, the method will be executed asynchronously; otherwise, it will execute synchronously.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> used for the service call.</param>
/// <returns>The HTTP response received from the server.</returns>
private async ValueTask<Response> UpdateStatusAsync(bool async, CancellationToken cancellationToken)
{
if (!_hasCompleted)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(DocumentTranslationOperation)}.{nameof(UpdateStatus)}");
scope.Start();
try
{
var update = async
? await _serviceClient.GetTranslationStatusAsync(new Guid(Id), cancellationToken).ConfigureAwait(false)
: _serviceClient.GetTranslationStatus(new Guid(Id), cancellationToken);
_response = update.GetRawResponse();
_retryAfterHeaderValue = update.Headers.RetryAfter;
_createdOn = update.Value.CreatedOn;
_lastModified = update.Value.LastModified;
_status = update.Value.Status;
_documentsTotal = update.Value.DocumentsTotal;
_documentsFailed = update.Value.DocumentsFailed;
_documentsInProgress = update.Value.DocumentsInProgress;
_documentsSucceeded = update.Value.DocumentsSucceeded;
_documentsNotStarted = update.Value.DocumentsNotStarted;
_documentsCanceled = update.Value.DocumentsCanceled;
if (update.Value.Status == DocumentTranslationStatus.Succeeded
|| update.Value.Status == DocumentTranslationStatus.Canceled
|| update.Value.Status == DocumentTranslationStatus.Failed)
{
_hasCompleted = true;
_hasValue = true;
}
else if (update.Value.Status == DocumentTranslationStatus.ValidationFailed)
{
ResponseError error = update.Value.Error;
_requestFailedException = _diagnostics.CreateRequestFailedException(_response, error.Message, error.Code, CreateAdditionalInformation(error));
_hasCompleted = true;
throw _requestFailedException;
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return GetRawResponse();
}
/// <summary>
/// Get the status of a specific document in the translation operation.
/// </summary>
/// <param name="documentId">ID of the document.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> used for the service call.</param>
public virtual Response<DocumentStatusResult> GetDocumentStatus(string documentId, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(DocumentTranslationOperation)}.{nameof(GetDocumentStatus)}");
scope.Start();
try
{
var parsedDocumentId = ClientCommon.ValidateModelId(documentId, nameof(documentId));
return _serviceClient.GetDocumentStatus(new Guid(Id), parsedDocumentId, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Get the status of a specific document in the translation operation.
/// </summary>
/// <param name="documentId">ID of the document.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> used for the service call.</param>
public virtual async Task<Response<DocumentStatusResult>> GetDocumentStatusAsync(string documentId, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(DocumentTranslationOperation)}.{nameof(GetDocumentStatus)}");
scope.Start();
try
{
var parsedDocumentId = ClientCommon.ValidateModelId(documentId, nameof(documentId));
return await _serviceClient.GetDocumentStatusAsync(new Guid(Id), parsedDocumentId, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Get the status of documents in the translation operation.
/// </summary>
/// <param name="options">Options to use when filtering result.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> used for the service call.</param>
public virtual Pageable<DocumentStatusResult> GetDocumentStatuses(GetDocumentStatusesOptions options = default, CancellationToken cancellationToken = default)
{
Page<DocumentStatusResult> FirstPageFunc(int? pageSizeHint)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(DocumentTranslationOperation)}.{nameof(GetDocumentStatuses)}");
scope.Start();
try
{
var idList = options?.Ids.Count > 0 ? options.Ids.Select(id => ClientCommon.ValidateModelId(id, "Id Filter")) : null;
var statusList = options?.Statuses.Count > 0 ? options.Statuses.Select(status => status.ToString()) : null;
var orderByList = options?.OrderBy.Count > 0 ? options.OrderBy.Select(order => order.ToGenerated()) : null;
var response = _serviceClient.GetDocumentsStatus(
new Guid(Id),
ids: idList,
statuses: statusList,
createdDateTimeUtcStart: options?.CreatedAfter,
createdDateTimeUtcEnd: options?.CreatedBefore,
orderBy: orderByList,
cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<DocumentStatusResult> NextPageFunc(string nextLink, int? pageSizeHint)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(DocumentTranslationOperation)}.{nameof(GetDocumentStatuses)}");
scope.Start();
try
{
var response = _serviceClient.GetDocumentsStatusNextPage(nextLink, new Guid(Id), cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Get the status of documents in the translation operation.
/// </summary>
/// <param name="options">Options to use when filtering result.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> used for the service call.</param>
public virtual AsyncPageable<DocumentStatusResult> GetDocumentStatusesAsync(GetDocumentStatusesOptions options = default, CancellationToken cancellationToken = default)
{
async Task<Page<DocumentStatusResult>> FirstPageFunc(int? pageSizeHint)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(DocumentTranslationOperation)}.{nameof(GetDocumentStatuses)}");
scope.Start();
try
{
var idList = options?.Ids.Count > 0 ? options.Ids.Select(id => ClientCommon.ValidateModelId(id, "Id Filter")) : null;
var statusList = options?.Statuses.Count > 0 ? options.Statuses.Select(status => status.ToString()) : null;
var orderByList = options?.OrderBy.Count > 0 ? options.OrderBy.Select(order => order.ToGenerated()) : null;
var response = await _serviceClient.GetDocumentsStatusAsync(
new Guid(Id),
ids: idList,
statuses: statusList,
createdDateTimeUtcStart: options?.CreatedAfter,
createdDateTimeUtcEnd: options?.CreatedBefore,
orderBy: orderByList,
cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<DocumentStatusResult>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(DocumentTranslationOperation)}.{nameof(GetDocumentStatuses)}");
scope.Start();
try
{
var response = await _serviceClient.GetDocumentsStatusNextPageAsync(nextLink, new Guid(Id), cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Cancel a running translation operation.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> used for the service call.</param>
public virtual void Cancel(CancellationToken cancellationToken)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(DocumentTranslationOperation)}.{nameof(Cancel)}");
scope.Start();
try
{
Response<TranslationStatusResult> response = _serviceClient.CancelTranslation(new Guid(Id), cancellationToken);
_response = response.GetRawResponse();
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Cancel a running translation operation.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> used for the service call.</param>
public virtual async Task CancelAsync(CancellationToken cancellationToken)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(DocumentTranslationOperation)}.{nameof(Cancel)}");
scope.Start();
try
{
Response<TranslationStatusResult> response = await _serviceClient.CancelTranslationAsync(new Guid(Id), cancellationToken).ConfigureAwait(false);
_response = response.GetRawResponse();
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Gets the final result of the long-running operation asynchronously.
/// </summary>
/// <remarks>
/// Operation must complete successfully (HasValue is true) for it to provide values.
/// </remarks>
public override AsyncPageable<DocumentStatusResult> GetValuesAsync(CancellationToken cancellationToken = default)
{
ValidateOperationStatus();
return GetDocumentStatusesAsync(cancellationToken: cancellationToken);
}
/// <summary>
/// Gets the final result of the long-running operation synchronously.
/// </summary>
/// <remarks>
/// Operation must complete successfully (HasValue is true) for it to provide values.
/// </remarks>
public override Pageable<DocumentStatusResult> GetValues(CancellationToken cancellationToken = default)
{
ValidateOperationStatus();
return GetDocumentStatuses(cancellationToken: cancellationToken);
}
private void ValidateOperationStatus()
{
if (!HasCompleted)
throw new InvalidOperationException("The operation has not completed yet.");
if (!HasValue)
throw _requestFailedException;
}
private static IDictionary<string, string> CreateAdditionalInformation(ResponseError error)
{
if (string.IsNullOrEmpty(error.ToString()))
return null;
return new Dictionary<string, string>(1) { { "AdditionalInformation", error.ToString() } };
}
}
}
| 46.902878 | 182 | 0.60668 | [
"MIT"
] | Ochirkhuyag/azure-sdk-for-net | sdk/translation/Azure.AI.Translation.Document/src/DocumentTranslationOperation.cs | 26,080 | C# |
using System;
using Thor.Generator.ProjectSystem;
using Thor.Generator.Templates;
namespace Thor.Generator
{
public class EventSourceGenerator
{
private readonly Project _source;
private readonly Project _target;
private readonly EventSourceResolver _eventSourceResolver;
private readonly EventSourceTemplateEngine _templateEngine;
public EventSourceGenerator(Project source, Project target, Template template)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (target == null)
{
throw new ArgumentNullException(nameof(target));
}
if (template == null)
{
throw new ArgumentNullException(nameof(template));
}
_source = source;
_target = target;
_eventSourceResolver = new EventSourceResolver(source, template);
_templateEngine = new EventSourceTemplateEngine(template);
}
public void Generate()
{
foreach (EventSourceFile eventSourceFile in _eventSourceResolver.FindEventSourceDefinitions())
{
string eventSource = _templateEngine.Generate(eventSourceFile.Model);
_target.UpdateDocument(eventSource, eventSourceFile.Model.FileName, eventSourceFile.Document.Folders);
}
}
}
}
| 31.340426 | 118 | 0.615071 | [
"MIT"
] | ChilliCream/EventSourceGenerator | src/Generator/EventSourceGenerator.cs | 1,475 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by \generate-code.bat.
//
// Changes to this file will be lost when the code is regenerated.
// The build server regenerates the code before each build and a pre-build
// step will regenerate the code on each local build.
//
// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units.
//
// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities.
// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities.
//
// </auto-generated>
//------------------------------------------------------------------------------
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.
using System;
#nullable enable
namespace UnitsNet.NumberExtensions.NumberToTemperature
{
/// <summary>
/// A number to Temperature Extensions
/// </summary>
public static class NumberToTemperatureExtensions
{
/// <inheritdoc cref="Temperature.FromDegreesCelsius(UnitsNet.QuantityValue)" />
public static Temperature DegreesCelsius<T>(this T value) =>
Temperature.FromDegreesCelsius(Convert.ToDecimal(value));
/// <inheritdoc cref="Temperature.FromDegreesDelisle(UnitsNet.QuantityValue)" />
public static Temperature DegreesDelisle<T>(this T value) =>
Temperature.FromDegreesDelisle(Convert.ToDecimal(value));
/// <inheritdoc cref="Temperature.FromDegreesFahrenheit(UnitsNet.QuantityValue)" />
public static Temperature DegreesFahrenheit<T>(this T value) =>
Temperature.FromDegreesFahrenheit(Convert.ToDecimal(value));
/// <inheritdoc cref="Temperature.FromDegreesNewton(UnitsNet.QuantityValue)" />
public static Temperature DegreesNewton<T>(this T value) =>
Temperature.FromDegreesNewton(Convert.ToDecimal(value));
/// <inheritdoc cref="Temperature.FromDegreesRankine(UnitsNet.QuantityValue)" />
public static Temperature DegreesRankine<T>(this T value) =>
Temperature.FromDegreesRankine(Convert.ToDecimal(value));
/// <inheritdoc cref="Temperature.FromDegreesReaumur(UnitsNet.QuantityValue)" />
public static Temperature DegreesReaumur<T>(this T value) =>
Temperature.FromDegreesReaumur(Convert.ToDecimal(value));
/// <inheritdoc cref="Temperature.FromDegreesRoemer(UnitsNet.QuantityValue)" />
public static Temperature DegreesRoemer<T>(this T value) =>
Temperature.FromDegreesRoemer(Convert.ToDecimal(value));
/// <inheritdoc cref="Temperature.FromKelvins(UnitsNet.QuantityValue)" />
public static Temperature Kelvins<T>(this T value) =>
Temperature.FromKelvins(Convert.ToDecimal(value));
/// <inheritdoc cref="Temperature.FromMillidegreesCelsius(UnitsNet.QuantityValue)" />
public static Temperature MillidegreesCelsius<T>(this T value) =>
Temperature.FromMillidegreesCelsius(Convert.ToDecimal(value));
/// <inheritdoc cref="Temperature.FromSolarTemperatures(UnitsNet.QuantityValue)" />
public static Temperature SolarTemperatures<T>(this T value) =>
Temperature.FromSolarTemperatures(Convert.ToDecimal(value));
}
}
| 48.136986 | 125 | 0.68099 | [
"MIT-feh"
] | IjaCZECH/UnitsNet | UnitsNet.NumberExtensions/GeneratedCode/NumberToTemperatureExtensions.g.cs | 3,516 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Project1_5_DataAccess
{
[Table("Reservation", Schema = "Hotel")]
public partial class Reservations
{
[Key]
public int Id { get; set; }
public int CustomerId { get; set; }
public int RoomId { get; set; }
[Column(TypeName = "date")]
public DateTime StartDate { get; set; }
[Column(TypeName = "date")]
public DateTime EndDate { get; set; }
[Column(TypeName = "money")]
public decimal TotalCost { get; set; }
public bool Paid { get; set; }
[ForeignKey("CustomerId")]
[InverseProperty("Reservation")]
public virtual Customers Customer { get; set; }
[ForeignKey("RoomId")]
[InverseProperty("Reservation")]
public virtual Rooms Room { get; set; }
}
}
| 30.774194 | 55 | 0.618449 | [
"MIT"
] | 1811-nov27-net/RP-AT-MN-Project1.5 | Project1-5_MVC_REST/Project1-5_DataAccess/Reservations.cs | 956 | C# |
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(YuukoOfficialSite.Startup))]
namespace YuukoOfficialSite
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapYuuko();
}
}
}
| 17.4375 | 59 | 0.602151 | [
"MIT"
] | CodeComb/YuukoOfficialSite | YuukoOfficialSite/Startup.cs | 281 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using TrulyRandom.Models;
namespace TrulyRandom
{
/// <summary>
/// Provides method for end-user to retrieve random data of varios types
/// </summary>
public class DataSource
{
/// <summary>
/// Number if bits currently available in the buffer
/// </summary>
public int BitsAvailable => source.BytesInBuffer * 8 + buffer.Count;
readonly List<bool> buffer = new();
readonly Module source;
internal DataSource(Module source)
{
this.source = source;
}
/// <summary>
/// Gets a single random bit
/// </summary>
/// <returns>Random bit</returns>
/// <exception cref="OutOfRandomnessException">Thrown if there is not enough data in the buffer</exception>
public bool GetBit()
{
lock (buffer)
{
if (buffer.Any())
{
bool result = buffer.Last();
buffer.RemoveAt(buffer.Count - 1);
return result;
}
byte[] data = source.ReadExactly(1);
if (data.Length == 0)
{
throw new OutOfRandomnessException("Not enough randomness in the buffer");
}
for (int i = 0; i < 7; i++)
{
buffer.Add(data[0].Bit(i));
}
return data[0].Bit(7);
}
}
/// <summary>
/// Gets a single random byte
/// </summary>
/// <returns>Random byte</returns>
/// <exception cref="OutOfRandomnessException">Thrown if there is not enough data in the buffer</exception>
public byte GetByte()
{
byte[] data = source.ReadExactly(1);
if (data.Length != 1)
{
throw new OutOfRandomnessException("Not enough randomness in the buffer");
}
return data[0];
}
/// <summary>
/// Gets an array of random bytes
/// </summary>
/// <param name="count">Number of bytes</param>
/// <returns>Random bytes</returns>
/// <exception cref="OutOfRandomnessException">Thrown if there is not enough data in the buffer</exception>
public byte[] GetBytes(int count)
{
byte[] data = source.ReadExactly(count);
if (data.Length != count)
{
throw new OutOfRandomnessException("Not enough randomness in the buffer");
}
return data;
}
/// <summary>
/// Gets a random ULong
/// </summary>
/// <returns>Random ULong</returns>
/// <exception cref="OutOfRandomnessException">Thrown if there is not enough data in the buffer</exception>
public ulong GetULong()
{
return GetULong(ulong.MaxValue);
}
/// <summary>
/// Gets a random ULong in a range between 0 and <paramref name="maxValue"/>
/// </summary>
/// <param name="maxValue">Upper bound (not inclusive)</param>
/// <returns>Random ULong</returns>
/// <exception cref="OutOfRandomnessException">Thrown if there is not enough data in the buffer</exception>
public ulong GetULong(ulong maxValue)
{
//Using FDR (Fast Dice Roller) algorithm
lock (buffer)
{
ulong v = 1, c = 0;
while (true)
{
v <<= 1;
c <<= 1;
if (GetBit())
{
c++;
}
if (v >= maxValue)
{
if (c < maxValue)
{
return c;
}
v -= maxValue;
c -= maxValue;
}
}
}
}
/// <summary>
/// Gets a random ULong in a range between <paramref name="minValue"/> and <paramref name="maxValue"/>
/// </summary>
/// <param name="minValue">Lower bound (inclusive)</param>
/// <param name="maxValue">Upper bound (not inclusive)</param>
/// <returns>Random ULong</returns>
/// <exception cref="OutOfRandomnessException">Thrown if there is not enough data in the buffer</exception>
/// <exception cref="ArgumentException">Thrown if bounds are specified incorrectly</exception>
public ulong GetULong(ulong minValue, ulong maxValue)
{
if (minValue >= maxValue)
{
throw new ArgumentException("Min value must be less than max value");
}
return GetULong(maxValue - minValue) + minValue;
}
/// <summary>
/// Gets a random long
/// </summary>
/// <returns>Random long</returns>
/// <exception cref="OutOfRandomnessException">Thrown if there is not enough data in the buffer</exception>
public long GetLong()
{
return (long)GetULong(long.MaxValue);
}
/// <summary>
/// Gets a random long in a range between 0 and <paramref name="maxValue"/>
/// </summary>
/// <param name="maxValue">Upper bound (not inclusive)</param>
/// <returns>Random long</returns>
/// <exception cref="OutOfRandomnessException">Thrown if there is not enough data in the buffer</exception>
/// <exception cref="ArgumentException">Thrown if bound is specified incorrectly</exception>
public long GetLong(long maxValue)
{
if (maxValue <= 0)
{
throw new ArgumentException("Max value must be > 0");
}
return (long)GetULong((ulong)maxValue);
}
/// <summary>
/// Gets a random long in a range between <paramref name="minValue"/> and <paramref name="maxValue"/>
/// </summary>
/// <param name="minValue">Lower bound (inclusive)</param>
/// <param name="maxValue">Upper bound (not inclusive)</param>
/// <returns>Random long</returns>
/// <exception cref="OutOfRandomnessException">Thrown if there is not enough data in the buffer</exception>
/// <exception cref="ArgumentException">Thrown if bounds are specified incorrectly</exception>
public long GetLong(long minValue, long maxValue)
{
if (minValue >= maxValue)
{
throw new ArgumentException("Min value must be less than max value");
}
return (long)GetULong((ulong)(maxValue - minValue)) + minValue;
}
/// <summary>
/// Gets a random UInt
/// </summary>
/// <returns>Random UInt</returns>
/// <exception cref="OutOfRandomnessException">Thrown if there is not enough data in the buffer</exception>
public uint GetUInt()
{
return GetUInt(uint.MaxValue);
}
/// <summary>
/// Gets a random UInt in a range between 0 and <paramref name="maxValue"/>
/// </summary>
/// <param name="maxValue">Upper bound (not inclusive)</param>
/// <returns>Random UInt</returns>
/// <exception cref="OutOfRandomnessException">Thrown if there is not enough data in the buffer</exception>
public uint GetUInt(uint maxValue)
{
lock (buffer)
{
uint v = 1, c = 0;
while (true)
{
v <<= 1;
c <<= 1;
if (GetBit())
{
c++;
}
if (v >= maxValue)
{
if (c < maxValue)
{
return c;
}
v -= maxValue;
c -= maxValue;
}
}
}
}
/// <summary>
/// Gets a random UInt in a range between <paramref name="minValue"/> and <paramref name="maxValue"/>
/// </summary>
/// <param name="minValue">Lower bound (inclusive)</param>
/// <param name="maxValue">Upper bound (not inclusive)</param>
/// <returns>Random UInt</returns>
/// <exception cref="OutOfRandomnessException">Thrown if there is not enough data in the buffer</exception>
/// <exception cref="ArgumentException">Thrown if bounds are specified incorrectly</exception>
public uint GetUInt(uint minValue, uint maxValue)
{
if (minValue >= maxValue)
{
throw new ArgumentException("Min value must be less than max value");
}
return GetUInt(maxValue - minValue) + minValue;
}
/// <summary>
/// Gets a random int
/// </summary>
/// <returns>Random int</returns>
/// <exception cref="OutOfRandomnessException">Thrown if there is not enough data in the buffer</exception>
public int GetInt()
{
return (int)GetUInt(int.MaxValue);
}
/// <summary>
/// Gets a random int in a range between 0 and <paramref name="maxValue"/>
/// </summary>
/// <param name="maxValue">Upper bound (not inclusive)</param>
/// <returns>Random int</returns>
/// <exception cref="OutOfRandomnessException">Thrown if there is not enough data in the buffer</exception>
/// <exception cref="ArgumentException">Thrown if bound is specified incorrectly</exception>
public int GetInt(int maxValue)
{
if (maxValue <= 0)
{
throw new ArgumentException("Max value must be > 0");
}
return (int)GetUInt((uint)maxValue);
}
/// <summary>
/// Gets a random int in a range between <paramref name="minValue"/> and <paramref name="maxValue"/>
/// </summary>
/// <param name="minValue">Lower bound (inclusive)</param>
/// <param name="maxValue">Upper bound (not inclusive)</param>
/// <returns>Random int</returns>
/// <exception cref="OutOfRandomnessException">Thrown if there is not enough data in the buffer</exception>
/// <exception cref="ArgumentException">Thrown if bounds are specified incorrectly</exception>
public int GetInt(int minValue, int maxValue)
{
if (minValue >= maxValue)
{
throw new ArgumentException("Min value must be less than max value");
}
return (int)GetUInt((uint)(maxValue - minValue)) + minValue;
}
/// <summary>
/// Gets a random double in a range between 0 and 1
/// </summary>
/// <param name="including0">Specifies whether 0 should be incuded</param>
/// <param name="including1">Specifies whether 1 should be incuded</param>
/// <returns>Random double</returns>
/// <exception cref="OutOfRandomnessException">Thrown if there is not enough data in the buffer</exception>
public double GetDouble(bool including0 = true, bool including1 = false)
{
return GetInt(including0 ? 0 : 1, including1 ? int.MaxValue : int.MaxValue - 1) * (1.0 / int.MaxValue);
}
/// <summary>
/// Gets a random double in a range between 0 and 1 (inclusive)
/// </summary>
/// <param name="minValue">Lower bound</param>
/// <param name="maxValue">Upper bound</param>
/// <param name="includingMin">Specifies whether minValue should be incuded</param>
/// <param name="includingMax">Specifies whether maxValue should be incuded</param>
/// <returns>Random double</returns>
/// <exception cref="OutOfRandomnessException">Thrown if there is not enough data in the buffer</exception>
public double GetDouble(double minValue, double maxValue, bool includingMin = true, bool includingMax = false)
{
return GetDouble(includingMin, includingMax) * (maxValue - minValue) + minValue;
}
/// <summary>
/// Gets a random double that follows Gaussian (normal) distribution
/// </summary>
/// <param name="mean">Mean value</param>
/// <param name="stdDev">Standard deviation</param>
/// <returns></returns>
public double GetNormal(double mean, double stdDev)
{
double u1 = 1.0 - GetDouble(true, false);
double u2 = 1.0 - GetDouble(true, false);
double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2);
return mean + stdDev * randStdNormal;
}
/// <summary>
/// Randomly shuffles specified array using Fisher–Yates algorithm
/// </summary>
/// <typeparam name="T">Type of an array element</typeparam>
/// <param name="array">Array to be shuffled</param>
public void Shuffle<T>(T[] array)
{
uint n = (uint)array.Length;
for (uint i = 0; i < (n - 1); i++)
{
uint r = i + GetUInt(n - i);
(array[i], array[r]) = (array[r], array[i]);
}
}
}
}
| 38.876791 | 118 | 0.527344 | [
"MIT"
] | AndrewRomashkin/TrulyRandom | TrulyRandom/Other/DataSource.cs | 13,572 | C# |
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Treehopper.Desktop.LibUsb
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int HotplugCallbackFunction(IntPtr context, IntPtr device, HotplugEvent e, IntPtr userData);
internal static class NativeMethods
{
internal const CallingConvention CC = 0;
internal const string LIBUSB_DLL = "libusb-1.0.so.0";
internal const int HotplugMatchAny = -1;
// libusb_init
[DllImport(LIBUSB_DLL, CallingConvention = CC, SetLastError = false, EntryPoint = "libusb_init")]
internal static extern int Init(out IntPtr pContext);
// libusb_exit
[DllImport(LIBUSB_DLL, CallingConvention = CC, SetLastError = false, EntryPoint = "libusb_exit")]
internal static extern void Exit(IntPtr pContext);
// libusb_hotplug_register_callback
[DllImport(LIBUSB_DLL, CallingConvention = CC, SetLastError = false,
EntryPoint = "libusb_hotplug_register_callback")]
internal static extern int HotplugRegisterCallback([In] IntPtr context, HotplugEvent events, int flags,
int vendor_id, int product_id, int dev_class, HotplugCallbackFunction cb_fn, IntPtr user_data,
IntPtr HandleRef);
// libusb_handle_events
[DllImport(LIBUSB_DLL, CallingConvention = CC, SetLastError = false, EntryPoint = "libusb_handle_events_completed")]
internal static extern int HandleEvents(IntPtr pContext, IntPtr completed);
// libusb_get_device_list
[DllImport(LIBUSB_DLL, CallingConvention = CC, SetLastError = false, EntryPoint = "libusb_get_device_list")]
public static extern int GetDeviceList([In] IntPtr context, [Out] out IntPtr device);
// libusb_free_device_list
[DllImport(LIBUSB_DLL, CallingConvention = CC, SetLastError = false, EntryPoint = "libusb_free_device_list")]
internal static extern void FreeDeviceList(IntPtr pHandleList, int unrefDevices);
// libusb_get_device_descriptor
[DllImport(LIBUSB_DLL, CallingConvention = CC, SetLastError = false,
EntryPoint = "libusb_get_device_descriptor")]
public static extern int GetDeviceDescriptor([In] IntPtr deviceProfileHandle,
[Out] LibUsbDeviceDescriptor deviceDescriptor);
// libusb_get_string_descriptor_ascii
[DllImport(LIBUSB_DLL, CallingConvention = CC, SetLastError = false,
EntryPoint = "libusb_get_string_descriptor_ascii")]
public static extern int GetStringDescriptor([In] LibUsbDeviceHandle deviceProfileHandle, [In] byte desc_index,
StringBuilder sb, int length);
// libusb_open
[DllImport(LIBUSB_DLL, CallingConvention = CC, SetLastError = false, EntryPoint = "libusb_open")]
internal static extern int Open([In] IntPtr deviceProfileHandle, ref IntPtr deviceHandle);
// libusb_claim_interface
[DllImport(LIBUSB_DLL, CallingConvention = CC, SetLastError = false, EntryPoint = "libusb_claim_interface")]
public static extern int ClaimInterface([In] LibUsbDeviceHandle deviceHandle, int interfaceNumber);
// libusb_close
[DllImport(LIBUSB_DLL, CallingConvention = CC, SetLastError = false, EntryPoint = "libusb_close")]
internal static extern void Close([In] IntPtr deviceHandle);
// libusb_bulk_transfer
[DllImport(LIBUSB_DLL, CallingConvention = CC, SetLastError = false, EntryPoint = "libusb_bulk_transfer")]
internal static extern LibUsbError BulkTransfer([In] LibUsbDeviceHandle deviceHandle, byte endpoint,
byte[] Data, int length, out int actualLength, int timeout);
}
} | 51.191781 | 124 | 0.719026 | [
"MIT"
] | ehailey1/treehopper-sdk | NET/API/Treehopper.Desktop/LibUsb/NativeMethods.cs | 3,739 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
namespace SampleTest {
// isを使ったパターンマッチングを試す
// https://docs.microsoft.com/ja-jp/dotnet/csharp/language-reference/keywords/is
public class IsPatternMatchingTest {
[Fact]
public void Is_nullのチェックができる() {
// Arrange
// Act
// Assert
int? value = null;
if (value is null) {
Assert.Null(value);
} else {
AssertHelper.Fail();
}
}
[Fact]
public void Is_非nullableに変換できる() {
// Arrange
// Act
// Assert
int? value = 0;
if (value is null) {
AssertHelper.Fail();
} else if (value is int value2) {
// int? value => int value2
Assert.Equal(0, value2);
}
}
// C# 9.0
// https://docs.microsoft.com/ja-jp/dotnet/csharp/whats-new/csharp-9#pattern-matching-enhancements
[Fact]
public void Is_notnullのチェックができる() {
// Arrange
// Act
// Assert
int? value = null;
if (value is not null) {
AssertHelper.Fail();
return;
}
Assert.Null(value);
}
[Fact]
public void Is_andとlessthanorequalとgreaterthanorequalを使ってみる() {
// Arrange
// Act
// Assert
Assert.All(
"0123456789".ToCharArray(),
digit => Assert.True(digit is >= '0' and <= '9'));
}
// https://docs.microsoft.com/ja-jp/dotnet/csharp/language-reference/operators/patterns#parenthesized-pattern
[Theory]
[InlineData(0, true)]
[InlineData(1, false)]
[InlineData(2, false)]
[InlineData(3, true)]
public void Is_notと括弧を使ってみる(int value, bool expected) {
// Arrange
// Act
// valueは1、2以外
var actual = value is not (1 or 2);
// Assert
Assert.Equal(expected, actual);
}
// https://docs.microsoft.com/ja-jp/dotnet/csharp/language-reference/operators/patterns#var-pattern
[Theory]
[InlineData(0, false)]
[InlineData(1, true)]
[InlineData(3, true)]
[InlineData(4, false)]
public void Is_varと使ってみる(int value, bool expected) {
// Arrange
static bool isInRange(Func<IEnumerable<int>> provider, int value)
// providerは重たい処理をイメージして、
// varでローカル変数に一度代入する
=> provider() is var values
&& value >= values.Min()
&& value <= values.Max();
// Act
var actual = isInRange(() => Enumerable.Range(1, 3), value);
// Assert
Assert.Equal(expected, actual);
}
}
}
| 22.37037 | 112 | 0.612583 | [
"MIT"
] | ichiroku11/dotnet-sample | src/SampleTest/IsPatternMatchingTest.cs | 2,608 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.