content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using Xunit;
namespace BlazorBlog.Ghost.Tests
{
public class GhostOptionsTests
{
[Theory]
[InlineData("api_url", "content_api_key", false)]
[InlineData("api_url", null, true)]
[InlineData(null, "content_api_key", true)]
public void ThrowsIfInvalid_Works(string? apiUrl, string? contentApiKey, bool isExceptionExpected)
{
var ghostOptions = new GhostOptions
{
ApiUrl = apiUrl,
ContentApiKey = contentApiKey
};
if (isExceptionExpected)
{
Assert.Throws<InvalidOperationException>(() =>
ghostOptions.ThrowsIfInvalid());
}
}
}
}
| 26.714286 | 106 | 0.557487 | [
"MIT"
] | asumo-dev/blazorblog | tests/BlazorBlog.Ghost.Tests/GhostOptionsTests.cs | 748 | C# |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
namespace System.Management.Automation
{
/// <summary>
/// Provides information about a configuration that is stored in session state.
/// </summary>
public class ConfigurationInfo : FunctionInfo
{
#region ctor
/// <summary>
/// Creates an instance of the ConfigurationInfo class with the specified name and ScriptBlock
/// </summary>
///
/// <param name="name">
/// The name of the configuration.
/// </param>
///
/// <param name="configuration">
/// The ScriptBlock for the configuration
/// </param>
///
/// <param name="context">
/// The ExecutionContext for the configuration.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="configuration"/> is null.
/// </exception>
///
internal ConfigurationInfo(string name, ScriptBlock configuration, ExecutionContext context) : this(name, configuration, context, null)
{
}
/// <summary>
/// Creates an instance of the ConfigurationInfo class with the specified name and ScriptBlock
/// </summary>
///
/// <param name="name">
/// The name of the configuration.
/// </param>
///
/// <param name="configuration">
/// The ScriptBlock for the configuration
/// </param>
///
/// <param name="context">
/// The ExecutionContext for the configuration.
/// </param>
///
/// <param name="helpFile">
/// The help file for the configuration.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="configuration"/> is null.
/// </exception>
///
internal ConfigurationInfo(string name, ScriptBlock configuration, ExecutionContext context, string helpFile)
: base(name, configuration, context, helpFile)
{
SetCommandType(CommandTypes.Configuration);
}
/// <summary>
/// Creates an instance of the ConfigurationInfo class with the specified name and ScriptBlock
/// </summary>
///
/// <param name="name">
/// The name of the configuration.
/// </param>
///
/// <param name="configuration">
/// The ScriptBlock for the configuration
/// </param>
///
/// <param name="options">
/// The options to set on the function. Note, Constant can only be set at creation time.
/// </param>
///
/// <param name="context">
/// The execution context for the configuration.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="configuration"/> is null.
/// </exception>
///
internal ConfigurationInfo(string name, ScriptBlock configuration, ScopedItemOptions options, ExecutionContext context) : this(name, configuration, options, context, null)
{
}
/// <summary>
/// Creates an instance of the ConfigurationInfo class with the specified name and ScriptBlock
/// </summary>
///
/// <param name="name">
/// The name of the configuration.
/// </param>
///
/// <param name="configuration">
/// The ScriptBlock for the configuration
/// </param>
///
/// <param name="options">
/// The options to set on the function. Note, Constant can only be set at creation time.
/// </param>
///
/// <param name="context">
/// The execution context for the configuration.
/// </param>
///
/// <param name="helpFile">
/// The help file for the configuration.
/// </param>
///
/// <param name="isMetaConfig">The configuration is a meta configuration</param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="configuration"/> is null.
/// </exception>
///
internal ConfigurationInfo(string name, ScriptBlock configuration, ScopedItemOptions options, ExecutionContext context, string helpFile, bool isMetaConfig)
: base(name, configuration, options, context, helpFile)
{
SetCommandType(CommandTypes.Configuration);
IsMetaConfiguration = isMetaConfig;
}
/// <summary>
/// Creates an instance of the ConfigurationInfo class with the specified name and ScriptBlock
/// </summary>
///
/// <param name="name">
/// The name of the configuration.
/// </param>
///
/// <param name="configuration">
/// The ScriptBlock for the configuration
/// </param>
///
/// <param name="options">
/// The options to set on the function. Note, Constant can only be set at creation time.
/// </param>
///
/// <param name="context">
/// The execution context for the configuration.
/// </param>
///
/// <param name="helpFile">
/// The help file for the configuration.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="configuration"/> is null.
/// </exception>
///
internal ConfigurationInfo(string name, ScriptBlock configuration, ScopedItemOptions options, ExecutionContext context, string helpFile)
: this(name, configuration, options, context, helpFile, false)
{
}
/// <summary>
/// This is a copy constructor, used primarily for get-command.
/// </summary>
internal ConfigurationInfo(ConfigurationInfo other)
: base(other)
{
}
/// <summary>
/// This is a copy constructor, used primarily for get-command.
/// </summary>
internal ConfigurationInfo(string name, ConfigurationInfo other)
: base(name, other)
{
}
/// <summary>
/// Create a copy of commandInfo for GetCommandCommand so that we can generate parameter
/// sets based on an argument list (so we can get the dynamic parameters.)
/// </summary>
internal override CommandInfo CreateGetCommandCopy(object[] arguments)
{
var copy = new ConfigurationInfo(this) { IsGetCommandCopy = true, Arguments = arguments };
return copy;
}
#endregion ctor
internal override HelpCategory HelpCategory
{
get { return HelpCategory.Configuration; }
}
/// <summary>
/// Indication whether the configuration is a meta-configuration
/// </summary>
public bool IsMetaConfiguration
{ get; internal set; }
}
}
| 35.11165 | 179 | 0.541269 | [
"Apache-2.0",
"MIT"
] | HydAu/PowerShell | src/System.Management.Automation/engine/ConfigurationInfo.cs | 7,233 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GamesPortal.Service.Artifactory;
using GamesPortal.Service.Entities;
using NSubstitute;
namespace GamesPortal.Service.Helpers
{
internal static class ArtifactoryGatewayHelper
{
public static ArtifactoryRepositoryDescriptor MockGameRepository(this IArtifactoryGateway artifactoryGateway, Entities.GameTechnology gameTechnology, bool isExternal = false)
{
var descriptor = CreateArtifactoryGamesRepositoryDescriptor(gameTechnology, isExternal);
artifactoryGateway.GetRepositoryDescriptor(Arg.Any<GameTechnology>(),
Arg.Any<PlatformType>(),
Arg.Any<bool>())
.Returns(descriptor);
return descriptor;
}
private static ArtifactoryRepositoryDescriptor CreateArtifactoryGamesRepositoryDescriptor(Entities.GameTechnology gameTechnology, bool isExternal = false)
{
var gamesRepository = Substitute.For<IArtifactoryGamesRepository>();
gamesRepository.RepositoryName.Returns(string.Format("{0}-{1}-Repository", gamesRepository, isExternal ? "external" : "internal"));
return new ArtifactoryRepositoryDescriptor(gameTechnology, isExternal, DEFAULT_PLATFORM_TYPE, gamesRepository);
}
public static ArtifactoryRepositoryDescriptor CreateRepositoryDescriptor(string repoName = "repoName", GameTechnology technolgoy = GameTechnology.Html5)
{
var repoStub = Substitute.For<IArtifactoryGamesRepository>();
repoStub.RepositoryName.Returns(repoName);
repoStub.GetRootFolderRelativeUrl().Returns(repoName);
return new ArtifactoryRepositoryDescriptor(technolgoy, true, ArtifactoryGatewayHelper.DEFAULT_PLATFORM_TYPE, repoStub);
}
public static IArtifactorySyncronizationLogger CreateMockLogger()
{
return Substitute.For<IArtifactorySyncronizationLogger>();
}
public static readonly PlatformType DEFAULT_PLATFORM_TYPE = PlatformType.Both;
}
}
| 44.333333 | 182 | 0.693056 | [
"MIT"
] | jackobo/jackobs-code | Portal/Server/Head/src/GamesPortal.Service.UnitTests/Helpers/ArtifactoryGatewayHelper.cs | 2,263 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <auto-generated>
// Generated using OBeautifulCode.CodeGen.ModelObject (1.0.0.0)
// </auto-generated>
// --------------------------------------------------------------------------------------------------------------------
namespace OBeautifulCode.CodeGen.ModelObject.Test
{
using global::System;
using global::System.CodeDom.Compiler;
using global::System.Collections.Concurrent;
using global::System.Collections.Generic;
using global::System.Collections.ObjectModel;
using global::System.Diagnostics.CodeAnalysis;
using global::System.Globalization;
using global::System.Linq;
using global::OBeautifulCode.Cloning.Recipes;
using global::OBeautifulCode.Equality.Recipes;
using global::OBeautifulCode.Type;
using global::OBeautifulCode.Type.Recipes;
using static global::System.FormattableString;
[Serializable]
public partial class ModelCloningPublicSetNullableChild1 : IDeepCloneable<ModelCloningPublicSetNullableChild1>
{
/// <inheritdoc />
public new ModelCloningPublicSetNullableChild1 DeepClone() => (ModelCloningPublicSetNullableChild1)this.DeepCloneInternal();
/// <inheritdoc />
protected override ModelCloningPublicSetNullableParent DeepCloneInternal() => ((IDeclareDeepCloneMethod<ModelCloningPublicSetNullableChild1>)this).DeepClone();
}
} | 43.558824 | 167 | 0.634706 | [
"MIT"
] | OBeautifulCode/OBeautifulCode.CodeGen | OBeautifulCode.CodeGen.ModelObject.Test/Models/Scripted/Cloning/PublicSet/Nullable/ModelCloningPublicSetNullableChild1.designer.cs | 1,483 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
//i needed this to enable passing the value of the btn pressed
public class StaticScript : MonoBehaviour
{
static public string mapButton = "";
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
string btn = "";
if (Input.GetMouseButtonDown(0))
{
btn = EventSystem.current.currentSelectedGameObject.name;
}
if (btn == "GrassButton")
{
mapButton = "grass";
}
else if (btn == "GeneratedButton")
{
mapButton = "generated";
}
}
}
| 21.473684 | 70 | 0.547794 | [
"MIT"
] | CityFever/CityFever | Assets/GUI/Scripts/StaticScript.cs | 818 | C# |
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using AtmReportGenerator.Entities;
using AtmReportGenerator.Logging;
using AtmReportGenerator.Utils;
using Tababular;
namespace AtmReportGenerator.Exporters
{
public class TxtFilesReportExporter : IReportExporter
{
private readonly ILogger _logger;
private readonly ReportGeneratorOptions _generatorOptions;
private readonly TableFormatter _tableFormatter;
public TxtFilesReportExporter(ILogger logger, ReportGeneratorOptions generatorOptions)
{
_logger = logger;
_generatorOptions = generatorOptions;
_tableFormatter = new TableFormatter();
}
public void Export(AggregatedAtmReport report)
{
_logger.LogInformation($"Starting export to folder {_generatorOptions.DestinationFolder}");
PrepareDirectory();
var dailyReports = report.BuildAggregatedDailyReport();
foreach (var aggregatedAtmDailyReport in dailyReports) LogAggregatedDailyReport(aggregatedAtmDailyReport);
}
public void LogAggregatedDailyReport(AggregatedAtmDailyReport report)
{
_logger.LogInformation($"Processing report for {report.Date.ToShortAtmFormat()}");
PrepareReportFile(report);
var dayStartReportsTable = report.DailyReports.Select(BuildDailyReportRow);
var dayStartReportsTableText = _tableFormatter.FormatDictionaries(dayStartReportsTable);
var eventsTable = BuildEventsTable(report);
var eventsTableText = _tableFormatter.FormatDictionaries(eventsTable);
var reportText = new StringBuilder();
reportText.AppendLine("Остатки");
reportText.AppendLine(dayStartReportsTableText);
reportText.AppendLine();
reportText.AppendLine("Загрузка/Выгрузка");
reportText.AppendLine(eventsTableText);
File.WriteAllText(GetReportFilePath(report), reportText.ToString(), Encoding.UTF8);
_logger.LogInformation($"Exported report for {report.Date.ToShortAtmFormat()}!");
}
private void PrepareDirectory()
{
PrepareDirectory(_generatorOptions.DestinationFolder);
}
private void PrepareReportFile(AggregatedAtmDailyReport report)
{
PrepareReportDirectory(report);
var reportFilePath = GetReportFilePath(report);
if (File.Exists(reportFilePath))
{
_logger.LogInformation($"Report for {report.Date.ToShortAtmFormat()} already exists, deleting...");
File.Delete(reportFilePath);
}
}
private string GetReportFilePath(AggregatedAtmDailyReport report) => Path.Combine(
_generatorOptions.DestinationFolder,
report.Date.Year.ToString(),
report.Date.Month.ToString(),
$"{report.Date.Day}.txt");
private void PrepareReportDirectory(AggregatedAtmDailyReport report)
{
var monthFolderPath = Path.Combine(_generatorOptions.DestinationFolder, report.Date.Year.ToString(), report.Date.Month.ToString());
PrepareDirectory(monthFolderPath);
}
private void PrepareDirectory(string path)
{
if (Directory.Exists(path)) return;
_logger.LogInformation($"Folder {path} not found, creating...");
Directory.CreateDirectory(path);
}
private IEnumerable<Dictionary<string, string>> BuildEventsTable(AggregatedAtmDailyReport report)
{
foreach (var dailyReport in report.DailyReports)
{
var cashLoad = dailyReport.CashLoad;
var cashUnload = dailyReport.CashUnload;
if (cashLoad > 0 || cashUnload > 0)
yield return new Dictionary<string, string>
{
{ "Устройство", dailyReport.AtmId },
{ "Загрузка", cashLoad.ToString(CultureInfo.InvariantCulture) },
{ "Выгрузка", cashUnload.ToString(CultureInfo.InvariantCulture) }
};
}
}
private Dictionary<string, string> BuildDailyReportRow(AtmDailyReport dailyReport) =>
new Dictionary<string, string>
{
{ "Устройство", dailyReport.AtmId },
{ "Остаток BYN", dailyReport.WorkingDayStartReport.Remaining.ToString(CultureInfo.InvariantCulture) }
};
}
} | 36.614173 | 143 | 0.643226 | [
"MIT"
] | andrew-kulikov/atm-report-generator | src/AtmReportGenerator/Exporters/TxtFilesReportExporter.cs | 4,718 | C# |
using UnityEngine;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
[VolumeComponentEditor(typeof(LiftGammaGain))]
sealed class LiftGammaGainEditor : VolumeComponentEditor
{
SerializedDataParameter m_Lift;
SerializedDataParameter m_Gamma;
SerializedDataParameter m_Gain;
readonly TrackballUIDrawer m_TrackballUIDrawer = new TrackballUIDrawer();
public override void OnEnable()
{
var o = new PropertyFetcher<LiftGammaGain>(serializedObject);
m_Lift = Unpack(o.Find(x => x.lift));
m_Gamma = Unpack(o.Find(x => x.gamma));
m_Gain = Unpack(o.Find(x => x.gain));
}
public override void OnInspectorGUI()
{
if (UniversalRenderPipeline.asset?.postProcessingFeatureSet == PostProcessingFeatureSet.PostProcessingV2)
{
EditorGUILayout.HelpBox(UniversalRenderPipelineAssetEditor.Styles.postProcessingGlobalWarning, MessageType.Warning);
return;
}
using (new EditorGUILayout.HorizontalScope())
{
m_TrackballUIDrawer.OnGUI(m_Lift.value, m_Lift.overrideState, EditorGUIUtility.TrTextContent("Lift"), GetLiftValue);
GUILayout.Space(4f);
m_TrackballUIDrawer.OnGUI(m_Gamma.value, m_Gamma.overrideState, EditorGUIUtility.TrTextContent("Gamma"), GetLiftValue);
GUILayout.Space(4f);
m_TrackballUIDrawer.OnGUI(m_Gain.value, m_Gain.overrideState, EditorGUIUtility.TrTextContent("Gain"), GetLiftValue);
}
}
static Vector3 GetLiftValue(Vector4 x) => new Vector3(x.x + x.w, x.y + x.w, x.z + x.w);
}
}
| 39.888889 | 136 | 0.636769 | [
"MIT"
] | DanielConrad/HSTD | Library/PackageCache/com.unity.render-pipelines.universal@7.3.1/Editor/Overrides/LiftGammaGainEditor.cs | 1,795 | C# |
using UnityEngine;
using WebXR;
using System.Text;
public class XRPKControllerInteraction : MonoBehaviour
{
public TextMesh controllerInputText;
public TextMesh leftControllerPosition;
public TextMesh rightControllerPosition;
private WebXRController _controller;
private Rigidbody _rb;
private StringBuilder _sb = new StringBuilder();
void Start()
{
_controller = GetComponent<WebXRController>();
_rb = GetComponent<Rigidbody>();
}
void Update()
{
PrintCurrentInput();
// mainly to sync RigidBody position
transform.SetPositionAndRotation(_controller.transform.position, _controller.transform.rotation);
}
void PrintCurrentInput()
{
_sb.Clear();
// controller events
if (_controller.GetAxis(WebXRController.AxisTypes.Grip) > 0)
{
_sb.Append(_controller.hand + " controller grip Value: " + _controller.GetAxis(WebXRController.AxisTypes.Grip).ToString() + "\n");
}
if (_controller.GetAxis(WebXRController.AxisTypes.Trigger) > 0)
{
_sb.Append(_controller.hand + " controller trigger Value: " + _controller.GetAxis(WebXRController.AxisTypes.Trigger).ToString() + "\n");
}
if (_controller.GetButton(WebXRController.ButtonTypes.ButtonA))
{
_sb.Append("Button A Pressed on " + _controller.hand + " Controller \n");
}
if (_controller.GetButton(WebXRController.ButtonTypes.ButtonB))
{
_sb.Append("Button B Pressed on " + _controller.hand + " Controller \n");
}
if (_controller.GetButton(WebXRController.ButtonTypes.Trigger))
{
_sb.Append("Trigger Pressed on " + _controller.hand + " Controller \n");
}
if (_controller.GetButton(WebXRController.ButtonTypes.Grip))
{
_sb.Append("Grip Pressed on " + _controller.hand + " Controller \n");
}
if (_sb.Length != 0)
{
controllerInputText.text = _sb.ToString();
}
// controller posrot
switch (_controller.hand)
{
case WebXRControllerHand.LEFT:
leftControllerPosition.text = "Left Controller Position:\n" + " " + (_controller.transform.position.x.ToString("F2") + " " + _controller.transform.position.y.ToString("F2") + " " + _controller.transform.position.z.ToString("F2"));
leftControllerPosition.text += "\n Left Controller Rotation:\n" + " " + (_controller.transform.rotation.x.ToString("F2") + " " + _controller.transform.rotation.y.ToString("F2") + " " + _controller.transform.rotation.z.ToString("F2") + " " + _controller.transform.rotation.w.ToString("F2"));
break;
case WebXRControllerHand.RIGHT:
rightControllerPosition.text = "Right Controller Position:\n" + (_controller.transform.position.x.ToString("F2") + " " + _controller.transform.position.y.ToString("F2") + " " + _controller.transform.position.z.ToString("F2"));
rightControllerPosition.text += "\n Right Controller Rotation:\n" + (_controller.transform.rotation.x.ToString("F2") + " " + _controller.transform.rotation.y.ToString("F2") + " " + _controller.transform.rotation.z.ToString("F2") + " " + _controller.transform.rotation.w.ToString("F2"));
break;
default:
break;
}
}
}
| 40.494118 | 306 | 0.6319 | [
"MIT"
] | PlutoVR/unity-networked-xrpk-sample | Assets/Samples/Pluto XR Package Exporter/0.0.2/Sample XRPK Scene/Scripts/XRPKControllerInteraction.cs | 3,442 | C# |
using System;
using Amazon.S3;
using Amazon.S3.Transfer;
namespace aws_net_workshop.examples
{
class _10_CreateLargeObject_TransferUtility
{
public static void Main(string[] args)
{
// create the AWS S3 client
AmazonS3Client s3 = AWSS3Factory.getS3Client();
// create the transfer utility using AWS S3 client
TransferUtility fileTransferUtility = new TransferUtility(s3);
// retrieve the object key/value from user
Console.Write("Enter the object key: ");
string key = Console.ReadLine();
Console.Write("Enter the file location: ");
string filePath = Console.ReadLine();
// configure transfer utility for parallel upload
TransferUtilityUploadRequest uploadRequest = new TransferUtilityUploadRequest()
{
BucketName = AWSS3Factory.S3_BUCKET,
FilePath = filePath,
StorageClass = S3StorageClass.Standard,
PartSize = 1024 * 1024 * 2, // 2MB
Key = key,
};
// grab the start time of upload
DateTime startDate = DateTime.Now;
// upload the file
fileTransferUtility.Upload(uploadRequest);
// grab the end time of upload
DateTime endDate = DateTime.Now;
Console.WriteLine(string.Format("Completed multi-part upload for object {0}/{1} with file path: {2}", AWSS3Factory.S3_BUCKET, key, filePath));
Console.WriteLine(string.Format("Process took: {0} seconds.", (endDate - startDate).TotalSeconds.ToString()));
Console.ReadLine();
}
}
}
| 34.979592 | 154 | 0.599183 | [
"Apache-2.0"
] | adrianmo/ecs-samples | aws-net-workshop/aws-net-workshop/examples/_10_CreateLargeObject_TransferUtility.cs | 1,716 | C# |
using System;
using System.ComponentModel;
using FarsiLibrary.FX.Utils;
namespace FarsiLibrary.FX.Win.Controls
{
public class CalendarDay : INotifyPropertyChanged
{
private DateTime date;
private bool isOtherMonth;
private bool isSelectable;
private object data;
public event PropertyChangedEventHandler PropertyChanged;
public CalendarDay(DateTime dt)
{
date = dt;
}
/// <summary>
/// DateTime
/// </summary>
public DateTime Date
{
get { return date; }
internal set
{
if (date != value)
{
DateTime oldDate = date;
date = value;
OnPropertyChanged("Date");
if (IsDateToday(oldDate) != IsDateToday(date))
{
OnPropertyChanged("IsToday");
}
if (IsDateWeekend(oldDate) != IsDateWeekend(date))
{
OnPropertyChanged("IsWeekend");
}
}
}
}
public bool IsOtherMonth
{
get { return isOtherMonth; }
internal set
{
if (isOtherMonth != value)
{
isOtherMonth = value;
OnPropertyChanged("IsOtherMonth");
}
}
}
public bool IsSelectable
{
get { return isSelectable; }
internal set
{
if (isSelectable != value)
{
isSelectable = value;
OnPropertyChanged("IsSelectable");
}
}
}
public bool IsToday
{
get { return IsDateToday(date); }
}
public bool IsWeekend
{
get { return IsDateWeekend(date); }
}
public object Data
{
get { return data; }
internal set
{
data = value;
OnPropertyChanged("Data");
}
}
public override string ToString()
{
return date.ToShortDateString();
}
internal void InternalUpdate(CalendarDay cdate)
{
Date = cdate.Date;
IsOtherMonth = cdate.IsOtherMonth;
IsSelectable = cdate.IsSelectable;
}
protected void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
private bool IsDateWeekend(DateTime selectedDate)
{
if(CultureHelper.IsFarsiCulture || CultureHelper.IsArabicCulture)
{
return selectedDate.DayOfWeek == DayOfWeek.Friday || selectedDate.DayOfWeek == DayOfWeek.Thursday;
}
return date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday;
}
private bool IsDateToday(DateTime selectedDate)
{
return CompareYearMonthDay(selectedDate, DateTime.Now) == 0;
}
internal static int CompareYearMonthDay(DateTime dt1, DateTime dt2)
{
DateTime first = new DateTime(dt1.Year, dt1.Month, dt1.Day);
DateTime second = new DateTime(dt2.Year, dt2.Month, dt2.Day);
TimeSpan ts = first - second;
return ts.Days;
}
}
} | 26.602941 | 114 | 0.484522 | [
"MIT"
] | shenhx/DotNetAll | 09OpenSources/FarsiLibraryFX_src/FarsiLibrary.FX.Win/Controls/MonthView/CalendarDay.cs | 3,618 | C# |
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "-")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1716:Identifiers should not match keywords", Justification = "-")]
| 67.375 | 152 | 0.784787 | [
"MIT"
] | frblondin/LinqQueryIndex | LinqQueryIndex/GlobalSuppressions.cs | 539 | C# |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Workday.Compensation
{
[GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")]
[Serializable]
public class PositionObjectType : INotifyPropertyChanged
{
private PositionObjectIDType[] idField;
private string descriptorField;
[method: CompilerGenerated]
[CompilerGenerated]
public event PropertyChangedEventHandler PropertyChanged;
[XmlElement("ID", Order = 0)]
public PositionObjectIDType[] ID
{
get
{
return this.idField;
}
set
{
this.idField = value;
this.RaisePropertyChanged("ID");
}
}
[XmlAttribute(Form = XmlSchemaForm.Qualified)]
public string Descriptor
{
get
{
return this.descriptorField;
}
set
{
this.descriptorField = value;
this.RaisePropertyChanged("Descriptor");
}
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| 21.639344 | 136 | 0.729545 | [
"MIT"
] | matteofabbri/Workday.WebServices | Workday.Compensation/PositionObjectType.cs | 1,320 | C# |
using asp_ng.Core;
using asp_ng.Models;
using asp_ng.ViewModels;
using AutoMapper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace asp_ng.Controllers
{
[Route("/api/vehicles/{vehicleId}/photos")]
public class PhotosController:Controller
{
private readonly IVehicleRepository vehicleRepository;
private readonly IHostingEnvironment host;
private readonly IUnitOfWork unitOfWork;
private readonly IMapper mapper;
private readonly PhotoSettings photoSettings;
private readonly IPhotoRepository photoRepository;
public PhotosController(IHostingEnvironment host,
IVehicleRepository vehicleRepository,
IPhotoRepository photoRepository,
IUnitOfWork unitOfWork,
IMapper mapper,
IOptionsSnapshot<PhotoSettings> options
)
{
this.photoSettings = options.Value;
this.host = host;
this.unitOfWork = unitOfWork;
this.vehicleRepository = vehicleRepository;
this.photoRepository = photoRepository;
this.mapper = mapper;
Console.WriteLine("The environment www is" + host.WebRootPath);
}
[HttpPost]
public async Task<IActionResult> Upload(int vehicleId, IFormFile file) {
var vehicle = await vehicleRepository.GetVehicle(vehicleId, includeRelated: false);
#region validations
if (vehicle == null)
{
return NotFound();
}
if (file == null || file.Length == 0)
{
return BadRequest("No photo");
}
// max file size is 5mb
if(file.Length > photoSettings.MaxFileSize)
{
return BadRequest("Maximum file size exceeded");
}
if(!photoSettings.IsSupported(file.FileName))
{
return BadRequest("Invalid file type");
}
#endregion
var uploadsFolderPath = Path.Combine(host.WebRootPath, "uploads");
if (!Directory.Exists(uploadsFolderPath))
{
Directory.CreateDirectory(uploadsFolderPath);
}
//todo: check for the extension of the file
var newFileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
var newFilePath = Path.Combine(uploadsFolderPath, newFileName);
using(var stream = new FileStream(newFilePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
//todo: generate a thumbnail
var photo = new Photo { FileName = newFileName };
vehicle.Photos.Add(photo);
await unitOfWork.CompleteAsync();
return Ok(mapper.Map<Photo, PhotoViewModel>(photo));
}
[HttpGet]
public async Task<IEnumerable<PhotoViewModel>> GetPhotos(int vehicleId)
{
var photos = await photoRepository.GetPhotos(vehicleId);
return mapper.Map<IEnumerable<Photo>, IEnumerable<PhotoViewModel>>(photos);
}
[HttpDelete]
public async Task<IActionResult> DeletePhoto(int photoId,string fileName)
{
await photoRepository.DeletePhotoAsync(photoId);
var uploadsFolderPath = Path.Combine(host.WebRootPath, "uploads/");
if (!Directory.Exists(uploadsFolderPath))
{
return BadRequest();
}
var file = new FileInfo(Path.Combine(uploadsFolderPath, fileName));
if (file.Exists)
{
file.Delete();
}
return Ok("photo deleted");
}
}
}
| 31.769841 | 95 | 0.594804 | [
"MIT"
] | brijmcq/aspcore-ng | Controllers/PhotosController.cs | 4,005 | C# |
using System;
using NetRuntimeSystem = System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Collections.Generic;
using NetOffice;
namespace NetOffice.ExcelApi
{
///<summary>
/// IButton
///</summary>
public class IButton_ : COMObject
{
#region Construction
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public IButton_(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IButton_(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="comProxy">inner wrapped COM proxy</param>
/// <param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IButton_(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IButton_(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
/// <param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IButton_(ICOMObject replacedObject) : base(replacedObject)
{
}
/// <summary>
/// Hidden stub .ctor
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IButton_() : base()
{
}
/// <param name="progId">registered ProgID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IButton_(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <param name="start">optional object Start</param>
/// <param name="length">optional object Length</param>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public NetOffice.ExcelApi.Characters get_Characters(object start, object length)
{
object[] paramsArray = Invoker.ValidateParamsArray(start, length);
object returnItem = Invoker.PropertyGet(this, "Characters", paramsArray);
NetOffice.ExcelApi.Characters newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Characters.LateBindingApiWrapperType) as NetOffice.ExcelApi.Characters;
return newObject;
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Alias for get_Characters
/// </summary>
/// <param name="start">optional object Start</param>
/// <param name="length">optional object Length</param>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.ExcelApi.Characters Characters(object start, object length)
{
return get_Characters(start, length);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <param name="start">optional object Start</param>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public NetOffice.ExcelApi.Characters get_Characters(object start)
{
object[] paramsArray = Invoker.ValidateParamsArray(start);
object returnItem = Invoker.PropertyGet(this, "Characters", paramsArray);
NetOffice.ExcelApi.Characters newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Characters.LateBindingApiWrapperType) as NetOffice.ExcelApi.Characters;
return newObject;
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Alias for get_Characters
/// </summary>
/// <param name="start">optional object Start</param>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.ExcelApi.Characters Characters(object start)
{
return get_Characters(start);
}
#endregion
#region Methods
#endregion
}
///<summary>
/// Interface IButton
/// SupportByVersion Excel, 9,10,11,12,14,15,16
///</summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
[EntityTypeAttribute(EntityType.IsInterface)]
public class IButton : COMObject
{
#pragma warning disable
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(IButton);
return _type;
}
}
#endregion
#region Construction
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public IButton(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IButton(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IButton(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IButton(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IButton(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IButton() : base()
{
}
/// <param name="progId">registered ProgID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IButton(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.ExcelApi.Application Application
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Application", paramsArray);
NetOffice.ExcelApi.Application newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Application.LateBindingApiWrapperType) as NetOffice.ExcelApi.Application;
return newObject;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.ExcelApi.Enums.XlCreator Creator
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Creator", paramsArray);
int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem);
return (NetOffice.ExcelApi.Enums.XlCreator)intReturnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object Parent
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray);
ICOMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem);
return newObject;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.ExcelApi.Range BottomRightCell
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BottomRightCell", paramsArray);
NetOffice.ExcelApi.Range newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Range.LateBindingApiWrapperType) as NetOffice.ExcelApi.Range;
return newObject;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public bool Enabled
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Enabled", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Enabled", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public Double Height
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Height", paramsArray);
return NetRuntimeSystem.Convert.ToDouble(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Height", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public Int32 Index
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Index", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public Double Left
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Left", paramsArray);
return NetRuntimeSystem.Convert.ToDouble(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Left", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public bool Locked
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Locked", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Locked", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public string Name
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Name", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Name", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string OnAction
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnAction", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnAction", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object Placement
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Placement", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Placement", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public bool PrintObject
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "PrintObject", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "PrintObject", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public Double Top
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Top", paramsArray);
return NetRuntimeSystem.Convert.ToDouble(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Top", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.ExcelApi.Range TopLeftCell
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "TopLeftCell", paramsArray);
NetOffice.ExcelApi.Range newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Range.LateBindingApiWrapperType) as NetOffice.ExcelApi.Range;
return newObject;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public bool Visible
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Visible", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Visible", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public Double Width
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Width", paramsArray);
return NetRuntimeSystem.Convert.ToDouble(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Width", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public Int32 ZOrder
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "ZOrder", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.ExcelApi.ShapeRange ShapeRange
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "ShapeRange", paramsArray);
NetOffice.ExcelApi.ShapeRange newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.ShapeRange.LateBindingApiWrapperType) as NetOffice.ExcelApi.ShapeRange;
return newObject;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public bool AddIndent
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "AddIndent", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "AddIndent", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object AutoScaleFont
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "AutoScaleFont", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "AutoScaleFont", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public bool AutoSize
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "AutoSize", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "AutoSize", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public string Caption
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Caption", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Caption", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.ExcelApi.Characters Characters
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Characters", paramsArray);
NetOffice.ExcelApi.Characters newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Characters.LateBindingApiWrapperType) as NetOffice.ExcelApi.Characters;
return newObject;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.ExcelApi.Font Font
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Font", paramsArray);
NetOffice.ExcelApi.Font newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Font.LateBindingApiWrapperType) as NetOffice.ExcelApi.Font;
return newObject;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public string Formula
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Formula", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Formula", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object HorizontalAlignment
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "HorizontalAlignment", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "HorizontalAlignment", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public bool LockedText
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "LockedText", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "LockedText", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object Orientation
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Orientation", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Orientation", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public string Text
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Text", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Text", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object VerticalAlignment
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "VerticalAlignment", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "VerticalAlignment", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public Int32 ReadingOrder
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "ReadingOrder", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "ReadingOrder", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object Accelerator
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Accelerator", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Accelerator", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public bool CancelButton
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "CancelButton", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "CancelButton", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public bool DefaultButton
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "DefaultButton", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "DefaultButton", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public bool DismissButton
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "DismissButton", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "DismissButton", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public bool HelpButton
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "HelpButton", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "HelpButton", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object PhoneticAccelerator
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "PhoneticAccelerator", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "PhoneticAccelerator", paramsArray);
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object BringToFront()
{
object[] paramsArray = null;
object returnItem = Invoker.MethodReturn(this, "BringToFront", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object Copy()
{
object[] paramsArray = null;
object returnItem = Invoker.MethodReturn(this, "Copy", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
/// <param name="appearance">optional NetOffice.ExcelApi.Enums.XlPictureAppearance Appearance = 2</param>
/// <param name="format">optional NetOffice.ExcelApi.Enums.XlCopyPictureFormat Format = -4147</param>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object CopyPicture(object appearance, object format)
{
object[] paramsArray = Invoker.ValidateParamsArray(appearance, format);
object returnItem = Invoker.MethodReturn(this, "CopyPicture", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
[CustomMethodAttribute]
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object CopyPicture()
{
object[] paramsArray = null;
object returnItem = Invoker.MethodReturn(this, "CopyPicture", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
/// <param name="appearance">optional NetOffice.ExcelApi.Enums.XlPictureAppearance Appearance = 2</param>
[CustomMethodAttribute]
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object CopyPicture(object appearance)
{
object[] paramsArray = Invoker.ValidateParamsArray(appearance);
object returnItem = Invoker.MethodReturn(this, "CopyPicture", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object Cut()
{
object[] paramsArray = null;
object returnItem = Invoker.MethodReturn(this, "Cut", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object Delete()
{
object[] paramsArray = null;
object returnItem = Invoker.MethodReturn(this, "Delete", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object Duplicate()
{
object[] paramsArray = null;
object returnItem = Invoker.MethodReturn(this, "Duplicate", paramsArray);
object newObject = Factory.CreateObjectFromComProxy(this,returnItem);
return newObject;
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
/// <param name="replace">optional object Replace</param>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object Select(object replace)
{
object[] paramsArray = Invoker.ValidateParamsArray(replace);
object returnItem = Invoker.MethodReturn(this, "Select", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
[CustomMethodAttribute]
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object Select()
{
object[] paramsArray = null;
object returnItem = Invoker.MethodReturn(this, "Select", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object SendToBack()
{
object[] paramsArray = null;
object returnItem = Invoker.MethodReturn(this, "SendToBack", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
/// <param name="customDictionary">optional object CustomDictionary</param>
/// <param name="ignoreUppercase">optional object IgnoreUppercase</param>
/// <param name="alwaysSuggest">optional object AlwaysSuggest</param>
/// <param name="spellLang">optional object SpellLang</param>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object CheckSpelling(object customDictionary, object ignoreUppercase, object alwaysSuggest, object spellLang)
{
object[] paramsArray = Invoker.ValidateParamsArray(customDictionary, ignoreUppercase, alwaysSuggest, spellLang);
object returnItem = Invoker.MethodReturn(this, "CheckSpelling", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
[CustomMethodAttribute]
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object CheckSpelling()
{
object[] paramsArray = null;
object returnItem = Invoker.MethodReturn(this, "CheckSpelling", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
/// <param name="customDictionary">optional object CustomDictionary</param>
[CustomMethodAttribute]
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object CheckSpelling(object customDictionary)
{
object[] paramsArray = Invoker.ValidateParamsArray(customDictionary);
object returnItem = Invoker.MethodReturn(this, "CheckSpelling", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
/// <param name="customDictionary">optional object CustomDictionary</param>
/// <param name="ignoreUppercase">optional object IgnoreUppercase</param>
[CustomMethodAttribute]
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object CheckSpelling(object customDictionary, object ignoreUppercase)
{
object[] paramsArray = Invoker.ValidateParamsArray(customDictionary, ignoreUppercase);
object returnItem = Invoker.MethodReturn(this, "CheckSpelling", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
/// <param name="customDictionary">optional object CustomDictionary</param>
/// <param name="ignoreUppercase">optional object IgnoreUppercase</param>
/// <param name="alwaysSuggest">optional object AlwaysSuggest</param>
[CustomMethodAttribute]
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object CheckSpelling(object customDictionary, object ignoreUppercase, object alwaysSuggest)
{
object[] paramsArray = Invoker.ValidateParamsArray(customDictionary, ignoreUppercase, alwaysSuggest);
object returnItem = Invoker.MethodReturn(this, "CheckSpelling", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
ICOMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
#endregion
#pragma warning restore
}
} | 28.988131 | 193 | 0.673994 | [
"MIT"
] | brunobola/NetOffice | Source/Excel/Interfaces/IButton.cs | 39,078 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Phantasma.CodeGen.Core.Nodes
{
public class IfNode : StatementNode
{
public ExpressionNode expr;
public StatementNode trueBranch;
public StatementNode falseBranch;
public IfNode(BlockNode owner) : base(owner)
{
}
public override IEnumerable<CompilerNode> Nodes
{
get
{
yield return expr;
yield return trueBranch;
if (falseBranch != null) yield return falseBranch;
yield break;
}
}
public override List<Instruction> Emit(Compiler compiler)
{
var temp = this.expr.Emit(compiler);
var first = this.trueBranch.Emit(compiler);
Instruction end = new Instruction() { source = this, target = compiler.AllocLabel(), op = Instruction.Opcode.Label };
Instruction middle = null;
if (falseBranch != null)
{
middle = new Instruction() { source = this, target = compiler.AllocLabel(), op = Instruction.Opcode.Label };
var second = this.falseBranch.Emit(compiler);
temp.Add(new Instruction() { source = this, target = compiler.AllocLabel(), op = Instruction.Opcode.JumpIfTrue, a = temp.Last(), b = middle });
temp.AddRange(second);
temp.Add(new Instruction() { source = this, target = compiler.AllocLabel(), op = Instruction.Opcode.Jump, b = end});
temp.Add(middle);
temp.AddRange(first);
}
else
{
temp.Add(new Instruction() { source = this, target = compiler.AllocLabel(), op = Instruction.Opcode.JumpIfFalse, a = temp.Last(), b = end });
temp.AddRange(first);
}
temp.Add(end);
return temp;
}
}
} | 33.305085 | 159 | 0.551654 | [
"MIT"
] | AttilaSATAN/PhantasmaChain | Phantasma.CodeGen/Core/Nodes/IfNode.cs | 1,967 | C# |
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Destructurama.Attributed;
using FluentValidation;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using ProjectName.Application.Contracts.Interfaces;
using ProjectName.Application.Domain.Entities;
using ProjectName.Application.Domain.Events.TodoItems;
using ProjectName.Application.Models.Dtos;
using ProjectName.Common.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ProjectName.Application.TodoItems.Commands.UpdateTodoItem
{
public class UpdateTodoItemCommand : IRequest<TodoItemDto>
{
public Guid ReferenceId { get; set; }
[LogMasked(ShowLast = 3)]
public string Title { get; set; }
public bool Done { get; set; }
}
public class UpdateTodoItemCommandHandler : RequestHandlerBase, IRequestHandler<UpdateTodoItemCommand, TodoItemDto>
{
public UpdateTodoItemCommandHandler(IApplicationDbContext context, ILogger<UpdateTodoItemCommandHandler> logger, IMapper mapper) : base(context, logger, mapper)
{ }
public async Task<TodoItemDto> Handle(UpdateTodoItemCommand request, CancellationToken cancellationToken)
{
var entity = await Context.TodoItems.FirstOrDefaultAsync(x => x.ReferenceId.Value == request.ReferenceId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (entity == null)
{
throw new NotFoundException(nameof(TodoItem), request.ReferenceId);
}
entity.Title = request.Title;
entity.Done = request.Done;
if (entity.Done == true)
{
entity.DomainEvents.Add(new TodoItemCompletedEvent(entity));
}
else
{
entity.DomainEvents.Add(new TodoItemUpdatedEvent(entity));
}
await Context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return new List<TodoItem>() { entity }.AsQueryable().ProjectTo<TodoItemDto>(Mapper.ConfigurationProvider).First();
}
}
public class UpdateTodoItemCommandValidator : AbstractValidator<UpdateTodoItemCommand>
{
public UpdateTodoItemCommandValidator()
{
RuleFor(v => v.Title)
.MaximumLength(200)
.NotEmpty();
}
}
}
| 33.405405 | 178 | 0.686084 | [
"MIT"
] | haefele-software/base-api | template/ProjectName.Application/TodoItems/Commands/UpdateTodoItem/UpdateTodoItemCommand.cs | 2,474 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해
// 제어됩니다. 어셈블리와 관련된 정보를 수정하려면
// 이러한 특성 값을 변경하세요.
[assembly: AssemblyTitle("TaleKitEditor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TaleKitEditor")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에
// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면
// 해당 형식에 대해 ComVisible 특성을 true로 설정하세요.
[assembly: ComVisible(false)]
//지역화 가능 애플리케이션 빌드를 시작하려면 다음을 설정하세요.
//.csproj 파일에서 <PropertyGroup> 내에 <UICulture>CultureYouAreCodingWith</UICulture>를
//설정하십시오. 예를 들어 소스 파일에서 영어(미국)를
//사용하는 경우 <UICulture>를 en-US로 설정합니다. 그런 다음 아래
//NeutralResourceLanguage 특성의 주석 처리를 제거합니다. 아래 줄의 "en-US"를 업데이트하여
//프로젝트 파일의 UICulture 설정과 일치시킵니다.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //테마별 리소스 사전의 위치
//(페이지 또는 응용 프로그램 리소스 사진에
// 리소스가 없는 경우에 사용됨)
ResourceDictionaryLocation.SourceAssembly //제네릭 리소스 사전의 위치
//(페이지 또는 응용 프로그램 리소스 사진에
// 리소스가 없는 경우에 사용됨)
)]
// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다.
//
// 주 버전
// 부 버전
// 빌드 번호
// 수정 버전
//
// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를
// 기본값으로 할 수 있습니다.
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 30.589286 | 92 | 0.677758 | [
"MIT"
] | Bgoon/TaleKit | TaleKit/TaleKitEditor/Properties/AssemblyInfo.cs | 2,488 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Ecs.Model.V20140526;
using System;
using System.Collections.Generic;
namespace Aliyun.Acs.Ecs.Transform.V20140526
{
public class CancelPhysicalConnectionResponseUnmarshaller
{
public static CancelPhysicalConnectionResponse Unmarshall(UnmarshallerContext context)
{
CancelPhysicalConnectionResponse cancelPhysicalConnectionResponse = new CancelPhysicalConnectionResponse();
cancelPhysicalConnectionResponse.HttpResponse = context.HttpResponse;
cancelPhysicalConnectionResponse.RequestId = context.StringValue("CancelPhysicalConnection.RequestId");
return cancelPhysicalConnectionResponse;
}
}
} | 39.894737 | 111 | 0.772427 | [
"Apache-2.0"
] | brightness007/unofficial-aliyun-openapi-net-sdk | aliyun-net-sdk-ecs/Ecs/Transform/V20140526/CancelPhysicalConnectionResponseUnmarshaller.cs | 1,516 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GitHub.Models;
using GitHub.VisualStudio;
using Microsoft.Win32;
using System.IO;
namespace GitHub.TeamFoundation
{
internal class RegistryHelper
{
const string TEGitKey = @"Software\Microsoft\VisualStudio\14.0\TeamFoundation\GitSourceControl";
static RegistryKey OpenGitKey(string path)
{
return Microsoft.Win32.Registry.CurrentUser.OpenSubKey(TEGitKey + "\\" + path, true);
}
internal static IEnumerable<ILocalRepositoryModel> PokeTheRegistryForRepositoryList()
{
using (var key = OpenGitKey("Repositories"))
{
return key.GetSubKeyNames().Select(x =>
{
using (var subkey = key.OpenSubKey(x))
{
try
{
var path = subkey?.GetValue("Path") as string;
if (path != null && Directory.Exists(path))
return new LocalRepositoryModel(path);
}
catch (Exception)
{
// no sense spamming the log, the registry might have ton of stale things we don't care about
}
return null;
}
})
.Where(x => x != null)
.ToList();
}
}
internal static string PokeTheRegistryForLocalClonePath()
{
using (var key = OpenGitKey("General"))
{
return (string)key?.GetValue("DefaultRepositoryPath", string.Empty, RegistryValueOptions.DoNotExpandEnvironmentNames);
}
}
const string NewProjectDialogKeyPath = @"Software\Microsoft\VisualStudio\14.0\NewProjectDialog";
const string MRUKeyPath = "MRUSettingsLocalProjectLocationEntries";
internal static string SetDefaultProjectPath(string path)
{
var old = String.Empty;
try
{
var newProjectKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(NewProjectDialogKeyPath, true) ??
Microsoft.Win32.Registry.CurrentUser.CreateSubKey(NewProjectDialogKeyPath);
if (newProjectKey == null)
{
throw new GitHubLogicException(
string.Format(
CultureInfo.CurrentCulture,
"Could not open or create registry key '{0}'",
NewProjectDialogKeyPath));
}
using (newProjectKey)
{
var mruKey = newProjectKey.OpenSubKey(MRUKeyPath, true) ??
Microsoft.Win32.Registry.CurrentUser.CreateSubKey(MRUKeyPath);
if (mruKey == null)
{
throw new GitHubLogicException(
string.Format(
CultureInfo.CurrentCulture,
"Could not open or create registry key '{0}'",
MRUKeyPath));
}
using (mruKey)
{
// is this already the default path? bail
old = (string)mruKey.GetValue("Value0", string.Empty, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (String.Equals(path.TrimEnd('\\'), old.TrimEnd('\\'), StringComparison.CurrentCultureIgnoreCase))
return old;
// grab the existing list of recent paths, throwing away the last one
var numEntries = (int)mruKey.GetValue("MaximumEntries", 5);
var entries = new List<string>(numEntries);
for (int i = 0; i < numEntries - 1; i++)
{
var val = (string)mruKey.GetValue("Value" + i, String.Empty, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (!String.IsNullOrEmpty(val))
entries.Add(val);
}
newProjectKey.SetValue("LastUsedNewProjectPath", path);
mruKey.SetValue("Value0", path);
// bump list of recent paths one entry down
for (int i = 0; i < entries.Count; i++)
mruKey.SetValue("Value" + (i + 1), entries[i]);
}
}
}
catch (Exception ex)
{
VsOutputLogger.WriteLine(string.Format(CultureInfo.CurrentCulture, "Error setting the create project path in the registry '{0}'", ex));
}
return old;
}
}
}
| 41.642276 | 151 | 0.49551 | [
"MIT"
] | nsb1271/UWPapplication | src/GitHub.TeamFoundation.14/RegistryHelper.cs | 5,124 | C# |
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace Coding4Fun.Phone.Controls.Converters
{
public class StringToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return string.IsNullOrEmpty(value as string) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| 30.238095 | 104 | 0.68189 | [
"MIT"
] | Coding4FunProjects/Coding4FunToolk | Legacy/Coding4Fun.Phone/Coding4Fun.Phone.Controls/Converters/StringToVisibilityConverter.cs | 637 | C# |
using System.Text.Json;
using Json.More;
namespace Json.Logic.Rules
{
[Operator("===")]
internal class StrictEqualsRule : Rule
{
private readonly Rule _a;
private readonly Rule _b;
public StrictEqualsRule(Rule a, Rule b)
{
_a = a;
_b = b;
}
public override JsonElement Apply(JsonElement data)
{
return _a.Apply(data).IsEquivalentTo(_b.Apply(data)).AsJsonElement();
}
}
} | 17.521739 | 72 | 0.684864 | [
"MIT"
] | ConnectionMaster/json-everything | JsonLogic/Rules/StrictEqualsRule.cs | 405 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace AppAzureSQL.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
}
| 34.4375 | 98 | 0.677858 | [
"MIT"
] | DanielLoRo31/Xamarin-Drivers-Application | AppAzureSQL/AppAzureSQL.iOS/AppDelegate.cs | 1,104 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Z.Dapper.Plus;
namespace Z.Test
{
public partial class Mapper_MapMapper_MapMapper
{
[TestMethod]
public void Z_Test_0009()
{
// Title2: MapSingleDestination_MapMany
Helper.CleanDatabase();
var singleBefore = new EntitySimple_Mapper { Single1 = 1, Single2 = 2, Many1 = 10, Many2 = 20, Many3 = 30, Many4 = 40};
var single = new EntitySimple_Mapper { Single1 = 1, Single2 = 2, Many1 = 10, Many2 = 20, Many3 = 30, Many4 = 40};
using (var cn = Helper.GetConnection())
{
cn.Open();
// PreTest
// Action
DapperPlusManager.Entity<EntitySimple_Mapper>("d47471e6-465a-4f21-89c2-1693398d34f7").Map(x => x.Single1, "Single1_Destination").Map(x => new { x.Many3, x.Many4});cn.BulkInsert("d47471e6-465a-4f21-89c2-1693398d34f7", single);
}
// GET count
int single1 = 0;
int single2 = 0;
int many1 = 0;
int many2 = 0;
int many3 = 0;
int many4 = 0;
int single1_Destination = 0;
int single2_Destination = 0;
int many1_Destination = 0;
int many2_Destination = 0;
int many3_Destination = 0;
int many4_Destination = 0;
using (var connection = Helper.GetConnection())
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = @"
SELECT TOP 1
[Single1] ,
[Single2] ,
[Many1] ,
[Many2] ,
[Many3] ,
[Many4] ,
[Single1_Destination] ,
[Single2_Destination] ,
[Many1_Destination] ,
[Many2_Destination] ,
[Many3_Destination] ,
[Many4_Destination] " +
"FROM [Z.Dapper.Plus].[dbo].[EntitySimple_Mapper]";
using (var reader = command.ExecuteReader())
{
reader.Read();
single1 = reader.IsDBNull(0) ? 0 : reader.GetInt32(0);
single2 = reader.IsDBNull(1) ? 0 : reader.GetInt32(1);
many1 = reader.IsDBNull(2) ? 0 : reader.GetInt32(2);
many2 = reader.IsDBNull(3) ? 0 : reader.GetInt32(3);
many3 = reader.IsDBNull(4) ? 0 : reader.GetInt32(4);
many4 = reader.IsDBNull(5) ? 0 : reader.GetInt32(5);
single1_Destination = reader.IsDBNull(6) ? 0 : reader.GetInt32(6);
single2_Destination = reader.IsDBNull(7) ? 0 : reader.GetInt32(7);
many1_Destination = reader.IsDBNull(8) ? 0 : reader.GetInt32(8);
many2_Destination = reader.IsDBNull(9) ? 0 : reader.GetInt32(9);
many3_Destination = reader.IsDBNull(10) ? 0 : reader.GetInt32(10);
many4_Destination = reader.IsDBNull(11) ? 0 : reader.GetInt32(11);
}
}
}
// Test
Assert.AreEqual(0, single1);
Assert.AreEqual(0, single2);
Assert.AreEqual(0, many1);
Assert.AreEqual(0, many2);
Assert.AreEqual(singleBefore.Many3, many3);
Assert.AreEqual(singleBefore.Many4, many4);
Assert.AreEqual(singleBefore.Single1, single1_Destination);
Assert.AreEqual(0, single2_Destination);
Assert.AreEqual(0, many1_Destination);
Assert.AreEqual(0, many2_Destination);
Assert.AreEqual(0, many3_Destination);
Assert.AreEqual(0, many4_Destination);
Assert.AreEqual(singleBefore.Single1, single.Single1);
Assert.AreEqual(singleBefore.Single2, single.Single2);
Assert.AreEqual(singleBefore.Many1, single.Many1);
Assert.AreEqual(singleBefore.Many2, single.Many2);
Assert.AreEqual(singleBefore.Many3, single.Many3);
Assert.AreEqual(singleBefore.Many4, single.Many4);
}
}
} | 34.198276 | 230 | 0.614822 | [
"MIT"
] | VagrantKm/Dapper-Plus | src/test/Z.Test/Mapper/MapMapper_MapMapper/0009.cs | 3,967 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006-2019, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2019. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.480)
// Version 5.480.0.0 www.ComponentFactory.com
// *****************************************************************************
using ComponentFactory.Krypton.Toolkit;
namespace ComponentFactory.Krypton.Ribbon
{
/// <summary>
/// Manage a collection of button specs for placing within a collection of ViewLayoutDocker instances.
/// </summary>
public class ButtonSpecManagerLayoutRibbon : ButtonSpecManagerLayout
{
#region Identity
/// <summary>
/// Initialize a new instance of the ButtonSpecManagerLayoutRibbon class.
/// </summary>
/// <param name="ribbon">Ribbon that owns the button manager.</param>
/// <param name="redirector">Palette redirector.</param>
/// <param name="variableSpecs">Variable set of button specifications.</param>
/// <param name="fixedSpecs">Fixed set of button specifications.</param>
/// <param name="viewDockers">Array of target view dockers.</param>
/// <param name="viewMetrics">Array of target metric providers.</param>
/// <param name="viewMetricInt">Array of target metrics for outside/inside spacer size.</param>
/// <param name="viewMetricPaddings">Array of target metrics for button padding.</param>
/// <param name="getRenderer">Delegate for returning a tool strip renderer.</param>
/// <param name="needPaint">Delegate for notifying paint requests.</param>
public ButtonSpecManagerLayoutRibbon(KryptonRibbon ribbon,
PaletteRedirect redirector,
ButtonSpecCollectionBase variableSpecs,
ButtonSpecCollectionBase fixedSpecs,
ViewLayoutDocker[] viewDockers,
IPaletteMetric[] viewMetrics,
PaletteMetricInt[] viewMetricInt,
PaletteMetricPadding[] viewMetricPaddings,
GetToolStripRenderer getRenderer,
NeedPaintHandler needPaint)
: base(ribbon, redirector, variableSpecs, fixedSpecs,
viewDockers, viewMetrics, viewMetricInt,
viewMetricPaddings, getRenderer, needPaint)
{
}
#endregion
#region Protected
/// <summary>
/// Create the button spec view appropriate for the button spec.
/// </summary>
/// <param name="redirector">Redirector for acquiring palette values.</param>
/// <param name="viewPaletteMetric">Target metric providers.</param>
/// <param name="viewMetricPadding">Target metric padding.</param>
/// <param name="buttonSpec">ButtonSpec instance.</param>
/// <returns>ButtonSpecView derived class.</returns>
protected override ButtonSpecView CreateButtonSpecView(PaletteRedirect redirector,
IPaletteMetric viewPaletteMetric,
PaletteMetricPadding viewMetricPadding,
ButtonSpec buttonSpec)
{
return new ButtonSpecViewRibbon(redirector, viewPaletteMetric,
viewMetricPadding, this, buttonSpec);
}
#endregion
}
}
| 57.819444 | 157 | 0.570502 | [
"BSD-3-Clause"
] | MarketingInternetOnlines/Krypton-NET-5.480 | Source/Krypton Components/ComponentFactory.Krypton.Ribbon/ButtonSpec/ButtonSpecManagerLayoutRibbon.cs | 4,166 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace StandardLibrary.Other.Stade
{
/// <summary>
///
/// IStade base abstract realisation
///
/// </summary>
/// <typeparam name="TEnum">Type of enum used for Shortcut value</typeparam>
/// <typeparam name="TObject">Type of controled object</typeparam>
public abstract class StadeBase<TEnum, TObject> : IStade<TEnum, TObject> where TEnum : Enum where TObject : class
{
public abstract TEnum ShortcutValue { get; }
public abstract TObject ControledObject { set; }
public virtual void OnDeselected(StadeDeselectedEventArgs<TEnum, TObject> args) { }
public virtual void OnSelected(StadeSelectedEventArgs<TEnum, TObject> args) { }
}
}
| 31.608696 | 114 | 0.737276 | [
"Unlicense"
] | LloydLion/Standard-Library | Standard Library/Other/Stade/StadeBase.cs | 729 | C# |
using System;
using System.IO;
using System.Text;
using toofz.NecroDancer.Replays;
using toofz.NecroDancer.Tests.Properties;
using Xunit;
namespace toofz.NecroDancer.Tests.Replays
{
public class ReplayDataStreamReaderTests
{
public class Cosntructor
{
[DisplayFact(nameof(ArgumentNullException))]
public void StreamIsNull_ThrowsArgumentNullException()
{
// Arrange
Stream stream = null;
// Act -> Assert
Assert.Throws<ArgumentNullException>(() =>
{
new ReplayDataStreamReader(stream);
});
}
[DisplayFact(nameof(ReplayDataStreamReader))]
public void ReturnsReplayDataStreamReader()
{
// Arrange
var stream = Stream.Null;
// Act
var reader = new ReplayDataStreamReader(stream);
// Assert
Assert.IsAssignableFrom<ReplayDataStreamReader>(reader);
}
}
public class ReadReplayDataMethod
{
[DisplayFact(nameof(ReplayData))]
public void ClassicReplayData_ReturnsReplayData()
{
// Arrange
var stream = new MemoryStream(Encoding.UTF8.GetBytes(Resources.ClassicReplayData));
var reader = new ReplayDataStreamReader(stream);
// Act
var replayData = reader.ReadReplayData();
// Assert
var expectedStream = new MemoryStream();
var writer = new ReplayDataStreamWriter(expectedStream);
writer.Write(replayData);
var expected = expectedStream.ToArray();
Assert.Equal(expected, Encoding.UTF8.GetBytes(Resources.ClassicReplayData));
}
[DisplayFact(nameof(ReplayData))]
public void AmplifiedReplayData_ReturnsReplayData()
{
// Arrange
var stream = new MemoryStream(Encoding.UTF8.GetBytes(Resources.AmplifiedReplayData));
var reader = new ReplayDataStreamReader(stream);
// Act
var replayData = reader.ReadReplayData();
// Assert
var expectedStream = new MemoryStream();
var writer = new ReplayDataStreamWriter(expectedStream);
writer.Write(replayData);
var expected = expectedStream.ToArray();
Assert.Equal(expected, Encoding.UTF8.GetBytes(Resources.AmplifiedReplayData));
}
[DisplayFact(nameof(ReplayData))]
public void RemoteReplayData_ReturnsReplayData()
{
// Arrange
var stream = new MemoryStream(Encoding.UTF8.GetBytes(Resources.RemoteReplayData));
var reader = new ReplayDataStreamReader(stream);
// Act
var replayData = reader.ReadReplayData();
// Assert
var expectedStream = new MemoryStream();
var writer = new ReplayDataStreamWriter(expectedStream);
writer.Write(replayData);
var expected = expectedStream.ToArray();
Assert.Equal(expected, Encoding.UTF8.GetBytes(Resources.RemoteReplayData));
}
[DisplayFact(nameof(ReplayData), Skip = "Should empty replays be parsable?")]
public void EmptyReplayData_ReturnsReplayData()
{
// Arrange
var stream = new MemoryStream(Encoding.UTF8.GetBytes(Resources.EmptyReplayData));
var reader = new ReplayDataStreamReader(stream);
// Act
var replayData = reader.ReadReplayData();
// Assert
var expectedStream = new MemoryStream();
var writer = new ReplayDataStreamWriter(expectedStream);
writer.Write(replayData);
var expected = expectedStream.ToArray();
Assert.Equal(expected, Encoding.UTF8.GetBytes(Resources.EmptyReplayData));
}
}
public class ReadLineMethod
{
[DisplayFact]
public void ReturnsLine()
{
// Arrange
var replay = @"a\nb";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(replay));
var reader = new ReplayDataStreamReader(stream);
// Act
var line = reader.ReadLine();
// Assert
Assert.Equal("a", line);
}
[DisplayFact]
public void NoMoreLines_ReturnsNull()
{
// Arrange
var replay = @"a\nb";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(replay));
var reader = new ReplayDataStreamReader(stream);
// Act
reader.ReadLine();
reader.ReadLine();
var line = reader.ReadLine();
// Assert
Assert.Null(line);
}
}
}
}
| 34.578947 | 101 | 0.534627 | [
"MIT"
] | leonard-thieu/toofz-necrodancer-core | test/toofz.NecroDancer.Tests/Replays/ReplayDataStreamReaderTests.cs | 5,258 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Libraries;
using ProgrammingParadigms;
using DomainAbstractions;
using StoryAbstractions;
namespace Application
{
public class GenerateALACode : IEvent
{
// Public fields and properties
public string InstanceName { get; set; } = "Default";
public Graph Graph { get; set; }
// Private fields
private List<string> _instantiations;
private List<string> _wireTos;
private List<string> _allCode;
// Ports
private IDataFlow<List<string>> instantiations;
private IDataFlow<List<string>> wireTos;
private IDataFlow<List<string>> allCode;
void IEvent.Execute()
{
_instantiations = GenerateInstantiations();
_wireTos = GenerateWireTos();
_allCode = new List<string>();
_allCode.AddRange(_instantiations);
_allCode.AddRange(_wireTos);
if (instantiations != null) instantiations.Data = _instantiations;
if (wireTos != null) wireTos.Data = _wireTos;
if (allCode != null) allCode.Data = _allCode;
}
// Methods
public List<string> GenerateInstantiations()
{
_instantiations = new List<string>();
var nodes = Graph.Nodes;
foreach (var node in nodes)
{
var alaNode = node as ALANode;
if (alaNode == null || alaNode.Model.Type == "UNDEFINED" || alaNode.IsReferenceNode) continue;
_instantiations.Add(alaNode.ToInstantiation());
}
return _instantiations;
}
public List<string> GenerateWireTos()
{
_wireTos = new List<string>();
var edges = Graph.Edges.Where(e => e is ALAWire wire && wire.Source != null && wire.Destination != null);
foreach (var edge in edges)
{
var wire = edge as ALAWire;
if (wire == null) continue;
var wireTo = wire.ToWireTo();
_wireTos.Add(wireTo);
}
return _wireTos;
}
private string CreateWireToString(string A, string B, string portName = "")
{
return string.IsNullOrWhiteSpace(portName) ? $"{A}.WireTo({B});" : $"{A}.WireTo({B}, \"{portName}\");";
}
public GenerateALACode()
{
}
}
}
| 27.758242 | 117 | 0.566508 | [
"MIT"
] | MahmoudFayed/GALADE | GALADE_Standalone/Application/Modules/GenerateALACode.cs | 2,528 | C# |
// <copyright file="Account.cs" company="Arm">
// Copyright (c) Arm. All rights reserved.
// </copyright>
namespace MbedCloudSDK.AccountManagement.Model.Account
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iam.Model;
using Mbed.Cloud.Common;
using MbedCloudSDK.Common;
using MbedCloudSDK.Common.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
/// <summary>
/// Account
/// </summary>
public class Account : Entity
{
/// <summary>
/// Gets the status of the account.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
[JsonProperty]
public AccountStatus? Status { get; private set; }
/// <summary>
/// Gets or sets the phone number of the company.
/// </summary>
public string PhoneNumber { get; set; }
/// <summary>
/// Gets or sets the postal code part of the postal address.
/// </summary>
public string Postcode { get; set; }
/// <summary>
/// Gets an array of aliases.
/// </summary>
[JsonProperty]
public List<string> Aliases { get; private set; }
/// <summary>
/// Gets or sets postal address line 2.
/// </summary>
public string AddressLine2 { get; set; }
/// <summary>
/// Gets or sets the city part of the postal address.
/// </summary>
public string City { get; set; }
/// <summary>
/// Gets or sets postal address line 1.
/// </summary>
public string AddressLine1 { get; set; }
/// <summary>
/// Gets or sets the display name for the account.
/// </summary>
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets the state part of the postal address.
/// </summary>
public string State { get; set; }
/// <summary>
/// Gets or sets the company email address for this account.
/// </summary>
public string Email { get; set; }
/// <summary>
/// Gets or sets the name of the company.
/// </summary>
public string Company { get; set; }
/// <summary>
/// Gets time when upgraded to commercial account in UTC format RFC3339.
/// </summary>
[JsonProperty]
public DateTime? UpgradedAt { get; private set; }
/// <summary>
/// Gets the tier level of the account; '0': free tier, commercial account. Other values are reserved for the future.
/// </summary>
[JsonProperty]
public string Tier { get; private set; }
/// <summary>
/// Gets list of limits as key-value pairs if requested.
/// </summary>
[JsonProperty]
public Dictionary<string, string> Limits { get; private set; }
/// <summary>
/// Gets or sets the country part of the postal address.
/// </summary>
public string Country { get; set; }
/// <summary>
/// Gets creation UTC time RFC3339.
/// </summary>
[JsonProperty]
public DateTime? CreatedAt { get; private set; }
/// <summary>
/// Gets or sets the name of the contact person for this account.
/// </summary>
public string Contact { get; set; }
/// <summary>
/// Gets account template ID.
/// </summary>
[JsonProperty]
public string TemplateId { get; private set; }
/// <summary>
/// Gets list of policies.
/// </summary>
/// <value>List of policies.</value>
[JsonProperty]
public List<Policy.Policy> Policies { get; private set; }
/// <summary>
/// Gets or sets a reason note for updating the status of the account
/// </summary>
[JsonProperty]
public string Reason { get; set; }
/// <summary>
/// Gets the Contract number of the customer.
/// </summary>
[JsonProperty]
public string ContractNumber { get; private set; }
/// <summary>
/// Gets the Customer number of the customer.
/// </summary>
[JsonProperty]
public string CustomerNumber { get; private set; }
/// <summary>
/// Gets or sets the number of days before the account expiration notification email should be sent.
/// </summary>
public string ExpiryWarning { get; set; }
/// <summary>
/// Gets or sets the The enforcement status of the multi-factor authentication.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public MultifactorAuthenticationStatusEnum? MultifactorAuthenticationStatus { get; set; }
/// <summary>
/// Gets or sets the list of notification email addresses.
/// </summary>
public List<string> NotificationEmails { get; set; }
/// <summary>
/// Gets the reference note for updating the status of the account.
/// </summary>
[JsonProperty]
public string ReferenceNote { get; private set; }
/// <summary>
/// Gets the last update UTC time RFC3339.
/// </summary>
[JsonProperty]
public DateTime? UpdatedAt { get; private set; }
/// <summary>
/// Gets the sales contact email
/// </summary>
[JsonProperty]
public string SalesContactEmail { get; private set; }
/// <summary>
/// Map to Account object.
/// </summary>
/// <param name="accountInfo">Identity and Account Manangement (IAM) information</param>
/// <returns>Account</returns>
public static Account Map(iam.Model.AccountInfo accountInfo)
{
var account = new Account
{
PhoneNumber = accountInfo.PhoneNumber,
Postcode = accountInfo.PostalCode,
Id = accountInfo.Id,
Aliases = accountInfo.Aliases ?? Enumerable.Empty<string>().ToList(),
AddressLine2 = accountInfo.AddressLine2,
City = accountInfo.City,
AddressLine1 = accountInfo.AddressLine1,
DisplayName = accountInfo.DisplayName,
State = accountInfo.State,
Email = accountInfo.Email,
Status = accountInfo.Status.ParseEnum<AccountStatus>(),
Company = accountInfo.Company,
UpgradedAt = accountInfo.UpgradedAt.ToNullableUniversalTime(),
Tier = accountInfo.Tier,
Limits = accountInfo.Limits ?? new Dictionary<string, string>(),
Country = accountInfo.Country,
CreatedAt = accountInfo.CreatedAt.ToNullableUniversalTime(),
Contact = accountInfo.Contact,
ContractNumber = accountInfo.ContractNumber,
TemplateId = accountInfo.TemplateId,
Policies = accountInfo?.Policies?.Select(p => { return Policy.Policy.Map(p); })?.ToList() ?? Enumerable.Empty<Policy.Policy>().ToList(),
Reason = accountInfo.Reason,
CustomerNumber = accountInfo.CustomerNumber,
ExpiryWarning = accountInfo.ExpirationWarningThreshold,
MultifactorAuthenticationStatus = accountInfo.MfaStatus.ParseEnum<MultifactorAuthenticationStatusEnum>(),
NotificationEmails = accountInfo.NotificationEmails ?? Enumerable.Empty<string>().ToList(),
ReferenceNote = accountInfo.ReferenceNote,
UpdatedAt = accountInfo.UpdatedAt,
SalesContactEmail = accountInfo.SalesContact,
};
return account;
}
/// <summary>
/// Returns the string presentation of the object.
/// </summary>
/// <returns>String presentation of the object.</returns>
public override string ToString()
=> this.DebugDump();
/// <summary>
/// Create an Update Request
/// </summary>
/// <returns>Account update request</returns>
public iam.Model.AccountUpdateReq CreateUpdateRequest()
{
var request = new iam.Model.AccountUpdateReq
{
PhoneNumber = PhoneNumber,
PostalCode = Postcode,
Aliases = Aliases,
AddressLine2 = AddressLine2,
City = City,
AddressLine1 = AddressLine1,
DisplayName = DisplayName,
State = State,
Email = Email,
Company = Company,
Country = Country,
Contact = Contact,
NotificationEmails = NotificationEmails,
ExpirationWarningThreshold = ExpiryWarning,
};
if (MultifactorAuthenticationStatus.HasValue)
{
request.MfaStatus = MultifactorAuthenticationStatus.ParseEnum<AccountUpdateReq.MfaStatusEnum>();
}
return request;
}
}
}
| 35.099237 | 152 | 0.561548 | [
"Apache-2.0"
] | ARMmbed/mbed-cloud-sdk-dotnet | src/Legacy/AccountManagement/Model/Account/Account.cs | 9,198 | C# |
namespace SoundFingerprinting.SQL.Connection
{
using System.Data;
internal interface IDatabaseProviderFactory
{
IDbConnection CreateConnection();
}
} | 19.333333 | 47 | 0.724138 | [
"MIT"
] | AddictedCS/soundfingerprinting.sql | src/SoundFingerprinting.SQL/Connection/IDatabaseProviderFactory.cs | 174 | C# |
// <copyright file="SettingsImport.cs" company="Traced-Ideas, Czech republic">
// Copyright (c) 1990-2021 All Right Reserved
// </copyright>
// <author>vl</author>
// <email></email>
// <date>2021-09-01</date>
// <summary>Part of Largo Composer</summary>
using LargoSharedClasses.Abstract;
using LargoSharedClasses.Music;
using LargoSharedClasses.Port;
using System.Diagnostics.Contracts;
using System.Xml.Linq;
namespace LargoSharedClasses.Settings
{
/// <summary>
/// Settings Import.
/// </summary>
public class SettingsImport
{
/// <summary>
/// Initializes a new instance of the <see cref="SettingsImport"/> class.
/// </summary>
public SettingsImport()
{
this.LastUsedFormat = MusicalSourceType.MIDI;
this.SplitMultiTracks = FileSplit.None;
this.SkipNegligibleTones = true;
}
#region Properties - Xml
/// <summary> Gets Xml representation. </summary>
/// <value> Property description. </value>
public virtual XElement GetXElement {
get {
XElement markSettings = new XElement("Import");
markSettings.Add(new XAttribute("LastUsedFormat", this.LastUsedFormat));
markSettings.Add(new XAttribute("SplitMultiTracks", this.SplitMultiTracks));
markSettings.Add(new XAttribute("SkipNegligibleTones", this.SkipNegligibleTones));
return markSettings;
}
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the last used source.
/// </summary>
/// <value>
/// The last used source.
/// </value>
public MusicalSourceType LastUsedFormat { get; set; }
/// <summary>
/// Gets or sets the split multi tracks.
/// </summary>
/// <value>
/// The split multi tracks.
/// </value>
public FileSplit SplitMultiTracks { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [skip negligible tones].
/// </summary>
/// <value>
/// <c>true</c> if [skip negligible tones]; otherwise, <c>false</c>.
/// </value>
public bool SkipNegligibleTones { get; set; }
#endregion
/// <summary>
/// Sets the x element.
/// </summary>
/// <param name="markSettings">The mark settings.</param>
public void SetXElement(XElement markSettings)
{
Contract.Requires(markSettings != null);
if (markSettings == null) {
return;
}
this.LastUsedFormat = DataEnums.ReadAttributeSourceType(markSettings.Attribute("LastUsedFormat"));
this.SplitMultiTracks = DataEnums.ReadAttributeFileSplit(markSettings.Attribute("SplitMultiTracks"));
this.SkipNegligibleTones = XmlSupport.ReadBooleanAttribute(markSettings.Attribute("SkipNegligibleTones"));
}
}
}
| 33.622222 | 118 | 0.592862 | [
"MIT"
] | Vladimir1965/LargoComposer | LargoSharedClasses/Settings/SettingsImport.cs | 3,028 | C# |
namespace Altom.AltUnityDriver.Commands
{
public class AltUnityTapElement : AltUnityCommandReturningAltElement
{
private readonly AltUnityObject altUnityObject;
private readonly int count;
private readonly float interval;
private readonly bool wait;
public AltUnityTapElement(SocketSettings socketSettings, AltUnityObject altUnityObject, int count, float interval, bool wait) : base(socketSettings)
{
this.altUnityObject = altUnityObject;
this.count = count;
this.interval = interval;
this.wait = wait;
}
public AltUnityObject Execute()
{
var altObject = Newtonsoft.Json.JsonConvert.SerializeObject(altUnityObject);
SendCommand("tapElement", altObject, count.ToString(), interval.ToString(), wait.ToString());
var element = ReceiveAltUnityObject();
if (wait)
{
var data = this.Recvall();
ValidateResponse("Finished", data);
}
return element;
}
}
} | 35.53125 | 157 | 0.598945 | [
"MIT"
] | geodreamalpha/geodreamalpha | desktop/Unity/Assets/AltUnityTester/AltUnityDriver/Commands/ObjectCommands/AltUnityTapElement.cs | 1,137 | 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.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.DotNet.Docker.Tests
{
[Trait("Category", "runtime")]
public class RuntimeImageTests : CommonRuntimeImageTests
{
public RuntimeImageTests(ITestOutputHelper outputHelper)
: base(outputHelper)
{
}
protected override DotNetImageType ImageType => DotNetImageType.Runtime;
[DotNetTheory]
[MemberData(nameof(GetImageData))]
public async Task VerifyAppScenario(ProductImageData imageData)
{
// Skip test for Arm32 Alpine 3.13 due to https://github.com/dotnet/runtime/issues/47423
if (imageData.OS == "alpine3.13" && imageData.Arch == Arch.Arm)
{
return;
}
ImageScenarioVerifier verifier = new ImageScenarioVerifier(imageData, DockerHelper, OutputHelper);
await verifier.Execute();
}
[DotNetTheory]
[MemberData(nameof(GetImageData))]
public void VerifyEnvironmentVariables(ProductImageData imageData)
{
List<EnvironmentVariableInfo> variables = new List<EnvironmentVariableInfo>();
if (imageData.Version.Major >= 5 || (imageData.Version.Major == 2 && DockerHelper.IsLinuxContainerModeEnabled))
{
variables.Add(GetRuntimeVersionVariableInfo(imageData, DockerHelper));
}
base.VerifyCommonEnvironmentVariables(imageData, variables);
}
public static EnvironmentVariableInfo GetRuntimeVersionVariableInfo(ProductImageData imageData, DockerHelper dockerHelper)
{
string version = imageData.GetProductVersion(DotNetImageType.Runtime, dockerHelper);
return new EnvironmentVariableInfo("DOTNET_VERSION", version);
}
}
}
| 36.666667 | 130 | 0.672249 | [
"MIT"
] | CholoTook/dotnet-docker | tests/Microsoft.DotNet.Docker.Tests/RuntimeImageTests.cs | 2,092 | 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("PythonInterop")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PythonInterop")]
[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("68396bbe-5630-4f1f-970c-8f953602eb8a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.810811 | 84 | 0.745533 | [
"MPL-2.0"
] | CPardi/PythonLibs4CSharp | PythonLibs4CSharp/Properties/AssemblyInfo.cs | 1,402 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static System.Math;
using static GeographicLib.MathEx;
namespace GeographicLib
{
/// <summary>
/// An accumulator for sums.
/// </summary>
/// <remarks>
/// This allows many numbers of floating point type T to be added together with twice the normal precision.
/// Thus if T is double, the effective precision of the sum is 106 bits or about 32 decimal places.
/// <para>
/// The implementation follows J. R. Shewchuk,
/// <a href="https://doi.org/10.1007/PL00009321">Adaptive Precision Floating-Point Arithmetic and Fast Robust Geometric Predicates</a>,
/// Discrete & Computational Geometry 18(3) 305–363 (1997).
/// </para>
/// Approximate timings (summing a vector<double>)
/// <list type="bullet">
/// <item>double: 2ns</item>
/// <item>Accumulator<double>: 23ns</item>
/// </list>
/// In the documentation of the member functions, <i>sum</i> stands for the value currently held in the accumulator.
/// </remarks>
public struct Accumulator
{
private double _s, _t;
/// <summary>
/// Construct from a T. This is not declared explicit, so that you can write Accumulator a = 5;
/// </summary>
/// <param name="y">set <i>sum</i> = <i>y</i>.</param>
public Accumulator(double y = 0)
{
(_s, _t) = (y, 0);
}
/// <summary>
/// Add a number to the accumulator.
/// </summary>
/// <param name="acc"></param>
/// <param name="y"></param>
/// <returns></returns>
public static Accumulator operator +(Accumulator acc, double y)
{
acc.Add(y);
return acc;
}
/// <summary>
/// Subtract a number from the accumulator.
/// </summary>
/// <param name="acc"></param>
/// <param name="y"></param>
/// <returns></returns>
public static Accumulator operator -(Accumulator acc, double y)
{
acc.Add(-y);
return acc;
}
/// <summary>
/// Multiply accumulator by an integer.
/// To avoid loss of accuracy, use only integers such that <i>n</i> × <i>T</i> is exactly representable as a <i>T</i> (i.e., ± powers of two).
/// Use <i>n</i> = −1 to negate sum.
/// </summary>
/// <param name="acc"></param>
/// <param name="n">set <i>sum</i> *= <i>n</i>.</param>
/// <returns></returns>
public static Accumulator operator *(Accumulator acc, int n)
{
acc._s *= n;
acc._t *= n;
return acc;
}
/// <summary>
/// Multiply accumulator by a number.
/// The fma (fused multiply and add) instruction is used (if available) in order to maintain accuracy.
/// </summary>
/// <param name="acc"></param>
/// <param name="y">set <i>sum</i> *= <i>y</i>.</param>
/// <returns></returns>
public static Accumulator operator *(Accumulator acc, double y)
{
var d = acc._s; acc._s *= y;
d = FusedMultiplyAdd(y, d, -acc._s); // the error in the first multiplication
acc._t = FusedMultiplyAdd(y, acc._t, d); // add error to the second term
return acc;
}
/// <summary>
/// Return the value held in the accumulator.
/// </summary>
/// <param name="acc"></param>
public static implicit operator double(Accumulator acc) => acc._s;
/// <summary>
/// Set the accumulator to a number.
/// </summary>
/// <param name="y">set <i>sum</i> = <i>y</i>.</param>
public static implicit operator Accumulator(double y) => new Accumulator(y);
/// <summary>
/// Return the result of adding a number to sum (but don't change sum).
/// </summary>
/// <param name="y">the number to be added to the sum.</param>
/// <returns><i>sum</i> + <i>y</i>.</returns>
public double Sum(double y)
{
Accumulator a = this;
a.Add(y);
return a._s;
}
/// <summary>
/// Reduce accumulator to the range [-y/2, y/2].
/// </summary>
/// <param name="y">the modulus</param>
/// <returns></returns>
public void Remainder(double y)
{
_s = IEEERemainder(_s, y);
Add(0);
}
private void Add(double y)
{
// Here's Shewchuk's solution...
// hold exact sum as [s, t, u]
// Accumulate starting at least significant end
y = MathEx.Sum(y, _t, out var u);
_s = MathEx.Sum(y, _s, out _t);
// Start is _s, _t decreasing and non-adjacent. Sum is now (s + t + u)
// exactly with s, t, u non-adjacent and in decreasing order (except for
// possible zeros). The following code tries to normalize the result.
// Ideally, we want _s = round(s+t+u) and _u = round(s+t+u - _s). The
// following does an approximate job (and maintains the decreasing
// non-adjacent property). Here are two "failures" using 3-bit floats:
//
// Case 1: _s is not equal to round(s+t+u) -- off by 1 ulp
// [12, -1] - 8 -> [4, 0, -1] -> [4, -1] = 3 should be [3, 0] = 3
//
// Case 2: _s+_t is not as close to s+t+u as it shold be
// [64, 5] + 4 -> [64, 8, 1] -> [64, 8] = 72 (off by 1)
// should be [80, -7] = 73 (exact)
//
// "Fixing" these problems is probably not worth the expense. The
// representation inevitably leads to small errors in the accumulated
// values. The additional errors illustrated here amount to 1 ulp of the
// less significant word during each addition to the Accumulator and an
// additional possible error of 1 ulp in the reported sum.
//
// Incidentally, the "ideal" representation described above is not
// canonical, because _s = round(_s + _t) may not be true. For example,
// with 3-bit floats:
//
// [128, 16] + 1 -> [160, -16] -- 160 = round(145).
// But [160, 0] - 16 -> [128, 16] -- 128 = round(144).
//
if (_s == 0) // This implies t == 0,
_s = u; // so result is u
else
_t += u; // otherwise just accumulate u to t.
}
}
}
| 38.418079 | 150 | 0.521029 | [
"MIT"
] | noelex/GeographicLib.NET | GeographicLib/Accumulator.cs | 6,808 | C# |
using System;
using System.Buffers;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading.Tasks;
using Xunit;
using static System.Globalization.CultureInfo;
namespace DotNext.IO
{
using Buffers;
[ExcludeFromCodeCoverage]
public sealed class TextStreamTests : Test
{
[Fact]
public static void WriteText()
{
using var writer = new PooledArrayBufferWriter<char>();
using var actual = writer.AsTextWriter();
using TextWriter expected = new StringWriter(InvariantCulture);
actual.Write("Hello, world!");
expected.Write("Hello, world!");
actual.Write("123".AsSpan());
expected.Write("123".AsSpan());
actual.Write(TimeSpan.Zero);
expected.Write(TimeSpan.Zero);
actual.Write(true);
expected.Write(true);
actual.Write('a');
expected.Write('a');
actual.Write(20);
expected.Write(20);
actual.Write(20U);
expected.Write(20U);
actual.Write(42L);
expected.Write(42L);
actual.Write(46UL);
expected.Write(46UL);
actual.Write(89M);
expected.Write(89M);
actual.Write(78.8F);
expected.Write(78.8F);
actual.Write(90.9D);
expected.Write(90.9D);
actual.WriteLine();
expected.WriteLine();
actual.Flush();
Equal(expected.ToString(), writer.ToString());
Equal(expected.ToString(), actual.ToString());
}
[Fact]
public static async Task WriteTextAsync()
{
var writer = new ArrayBufferWriter<char>();
using var actual = writer.AsTextWriter();
using TextWriter expected = new StringWriter(InvariantCulture);
await actual.WriteAsync("Hello, world!");
await expected.WriteAsync("Hello, world!");
await actual.WriteAsync("123".AsMemory());
await expected.WriteAsync("123".AsMemory());
await actual.WriteAsync('a');
await expected.WriteAsync('a');
await actual.WriteLineAsync();
await expected.WriteLineAsync();
await actual.FlushAsync();
Equal(expected.ToString(), writer.BuildString());
Equal(expected.ToString(), actual.ToString());
}
[Fact]
public static async Task WriteSequence()
{
var sequence = new [] { "abc".AsMemory(), "def".AsMemory(), "g".AsMemory() }.ToReadOnlySequence();
await using var writer = new StringWriter();
await writer.WriteAsync(sequence);
Equal("abcdefg", writer.ToString());
}
}
} | 28.098039 | 110 | 0.554431 | [
"MIT"
] | human33/dotNext | src/DotNext.Tests/IO/TextStreamTests.cs | 2,866 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
public class BoardManager : MonoBehaviour {
public int difficulty = 0;
public int columns = 6;
public int rows = 6;
public GameObject door;
public GameObject table;
public GameObject trash;
public GameObject pet;
public GameObject wallTile;
public GameObject[] floorTiles;
public LayerMask blockingLayer;
private float doggoFreq;
private Transform boardHolder;
private List<Vector3> gridPositions = new List<Vector3> ();
// Creates list of all possible locations on the board
void InitializeList () {
gridPositions.Clear ();
for (int x = 1; x < columns - 1; x++) {
for (int y = 1; y < rows - 1; y++) {
gridPositions.Add (new Vector3 (x, y, 0f));
}
}
}
// Places a game object tile at each location on the board
void BoardSetup () {
boardHolder = new GameObject ("Board").transform;
for (int x = -1; x < columns + 1; x++) {
for (int y = -1; y < rows + 1; y++) {
GameObject toInstantiate = floorTiles [Random.Range (0, floorTiles.Length)];
// places a wall tile if the location is an edge location
if (x == -1 || x == columns || y == -1 || y == rows)
toInstantiate = wallTile;
GameObject instance = Instantiate (toInstantiate, new Vector3 (x, y, 0f), Quaternion.identity) as GameObject;
instance.transform.SetParent (boardHolder);
}
}
}
//the only public method - what the gameManager calls
public void SetupScene () {
BoardSetup ();
InitializeList ();
Instantiate (door, new Vector3 (columns - 1, rows - 1, 0f), Quaternion.identity);
Instantiate (table, new Vector3 (0, rows - 1, 0f), Quaternion.identity);
Instantiate (trash, new Vector3 (columns - 1, 0, 0f), Quaternion.identity);
switch (difficulty) {
case 0:
doggoFreq = 20f;
break;
case 1:
doggoFreq = 10f;
break;
case 2:
doggoFreq = 5f;
break;
default:
doggoFreq = 60f;
break;
}
InvokeRepeating ("DoggoSpawner", 0.0f, doggoFreq);
}
private void DoggoSpawner() {
StartCoroutine(CreateDoggo());
}
IEnumerator CreateDoggo() {
// calculation to check whether spawn location is empty of not
Vector3 start = new Vector3((float)columns - 1, (float)rows - 1, 0);
Vector3 end = new Vector3((float)(columns - 2), (float)rows - 1, 0);
BoxCollider2D doorCollider = GameObject.Find("Door(Clone)").GetComponent<BoxCollider2D>();
doorCollider.enabled = false;
RaycastHit2D hit = Physics2D.Linecast(start, end, blockingLayer);
doorCollider.enabled = true;
// if not empty, yield until it is
if (hit.transform != null)
yield return null;
else
Instantiate (pet, end, Quaternion.identity);
}
public int GetColumns() {
return this.columns;
}
public int GetRows() {
return this.rows;
}
public void SetDifficulty(int level) {
difficulty = level;
}
} | 28.299065 | 113 | 0.650925 | [
"MIT"
] | budmonde/doggo | Assets/Scripts/BoardManager.cs | 3,030 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace PostComment.Core.SharedKernel
{
public abstract class BaseEntity
{
public virtual int Id { get; set; }
}
}
| 17.166667 | 43 | 0.699029 | [
"MIT"
] | rodrigostrj/PostCommentService | src/PostComment/PostComment.Core/SharedKernel/BaseEntity.cs | 208 | C# |
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Memberships.Models.Core
{
[Table("ItemType")]
public class ItemType
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[MaxLength(255)]
[Required]
public string Title { get; set; }
}
} | 23.9375 | 61 | 0.668407 | [
"MIT"
] | jessepatricio/Memberships | Memberships/Models/Core/ItemType.cs | 385 | C# |
// Generated on 12/11/2014 19:01:40
using System;
using System.Collections.Generic;
using System.Linq;
using BlueSheep.Common.Protocol.Types;
using BlueSheep.Common.IO;
using BlueSheep.Engine.Types;
namespace BlueSheep.Common.Protocol.Messages
{
public class QuestListMessage : Message
{
public new const uint ID =5626;
public override uint ProtocolID
{
get { return ID; }
}
public short[] finishedQuestsIds;
public short[] finishedQuestsCounts;
public Types.QuestActiveInformations[] activeQuests;
public QuestListMessage()
{
}
public QuestListMessage(short[] finishedQuestsIds, short[] finishedQuestsCounts, Types.QuestActiveInformations[] activeQuests)
{
this.finishedQuestsIds = finishedQuestsIds;
this.finishedQuestsCounts = finishedQuestsCounts;
this.activeQuests = activeQuests;
}
public override void Serialize(BigEndianWriter writer)
{
writer.WriteUShort((ushort)finishedQuestsIds.Length);
foreach (var entry in finishedQuestsIds)
{
writer.WriteVarShort(entry);
}
writer.WriteUShort((ushort)finishedQuestsCounts.Length);
foreach (var entry in finishedQuestsCounts)
{
writer.WriteVarShort(entry);
}
writer.WriteUShort((ushort)activeQuests.Length);
foreach (var entry in activeQuests)
{
writer.WriteShort(entry.TypeId);
entry.Serialize(writer);
}
}
public override void Deserialize(BigEndianReader reader)
{
var limit = reader.ReadUShort();
finishedQuestsIds = new short[limit];
for (int i = 0; i < limit; i++)
{
finishedQuestsIds[i] = reader.ReadVarShort();
}
limit = reader.ReadUShort();
finishedQuestsCounts = new short[limit];
for (int i = 0; i < limit; i++)
{
finishedQuestsCounts[i] = reader.ReadVarShort();
}
limit = reader.ReadUShort();
activeQuests = new Types.QuestActiveInformations[limit];
for (int i = 0; i < limit; i++)
{
activeQuests[i] = Types.ProtocolTypeManager.GetInstance<Types.QuestActiveInformations>(reader.ReadShort());
activeQuests[i].Deserialize(reader);
}
}
}
} | 29.629213 | 134 | 0.565036 | [
"MIT"
] | Sadikk/BlueSheep | BlueSheep/Common/Protocol/messages/game/context/roleplay/quest/QuestListMessage.cs | 2,637 | C# |
// AnimatorTriggerAction
using HutongGames.PlayMaker;
using UnityEngine;
[ActionCategory("Animation")]
public class AnimatorTriggerAction : FsmStateAction
{
public bool UseOwnerGameObject = false;
public FsmGameObject Target;
public FsmString Parameter;
private Animator anim;
private void InitializeComponents()
{
if (anim == null)
{
if (UseOwnerGameObject)
{
anim = base.Owner.GetComponentInParent<Animator>();
}
else if (Target.Value != null)
{
anim = Target.Value.GetComponent<Animator>();
}
}
}
public override void OnEnter()
{
InitializeComponents();
if (anim != null)
{
anim.SetTrigger(Parameter.Value);
}
Finish();
}
}
| 16.780488 | 55 | 0.696221 | [
"MIT"
] | smdx24/CPI-Source-Code | ClubPenguin.Adventure/AnimatorTriggerAction.cs | 688 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
namespace MyAlbum.Converters
{
public class ViewTypeToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return (ViewType)value == (ViewType)parameter;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return new NotImplementedException();
}
}
}
| 26.869565 | 100 | 0.66343 | [
"MIT"
] | Avi-Meshulam/MyAlbum | MyAlbum/Converters/ViewTypeToBoolConverter.cs | 620 | C# |
// Copyright 2019 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Monitoring.V3.Tests
{
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using apis = Google.Cloud.Monitoring.V3;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Moq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
/// <summary>Generated unit tests</summary>
public class GeneratedUptimeCheckServiceClientTest
{
[Fact]
public void GetUptimeCheckConfig()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
GetUptimeCheckConfigRequest expectedRequest = new GetUptimeCheckConfigRequest
{
Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.GetUptimeCheckConfig(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
string formattedName = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString();
UptimeCheckConfig response = client.GetUptimeCheckConfig(formattedName);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetUptimeCheckConfigAsync()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
GetUptimeCheckConfigRequest expectedRequest = new GetUptimeCheckConfigRequest
{
Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.GetUptimeCheckConfigAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<UptimeCheckConfig>(Task.FromResult(expectedResponse), null, null, null, null));
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
string formattedName = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString();
UptimeCheckConfig response = await client.GetUptimeCheckConfigAsync(formattedName);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void GetUptimeCheckConfig2()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
GetUptimeCheckConfigRequest request = new GetUptimeCheckConfigRequest
{
Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.GetUptimeCheckConfig(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
UptimeCheckConfig response = client.GetUptimeCheckConfig(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetUptimeCheckConfigAsync2()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
GetUptimeCheckConfigRequest request = new GetUptimeCheckConfigRequest
{
Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.GetUptimeCheckConfigAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<UptimeCheckConfig>(Task.FromResult(expectedResponse), null, null, null, null));
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
UptimeCheckConfig response = await client.GetUptimeCheckConfigAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void CreateUptimeCheckConfig()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
CreateUptimeCheckConfigRequest expectedRequest = new CreateUptimeCheckConfigRequest
{
Parent = new ProjectName("[PROJECT]").ToString(),
UptimeCheckConfig = new UptimeCheckConfig(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name3373707",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.CreateUptimeCheckConfig(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
string formattedParent = new ProjectName("[PROJECT]").ToString();
UptimeCheckConfig uptimeCheckConfig = new UptimeCheckConfig();
UptimeCheckConfig response = client.CreateUptimeCheckConfig(formattedParent, uptimeCheckConfig);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task CreateUptimeCheckConfigAsync()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
CreateUptimeCheckConfigRequest expectedRequest = new CreateUptimeCheckConfigRequest
{
Parent = new ProjectName("[PROJECT]").ToString(),
UptimeCheckConfig = new UptimeCheckConfig(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name3373707",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.CreateUptimeCheckConfigAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<UptimeCheckConfig>(Task.FromResult(expectedResponse), null, null, null, null));
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
string formattedParent = new ProjectName("[PROJECT]").ToString();
UptimeCheckConfig uptimeCheckConfig = new UptimeCheckConfig();
UptimeCheckConfig response = await client.CreateUptimeCheckConfigAsync(formattedParent, uptimeCheckConfig);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void CreateUptimeCheckConfig2()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
CreateUptimeCheckConfigRequest request = new CreateUptimeCheckConfigRequest
{
Parent = new ProjectName("[PROJECT]").ToString(),
UptimeCheckConfig = new UptimeCheckConfig(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name3373707",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.CreateUptimeCheckConfig(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
UptimeCheckConfig response = client.CreateUptimeCheckConfig(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task CreateUptimeCheckConfigAsync2()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
CreateUptimeCheckConfigRequest request = new CreateUptimeCheckConfigRequest
{
Parent = new ProjectName("[PROJECT]").ToString(),
UptimeCheckConfig = new UptimeCheckConfig(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name3373707",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.CreateUptimeCheckConfigAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<UptimeCheckConfig>(Task.FromResult(expectedResponse), null, null, null, null));
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
UptimeCheckConfig response = await client.CreateUptimeCheckConfigAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void UpdateUptimeCheckConfig()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
UpdateUptimeCheckConfigRequest expectedRequest = new UpdateUptimeCheckConfigRequest
{
UptimeCheckConfig = new UptimeCheckConfig(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name3373707",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.UpdateUptimeCheckConfig(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
UptimeCheckConfig uptimeCheckConfig = new UptimeCheckConfig();
UptimeCheckConfig response = client.UpdateUptimeCheckConfig(uptimeCheckConfig);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task UpdateUptimeCheckConfigAsync()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
UpdateUptimeCheckConfigRequest expectedRequest = new UpdateUptimeCheckConfigRequest
{
UptimeCheckConfig = new UptimeCheckConfig(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name3373707",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.UpdateUptimeCheckConfigAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<UptimeCheckConfig>(Task.FromResult(expectedResponse), null, null, null, null));
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
UptimeCheckConfig uptimeCheckConfig = new UptimeCheckConfig();
UptimeCheckConfig response = await client.UpdateUptimeCheckConfigAsync(uptimeCheckConfig);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void UpdateUptimeCheckConfig2()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
UpdateUptimeCheckConfigRequest request = new UpdateUptimeCheckConfigRequest
{
UptimeCheckConfig = new UptimeCheckConfig(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name3373707",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.UpdateUptimeCheckConfig(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
UptimeCheckConfig response = client.UpdateUptimeCheckConfig(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task UpdateUptimeCheckConfigAsync2()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
UpdateUptimeCheckConfigRequest request = new UpdateUptimeCheckConfigRequest
{
UptimeCheckConfig = new UptimeCheckConfig(),
};
UptimeCheckConfig expectedResponse = new UptimeCheckConfig
{
Name = "name3373707",
DisplayName = "displayName1615086568",
IsInternal = true,
};
mockGrpcClient.Setup(x => x.UpdateUptimeCheckConfigAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<UptimeCheckConfig>(Task.FromResult(expectedResponse), null, null, null, null));
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
UptimeCheckConfig response = await client.UpdateUptimeCheckConfigAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteUptimeCheckConfig()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
DeleteUptimeCheckConfigRequest expectedRequest = new DeleteUptimeCheckConfigRequest
{
Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteUptimeCheckConfig(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
string formattedName = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString();
client.DeleteUptimeCheckConfig(formattedName);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteUptimeCheckConfigAsync()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
DeleteUptimeCheckConfigRequest expectedRequest = new DeleteUptimeCheckConfigRequest
{
Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteUptimeCheckConfigAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
string formattedName = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString();
await client.DeleteUptimeCheckConfigAsync(formattedName);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteUptimeCheckConfig2()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
DeleteUptimeCheckConfigRequest request = new DeleteUptimeCheckConfigRequest
{
Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteUptimeCheckConfig(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteUptimeCheckConfig(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteUptimeCheckConfigAsync2()
{
Mock<UptimeCheckService.UptimeCheckServiceClient> mockGrpcClient = new Mock<UptimeCheckService.UptimeCheckServiceClient>(MockBehavior.Strict);
DeleteUptimeCheckConfigRequest request = new DeleteUptimeCheckConfigRequest
{
Name = new UptimeCheckConfigName("[PROJECT]", "[UPTIME_CHECK_CONFIG]").ToString(),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteUptimeCheckConfigAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
UptimeCheckServiceClient client = new UptimeCheckServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteUptimeCheckConfigAsync(request);
mockGrpcClient.VerifyAll();
}
}
}
| 52.173684 | 154 | 0.65863 | [
"Apache-2.0"
] | alexdoan102/google-cloud-dotnet | apis/Google.Cloud.Monitoring.V3/Google.Cloud.Monitoring.V3.Tests/UptimeCheckServiceClientTest.g.cs | 19,826 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Orchard.ContentManagement;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.ContentManagement.MetaData.Models;
using Orchard.ContentManagement.ViewModels;
using Orchard.Localization;
using Orchard.UI.Notify;
using Orchard.Localization.Services;
namespace Orchard.Autoroute.Settings {
public class AutorouteSettingsHooks : ContentDefinitionEditorEventsBase {
private readonly INotifier _notifier;
private readonly ICultureManager _cultureManager;
public AutorouteSettingsHooks(INotifier notifier, ICultureManager cultureManager) {
_notifier = notifier;
_cultureManager = cultureManager;
}
public Localizer T { get; set; }
public override IEnumerable<TemplateViewModel> TypePartEditor(ContentTypePartDefinition definition) {
if (definition.PartDefinition.Name != "AutoroutePart")
yield break;
var settings = definition.Settings.GetModel<AutorouteSettings>();
// Get cultures
settings.SiteCultures = _cultureManager.ListCultures().ToList();
// Get default site culture
settings.DefaultSiteCulture = _cultureManager.GetSiteCulture();
// Adding Patterns for the UI
List<RoutePattern> newPatterns = new List<RoutePattern>();
// Adding a null culture for the culture neutral pattern
var cultures = new List<string>();
cultures.Add(null);
cultures.AddRange(settings.SiteCultures);
foreach (string culture in cultures) {
// Adding all existing patterns for the culture
newPatterns.AddRange(
settings.Patterns.Where(x => String.Equals(x.Culture, culture, StringComparison.OrdinalIgnoreCase))
);
// Adding a pattern for each culture if there is none
if (!settings.Patterns.Where(x => String.Equals(x.Culture, culture, StringComparison.OrdinalIgnoreCase)).Any()) {
newPatterns.Add(new RoutePattern { Culture = culture, Name = "Title", Description = "my-title", Pattern = "{Content.Slug}" });
}
// Adding a new empty line for each culture
newPatterns.Add(new RoutePattern { Culture = culture, Name = null, Description = null, Pattern = null });
// If the content type has no defaultPattern for autoroute, assign one
var defaultPatternExists = false;
if (String.IsNullOrEmpty(culture))
defaultPatternExists = settings.DefaultPatterns.Any(x => String.IsNullOrEmpty(x.Culture));
else
defaultPatternExists = settings.DefaultPatterns.Any(x => String.Equals(x.Culture, culture, StringComparison.OrdinalIgnoreCase));
if (!defaultPatternExists) {
// If in the default culture check the old setting
if (String.Equals(culture, _cultureManager.GetSiteCulture(), StringComparison.OrdinalIgnoreCase)) {
var defaultPatternIndex = settings.DefaultPatternIndex;
if (!String.IsNullOrWhiteSpace(defaultPatternIndex)) {
var patternIndex = defaultPatternIndex;
settings.DefaultPatterns.Add(new DefaultPattern { Culture = settings.DefaultSiteCulture, PatternIndex = patternIndex });
}
else {
settings.DefaultPatterns.Add(new DefaultPattern { PatternIndex = "0", Culture = culture });
}
}
else {
settings.DefaultPatterns.Add(new DefaultPattern { PatternIndex = "0", Culture = culture });
}
}
}
settings.Patterns = newPatterns;
yield return DefinitionTemplate(settings);
}
public override IEnumerable<TemplateViewModel> TypePartEditorUpdate(ContentTypePartDefinitionBuilder builder, IUpdateModel updateModel) {
if (builder.Name != "AutoroutePart")
yield break;
var settings = new AutorouteSettings {
Patterns = new List<RoutePattern>()
};
// Get cultures
settings.SiteCultures = _cultureManager.ListCultures().ToList();
if (updateModel.TryUpdateModel(settings, "AutorouteSettings", null, null)) {
//TODO need to add validations client and/or server side here
// If some default pattern is an empty pattern set it to the first pattern for the language
var newDefaultPatterns = new List<DefaultPattern>();
foreach (var defaultPattern in settings.DefaultPatterns) {
RoutePattern correspondingPattern = null;
if (string.IsNullOrEmpty(defaultPattern.Culture))
correspondingPattern = settings.Patterns.Where(x => String.IsNullOrEmpty(x.Culture)).ElementAt(Convert.ToInt32(defaultPattern.PatternIndex));
else
correspondingPattern = settings.Patterns.Where(x => String.Equals(x.Culture, defaultPattern.Culture, StringComparison.OrdinalIgnoreCase)).ElementAt(Convert.ToInt32(defaultPattern.PatternIndex));
if (String.IsNullOrWhiteSpace(correspondingPattern.Name) && String.IsNullOrWhiteSpace(correspondingPattern.Pattern) && String.IsNullOrWhiteSpace(correspondingPattern.Description))
newDefaultPatterns.Add(new DefaultPattern { Culture = defaultPattern.Culture, PatternIndex = "0" });
else
newDefaultPatterns.Add(defaultPattern);
}
settings.DefaultPatterns = newDefaultPatterns;
// Remove empty patterns
var patterns = settings.Patterns;
patterns.RemoveAll(p => String.IsNullOrWhiteSpace(p.Name) && String.IsNullOrWhiteSpace(p.Pattern) && String.IsNullOrWhiteSpace(p.Description));
// Adding a null culture for the culture neutral pattern
var cultures = new List<string>();
cultures.Add(null);
cultures.AddRange(settings.SiteCultures);
//If there is no pattern for some culture create a default one
List<RoutePattern> newPatterns = new List<RoutePattern>();
int current = 0;
foreach (string culture in cultures) {
if (settings.Patterns.Any(x => String.Equals(x.Culture, culture, StringComparison.OrdinalIgnoreCase))) {
foreach (RoutePattern routePattern in settings.Patterns.Where(x => String.Equals(x.Culture, culture, StringComparison.OrdinalIgnoreCase))) {
newPatterns.Add(settings.Patterns[current]);
current++;
}
}
else {
newPatterns.Add(new RoutePattern {
Name = "Title",
Description = "my-title",
Pattern = "{Content.Slug}",
Culture = culture
});
_notifier.Warning(T("A default pattern has been added to AutoroutePart"));
}
}
settings.Patterns = newPatterns;
// Update the settings builder
settings.Build(builder);
}
yield return DefinitionTemplate(settings);
}
}
}
| 48.648148 | 218 | 0.595863 | [
"BSD-3-Clause"
] | 1996dylanriley/Orchard | src/Orchard.Web/Modules/Orchard.Autoroute/Settings/AutorouteSettingsEvents.cs | 7,883 | C# |
//Copyright (C) 2006 Richard J. Northedge
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the AbstractResolver.java source file found in the
//original java implementation of OpenNLP. That source file contains the following header:
//Copyright (C) 2003 Thomas Morton
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
using System;
namespace Voxell.NLP.Coreference.Resolver
{
/// <summary>
/// Default implementation of some methods in the {@link IResolver} interface.
/// </summary>
public abstract class AbstractResolver : IResolver
{
/// <summary>
/// The number of previous entities that resolver should consider.
/// </summary>
private int mNumberEntitiesBack;
/// <summary>
/// Debugging variable which specifies whether error output is generated if a class excludes as possibly coreferent mentions which are in-fact coreferent.
/// </summary>
private bool mShowExclusions;
/// <summary>
/// Debugging variable which holds statistics about mention distances durring training.
/// </summary>
private Util.CountedSet<int> mDistances;
/// <summary>
/// The number of sentences back this resolver should look for a referent.
/// </summary>
private int mNumberSentencesBack;
/// <summary>
/// The number of sentences back this resolver should look for a referent.
/// </summary>
protected internal virtual int NumberSentencesBack
{
get
{
return mNumberSentencesBack;
}
set
{
mNumberSentencesBack = value;
}
}
/// <summary>
/// Debugging variable which holds statistics about mention distances durring training.
/// </summary>
protected internal virtual bool ShowExclusions
{
get
{
return mShowExclusions;
}
set
{
mShowExclusions = value;
}
}
/// <summary>
/// Debugging variable which holds statistics about mention distances durring training.
/// </summary>
protected internal virtual Util.CountedSet<int> Distances
{
get
{
return mDistances;
}
set
{
mDistances = value;
}
}
protected AbstractResolver(int numberEntitiesBack)
{
mNumberEntitiesBack = numberEntitiesBack;
mShowExclusions = true;
mDistances = new Util.CountedSet<int>();
}
/// <summary>
/// Returns the number of previous entities that resolver should consider.
/// </summary>
/// <returns>
/// the number of previous entities that resolver should consider.
/// </returns>
protected internal virtual int GetNumberEntitiesBack()
{
return mNumberEntitiesBack;
}
/// <summary>
/// The number of entites that should be considered for resolution with the specified discourse model.
/// </summary>
/// <param name="discourseModel">
/// The discourse model.
/// </param>
/// <returns>
/// number of entites that should be considered for resolution.
/// </returns>
protected internal virtual int GetNumberEntitiesBack(DiscourseModel discourseModel)
{
return System.Math.Min(discourseModel.EntityCount, mNumberEntitiesBack);
}
/// <summary>
/// Returns the head parse for the specified mention.
/// </summary>
/// <param name="mention">
/// The mention.
/// </param>
/// <returns>
/// the head parse for the specified mention.
/// </returns>
protected internal virtual Mention.IParse GetHead(Mention.MentionContext mention)
{
return mention.HeadTokenParse;
}
/// <summary>
/// Returns the index for the head word for the specified mention.
/// </summary>
/// <param name="mention">
/// The mention.
/// </param>
/// <returns>
/// the index for the head word for the specified mention.
/// </returns>
protected internal virtual int GetHeadIndex(Mention.MentionContext mention)
{
Mention.IParse[] mentionTokens = mention.TokenParses;
for (int currentToken = mentionTokens.Length - 1; currentToken >= 0; currentToken--)
{
Mention.IParse token = mentionTokens[currentToken];
if (token.SyntacticType != "POS" && token.SyntacticType != "," && token.SyntacticType != ".")
{
return currentToken;
}
}
return mentionTokens.Length - 1;
}
/// <summary>
/// Returns the text of the head word for the specified mention.
/// </summary>
/// <param name="mention">
/// The mention.
/// </param>
/// <returns>
/// The text of the head word for the specified mention.
/// </returns>
protected internal virtual string GetHeadString(Mention.MentionContext mention)
{
return mention.HeadTokenText.ToLower();
}
/// <summary>
/// Determines if the specified entity is too far from the specified mention to be resolved to it.
/// Once an entity has been determined to be out of range subsequent entities are not considered.
/// </summary>
/// <seealso cref="IsExcluded">
/// </seealso>
/// <param name="mention">
/// The mention which is being considered.
/// </param>
/// <param name="entity">
/// The entity to which the mention is to be resolved.
/// </param>
/// <returns>
/// true is the entity is in range of the mention, false otherwise.
/// </returns>
protected internal virtual bool IsOutOfRange(Mention.MentionContext mention, DiscourseEntity entity)
{
return false;
}
/// <summary>
/// Excludes entities which you are not compatible with the entity under consideration. The default
/// implementation excludes entties whose last extent contains the extent under consideration.
/// This prevents posessive pronouns from referring to the noun phrases they modify and other
/// undesirable things.
/// </summary>
/// <param name="mention">
/// The mention which is being considered as referential.
/// </param>
/// <param name="entity">
/// The entity to which the mention is to be resolved.
/// </param>
/// <returns>
/// true if the entity should be excluded, false otherwise.
/// </returns>
protected internal virtual bool IsExcluded(Mention.MentionContext mention, DiscourseEntity entity)
{
Mention.MentionContext context = entity.LastExtent;
return mention.SentenceNumber == context.SentenceNumber && mention.IndexSpan.End <= context.IndexSpan.End;
}
public virtual DiscourseEntity Retain(Mention.MentionContext mention, DiscourseModel discourseModel)
{
int entityIndex = 0;
if (mention.Id == - 1)
{
return null;
}
for (; entityIndex < discourseModel.EntityCount; entityIndex++)
{
DiscourseEntity currentDiscourseEntity = discourseModel.GetEntity(entityIndex);
Mention.MentionContext candidateExtentContext = currentDiscourseEntity.LastExtent;
if (candidateExtentContext.Id == mention.Id)
{
Distances.Add(entityIndex);
return currentDiscourseEntity;
}
}
//System.err.println("AbstractResolver.Retain: non-referring entity with id: "+ec.toText()+" id="+ec.id);
return null;
}
/// <summary>
/// Returns the string of "_" delimited tokens for the specified mention.
/// </summary>
/// <param name="mention">
/// The mention.
/// </param>
/// <returns>
/// the string of "_" delimited tokens for the specified mention.
/// </returns>
protected internal virtual string GetFeatureString(Mention.MentionContext mention)
{
System.Text.StringBuilder output = new System.Text.StringBuilder();
object[] mentionTokens = mention.Tokens;
output.Append(mentionTokens[0].ToString());
for (int currentToken = 1; currentToken < mentionTokens.Length; currentToken++)
{
output.Append("_").Append(mentionTokens[currentToken].ToString());
}
return output.ToString();
}
/// <summary>
/// Returns a string for the specified mention with punctuation, honorifics, designators, and determiners removed.
/// </summary>
/// <param name="mention">
/// The mention to be stripped.
/// </param>
/// <returns>
/// a normalized string representation of the specified mention.
/// </returns>
protected internal virtual string StripNounPhrase(Mention.MentionContext mention)
{
int start = mention.NonDescriptorStart; //start after descriptors
Mention.IParse[] mentionTokens = mention.TokenParses;
int end = mention.HeadTokenIndex + 1;
if (start == end)
{
//System.err.println("StripNounPhrase: return null 1");
return null;
}
//strip determiners
if (mentionTokens[start].SyntacticType == "DT")
{
start++;
}
if (start == end)
{
//System.err.println("StripNounPhrase: return null 2");
return null;
}
//get to first NNP
string type;
for (int index = start; index < end; index++)
{
type = mentionTokens[start].SyntacticType;
if (type.StartsWith("NNP"))
{
break;
}
start++;
}
if (start == end)
{
//System.err.println("StripNounPhrase: return null 3");
return null;
}
if (start + 1 != end)
{
// don't do this on head words, to keep "U.S."
//strip off honorifics in begining
if (Linker.HonorificsPattern.IsMatch(mentionTokens[start].ToString()))
{
start++;
}
if (start == end)
{
//System.err.println("StripNounPhrase: return null 4");
return null;
}
//strip off and honorifics on the end
if (Linker.DesignatorsPattern.IsMatch(mentionTokens[mentionTokens.Length - 1].ToString()))
{
end--;
}
}
if (start == end)
{
//System.err.println("StripNounPhrase: return null 5");
return null;
}
System.Text.StringBuilder strip = new System.Text.StringBuilder();
for (int i = start; i < end; i++)
{
strip.Append(mentionTokens[i].ToString()).Append(" ");
}
return strip.ToString().Trim();
}
public virtual void Train()
{
}
/// <summary>
/// Returns a string representing the gender of the specifed pronoun.
/// </summary>
/// <param name="pronoun">
/// An English pronoun.
/// </param>
/// <returns>
/// the gender of the specifed pronoun.
/// </returns>
public static string GetPronounGender(string pronoun)
{
//java uses "Matcher.matches" to check if the whole string matches the pattern
if (Linker.MalePronounPattern.IsMatch(pronoun))
{
return "m";
}
else if (Linker.FemalePronounPattern.IsMatch(pronoun))
{
return "f";
}
else if (Linker.NeuterPronounPattern.IsMatch(pronoun))
{
return "n";
}
else
{
return "u";
}
}
public abstract bool CanResolve(Mention.MentionContext mention);
public abstract DiscourseEntity Resolve(Mention.MentionContext expression, DiscourseModel discourseModel);
}
} | 34.511568 | 162 | 0.605512 | [
"Apache-2.0"
] | studentutu/UnityNLP | Runtime/VoxellNLP/Coreference/Resolver/AbstractResolver.cs | 13,425 | C# |
#pragma checksum "H:\Client\SimplCommerce\src\Modules\SimplCommerce.Module.PaymentCashfree\Areas\PaymentCashfree\Views\_ViewStart.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "7091c65830b0329e613be026ede8a57552863778"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Areas_PaymentCashfree_Views__ViewStart), @"mvc.1.0.view", @"/Areas/PaymentCashfree/Views/_ViewStart.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "H:\Client\SimplCommerce\src\Modules\SimplCommerce.Module.PaymentCashfree\Areas\PaymentCashfree\Views\_ViewImports.cshtml"
using Microsoft.AspNetCore.Identity;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "H:\Client\SimplCommerce\src\Modules\SimplCommerce.Module.PaymentCashfree\Areas\PaymentCashfree\Views\_ViewImports.cshtml"
using Microsoft.AspNetCore.Mvc.Localization;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"7091c65830b0329e613be026ede8a57552863778", @"/Areas/PaymentCashfree/Views/_ViewStart.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"252a5853f5646565b6d19f2f67b215e8a2ab4af3", @"/Areas/PaymentCashfree/Views/_ViewImports.cshtml")]
public class Areas_PaymentCashfree_Views__ViewStart : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 1 "H:\Client\SimplCommerce\src\Modules\SimplCommerce.Module.PaymentCashfree\Areas\PaymentCashfree\Views\_ViewStart.cshtml"
Layout = "_Layout";
#line default
#line hidden
#nullable disable
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public IViewLocalizer Localizer { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 52.721311 | 221 | 0.782649 | [
"Apache-2.0"
] | sujatabpawar/ecommerci_api | src/Modules/SimplCommerce.Module.PaymentCashfree/obj/Debug/net5.0/Razor/Areas/PaymentCashfree/Views/_ViewStart.cshtml.g.cs | 3,216 | C# |
/**
* Copyright 2013 Canada Health Infoway, 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.
*
* Author: $LastChangedBy: gng $
* Last modified: $LastChangedDate: 2015-11-19 18:20:12 -0500 (Fri, 30 Jan 2015) $
* Revision: $LastChangedRevision: 9755 $
*/
using System.Collections.Generic;
using Ca.Infoway.Messagebuilder.Datatype;
namespace Ca.Infoway.Messagebuilder.Datatype
{
/// <summary>HL7 datatype SET.</summary>
/// <remarks>
/// HL7 datatype SET. Backed by a java Set.
/// Used when multiple repetitions are allowed, order is irrelevant and duplicates are prohibited.
/// </remarks>
/// <author>Intelliware Development</author>
/// <TBD></TBD>
/// <TBD></TBD>
public interface SET<T, V> : COLLECTION<T> where T : ANY<V>
{
/// <summary>Returns the underlying Java Set containing values in the underlying Java datatype.</summary>
/// <remarks>Returns the underlying Java Set containing values in the underlying Java datatype.</remarks>
/// <returns>the underlying Java Set containing values in the underlying Java datatype</returns>
ICollection<V> RawSet();
ICollection<U> RawSet<U>() where U : V;
}
}
| 38 | 108 | 0.698246 | [
"ECL-2.0",
"Apache-2.0"
] | CanadaHealthInfoway/message-builder-dotnet | message-builder-core/Main/Ca/Infoway/Messagebuilder/Datatype/SET.cs | 1,710 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.CommandLine.Invocation;
using System.CommandLine.Parsing;
using System.IO;
using FluentAssertions;
using System.Linq;
using Xunit;
using Xunit.Abstractions;
namespace System.CommandLine.Tests
{
public class ParsingValidationTests
{
private readonly ITestOutputHelper _output;
public ParsingValidationTests(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void When_an_option_accepts_only_specific_arguments_but_a_wrong_one_is_supplied_then_an_informative_error_is_returned()
{
var parser = new Parser(
new Option("-x")
{
Argument = new Argument
{
Arity = ArgumentArity.ExactlyOne
}
.FromAmong("this", "that", "the-other-thing")
});
var result = parser.Parse("-x none-of-those");
result.Errors
.Select(e => e.Message)
.Single()
.Should()
.Contain("Argument 'none-of-those' not recognized. Must be one of:\n\t'this'\n\t'that'\n\t'the-other-thing'");
}
[Fact]
public void When_an_option_has_en_error_then_the_error_has_a_reference_to_the_option()
{
var option = new Option("-x")
{
Argument = new Argument
{
Arity = ArgumentArity.ExactlyOne
}.FromAmong("this", "that")
};
var parser = new Parser(option);
var result = parser.Parse("-x something_else");
result.Errors
.Where(e => e.SymbolResult != null)
.Should()
.Contain(e => e.SymbolResult.Symbol.Name == option.Name);
}
[Fact]
public void When_a_required_argument_is_not_supplied_then_an_error_is_returned()
{
var parser = new Parser(new Option("-x")
{
Argument = new Argument
{
Arity = ArgumentArity.ExactlyOne
}
});
var result = parser.Parse("-x");
result.Errors
.Should()
.Contain(e => e.Message == "Required argument missing for option: -x");
}
[Fact]
public void When_a_required_option_is_not_supplied_then_an_error_is_returned()
{
var command = new Command("command")
{
new Option("-x")
{
IsRequired = true
}
};
var result = command.Parse("");
result.Errors
.Should()
.ContainSingle(e => e.SymbolResult.Symbol == command)
.Which
.Message
.Should()
.Be("Option '-x' is required.");
}
[Theory]
[InlineData("subcommand -x arg")]
[InlineData("-x arg subcommand")]
public void When_a_required_option_is_allowed_at_more_than_one_position_it_only_needs_to_be_satisfied_in_one(string commandLine)
{
var option = new Option<string>("-x")
{
IsRequired = true
};
var command = new RootCommand
{
option,
new Command("subcommand")
{
option
}
};
var result = command.Parse(commandLine);
result.Errors.Should().BeEmpty();
}
[Fact]
public void Required_options_on_parent_commands_do_not_create_parse_errors_when_an_inner_command_is_specified()
{
var child = new Command("child");
var parent = new RootCommand
{
new Option<string>("-x") { IsRequired = true },
child
};
parent.Name = "parent";
var result = parent.Parse("child");
result.Errors.Should().BeEmpty();
}
[Fact]
public void When_no_option_accepts_arguments_but_one_is_supplied_then_an_error_is_returned()
{
var parser = new Parser(
new Command("the-command")
{
new Option("-x")
});
var result = parser.Parse("the-command -x some-arg");
_output.WriteLine(result.ToString());
result.Errors
.Select(e => e.Message)
.Should()
.ContainSingle(e => e == "Unrecognized command or argument 'some-arg'");
}
[Fact]
public void A_custom_validator_can_be_added_to_a_command()
{
var command = new Command("the-command")
{
new Option("--one"),
new Option("--two")
};
command.AddValidator(commandResult =>
{
if (commandResult.Children.Contains("one") &&
commandResult.Children.Contains("two"))
{
return "Options '--one' and '--two' cannot be used together.";
}
return null;
});
var result = command.Parse("the-command --one --two");
result
.Errors
.Select(e => e.Message)
.Should()
.ContainSingle("Options '--one' and '--two' cannot be used together.");
}
[Fact]
public void A_custom_validator_can_be_added_to_an_option()
{
var option = new Option<int>("-x");
option.AddValidator(r =>
{
var value = r.GetValueOrDefault<int>();
return $"Option {r.Token.Value} cannot be set to {value}";
});
var command = new RootCommand { option };
var result = command.Parse("-x 123");
result.Errors
.Should()
.ContainSingle(e => e.SymbolResult.Symbol == option)
.Which
.Message
.Should()
.Be("Option -x cannot be set to 123");
}
[Fact]
public void A_custom_validator_can_be_added_to_an_argument()
{
var argument = new Argument<int>("x");
argument.AddValidator(r =>
{
var value = r.GetValueOrDefault<int>();
return $"Argument {r.Argument.Name} cannot be set to {value}";
});
var command = new RootCommand { argument };
var result = command.Parse("123");
result.Errors
.Should()
.ContainSingle(e => e.SymbolResult.Symbol == argument)
.Which
.Message
.Should()
.Be("Argument x cannot be set to 123");
}
[Fact]
public void Custom_validator_error_messages_are_not_repeated()
{
var errorMessage = "that's not right...";
var argument = new Argument<string>();
argument.AddValidator(o => errorMessage);
var cmd = new Command("get")
{
argument
};
var result = cmd.Parse("get something");
result.Errors
.Should()
.ContainSingle(errorMessage);
}
public class PathValidity
{
[Fact]
public void LegalFilePathsOnly_rejects_command_arguments_containing_invalid_path_characters()
{
var command = new Command("the-command")
{
new Argument<string>().LegalFilePathsOnly()
};
var invalidCharacter = Path.GetInvalidPathChars().First(c => c != '"');
var result = command.Parse($"the-command {invalidCharacter}");
result.Errors
.Should()
.Contain(e => e.SymbolResult.Symbol == command.Arguments.First() &&
e.Message == $"Character not allowed in a path: {invalidCharacter}");
}
[Fact]
public void LegalFilePathsOnly_rejects_option_arguments_containing_invalid_path_characters()
{
var command = new Command("the-command")
{
new Option<string>("-x").LegalFilePathsOnly()
};
var invalidCharacter = Path.GetInvalidPathChars().First(c => c != '"');
var result = command.Parse($"the-command -x {invalidCharacter}");
result.Errors
.Should()
.Contain(e => e.SymbolResult.Symbol.Name == "x" &&
e.Message == $"Character not allowed in a path: {invalidCharacter}");
}
[Fact]
public void LegalFilePathsOnly_accepts_command_arguments_containing_valid_path_characters()
{
var command = new Command("the-command")
{
new Argument<string[]>().LegalFilePathsOnly()
};
var validPathName = Directory.GetCurrentDirectory();
var validNonExistingFileName = Path.Combine(validPathName, Guid.NewGuid().ToString());
var result = command.Parse($"the-command {validPathName} {validNonExistingFileName}");
result.Errors.Should().BeEmpty();
}
[Fact]
public void LegalFilePathsOnly_accepts_option_arguments_containing_valid_path_characters()
{
var command = new Command("the-command")
{
new Option<string[]>("-x").LegalFilePathsOnly()
};
var validPathName = Directory.GetCurrentDirectory();
var validNonExistingFileName = Path.Combine(validPathName, Guid.NewGuid().ToString());
var result = command.Parse($"the-command -x {validPathName} {validNonExistingFileName}");
result.Errors.Should().BeEmpty();
}
}
public class FileExistence
{
[Fact]
public void A_command_argument_can_be_invalid_based_on_file_existence()
{
var command = new Command("move")
{
new Argument<FileInfo>("to").ExistingOnly()
};
var path = NonexistentPath();
var result = command.Parse($@"move ""{path}""");
result.Errors
.Should()
.HaveCount(1)
.And
.Contain(e => e.SymbolResult.Symbol.Name == "to" &&
e.Message == $"File does not exist: {path}");
}
[Fact]
public void An_option_argument_can_be_invalid_based_on_file_existence()
{
var command = new Command("move")
{
new Option<FileInfo>("--to").ExistingOnly()
};
var path = NonexistentPath();
var result = command.Parse($@"move --to ""{path}""");
result.Errors
.Should()
.HaveCount(1)
.And
.Contain(e => e.SymbolResult.Symbol.Name == "to" &&
e.Message == $"File does not exist: {path}");
}
[Fact]
public void A_command_argument_can_be_invalid_based_on_directory_existence()
{
var command = new Command("move")
{
new Argument<DirectoryInfo>("to").ExistingOnly()
};
var path = NonexistentPath();
var result = command.Parse($@"move ""{path}""");
result.Errors
.Should()
.HaveCount(1)
.And
.Contain(e => e.SymbolResult.Symbol.Name == "to" &&
e.Message == $"Directory does not exist: {path}");
}
[Fact]
public void An_option_argument_can_be_invalid_based_on_directory_existence()
{
var command = new Command("move")
{
new Option<DirectoryInfo>("--to").ExistingOnly()
};
var path = NonexistentPath();
var result = command.Parse($@"move --to ""{path}""");
result.Errors
.Should()
.HaveCount(1)
.And
.Contain(e => e.SymbolResult.Symbol.Name == "to" &&
e.Message == $"Directory does not exist: {path}");
}
[Fact]
public void A_command_argument_can_be_invalid_based_on_file_or_directory_existence()
{
var command = new Command("move")
{
new Argument<FileSystemInfo>().ExistingOnly()
};
var path = NonexistentPath();
var result = command.Parse($"move \"{path}\"");
result.Errors
.Should()
.HaveCount(1)
.And
.Contain(e => e.SymbolResult.Symbol == command.Arguments.First() &&
e.Message == $"File or directory does not exist: {path}");
}
[Fact]
public void An_option_argument_can_be_invalid_based_on_file_or_directory_existence()
{
var command = new Command("move")
{
new Option<FileSystemInfo>("--to").ExistingOnly()
};
var path = NonexistentPath();
var result = command.Parse($@"move --to ""{path}""");
result.Errors
.Should()
.HaveCount(1)
.And
.Contain(e => e.SymbolResult.Symbol.Name == "to" &&
e.Message == $"File or directory does not exist: {path}");
}
[Fact]
public void A_command_argument_with_multiple_files_can_be_invalid_based_on_file_existence()
{
var command = new Command("move")
{
new Argument<IEnumerable<FileInfo>>("to").ExistingOnly()
};
var path = NonexistentPath();
var result = command.Parse($@"move ""{path}""");
result.Errors
.Should()
.HaveCount(1)
.And
.Contain(e => e.SymbolResult.Symbol.Name == "to" &&
e.Message == $"File does not exist: {path}");
}
[Fact]
public void An_option_argument_with_multiple_files_can_be_invalid_based_on_file_existence()
{
var command = new Command("move")
{
new Option<IEnumerable<FileInfo>>("--to").ExistingOnly()
};
var path = NonexistentPath();
var result = command.Parse($@"move --to ""{path}""");
result.Errors
.Should()
.HaveCount(1)
.And
.Contain(e => e.SymbolResult.Symbol.Name == "to" &&
e.Message == $"File does not exist: {path}");
}
[Fact]
public void A_command_argument_with_multiple_directories_can_be_invalid_based_on_directory_existence()
{
var command = new Command("move")
{
new Argument<List<DirectoryInfo>>("to").ExistingOnly()
};
var path = NonexistentPath();
var result = command.Parse($@"move ""{path}""");
result.Errors
.Should()
.HaveCount(1)
.And
.Contain(e => e.SymbolResult.Symbol.Name == "to" &&
e.Message == $"Directory does not exist: {path}");
}
[Fact]
public void An_option_argument_with_multiple_directories_can_be_invalid_based_on_directory_existence()
{
var command = new Command("move")
{
new Option<DirectoryInfo[]>("--to").ExistingOnly()
};
var path = NonexistentPath();
var result = command.Parse($@"move --to ""{path}""");
result.Errors
.Should()
.HaveCount(1)
.And
.Contain(e => e.SymbolResult.Symbol.Name == "to" &&
e.Message == $"Directory does not exist: {path}");
}
[Fact]
public void A_command_argument_with_multiple_FileSystemInfos_can_be_invalid_based_on_file_existence()
{
var command = new Command("move")
{
new Argument<FileSystemInfo[]>("to")
{
Arity = ArgumentArity.ZeroOrMore
}.ExistingOnly(),
new Option("--to")
{
Argument = new Argument
{
Arity = ArgumentArity.ExactlyOne
}
}
};
var path = NonexistentPath();
var result = command.Parse($@"move ""{path}""");
result.Errors
.Should()
.Contain(e => e.SymbolResult.Symbol.Name == "to" &&
e.Message == $"File or directory does not exist: {path}");
}
[Fact]
public void An_option_argument_with_multiple_FileSystemInfos_can_be_invalid_based_on_file_existence()
{
var command = new Command("move")
{
new Option<FileSystemInfo[]>("--to").ExistingOnly()
};
var path = NonexistentPath();
var result =
command.Parse(
$@"move --to ""{path}""");
result.Errors
.Should()
.Contain(e => e.SymbolResult.Symbol.Name == "to" &&
e.Message == $"File or directory does not exist: {path}");
}
[Fact]
public void A_command_argument_with_multiple_FileSystemInfos_can_be_invalid_based_on_directory_existence()
{
var command = new Command("move")
{
new Argument<FileSystemInfo>("to").ExistingOnly()
};
var path = NonexistentPath();
var result = command.Parse($@"move ""{path}""");
result.Errors
.Should()
.HaveCount(1)
.And
.Contain(e => e.SymbolResult.Symbol.Name == "to" &&
e.Message == $"File or directory does not exist: {path}");
}
[Fact]
public void An_option_argument_with_multiple_FileSystemInfos_can_be_invalid_based_on_directory_existence()
{
var command = new Command("move")
{
new Option<FileSystemInfo[]>("--to").ExistingOnly()
};
var path = NonexistentPath();
var result = command.Parse($@"move --to ""{path}""");
result.Errors
.Should()
.HaveCount(1)
.And
.Contain(e => e.SymbolResult.Symbol.Name == "to" &&
e.Message == $"File or directory does not exist: {path}");
}
[Fact]
public void Command_argument_does_not_return_errors_when_file_exists()
{
var command = new Command("move")
{
new Argument<FileInfo>().ExistingOnly()
};
var path = ExistingFile();
var result = command.Parse($@"move ""{path}""");
result.Errors.Should().BeEmpty();
}
[Fact]
public void Option_argument_does_not_return_errors_when_file_exists()
{
var command = new Command("move")
{
new Option<FileInfo>("--to").ExistingOnly()
};
var path = ExistingFile();
var result = command.Parse($@"move --to ""{path}""");
result.Errors.Should().BeEmpty();
}
[Fact]
public void Command_argument_does_not_return_errors_when_Directory_exists()
{
var command = new Command("move")
{
new Argument<DirectoryInfo>().ExistingOnly()
};
var path = ExistingDirectory();
var result = command.Parse($@"move ""{path}""");
result.Errors.Should().BeEmpty();
}
[Fact]
public void Option_argument_does_not_return_errors_when_Directory_exists()
{
var command = new Command("move")
{
new Option<DirectoryInfo>("--to").ExistingOnly()
};
var path = ExistingDirectory();
var result = command.Parse($@"move --to ""{path}""");
result.Errors.Should().BeEmpty();
}
private string NonexistentPath()
{
return Guid.NewGuid().ToString();
}
private string ExistingDirectory()
{
return Directory.GetCurrentDirectory();
}
private string ExistingFile()
{
return new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles().First().FullName;
}
}
[Fact]
public void A_command_with_subcommands_is_invalid_to_invoke_if_it_has_no_handler()
{
var outer = new Command("outer");
var inner = new Command("inner");
var innerer = new Command("inner-er");
outer.AddCommand(inner);
inner.AddCommand(innerer);
var result = outer.Parse("outer inner arg");
result.Errors
.Should()
.ContainSingle(
e => e.Message.Equals(ValidationMessages.Instance.RequiredCommandWasNotProvided()) &&
e.SymbolResult.Symbol.Name.Equals("inner"));
}
[Fact]
public void A_root_command_is_invalid_if_it_has_no_handler()
{
var rootCommand = new RootCommand();
var inner = new Command("inner");
rootCommand.Add(inner);
var result = rootCommand.Parse("");
result.Errors
.Should()
.ContainSingle(
e => e.Message.Equals(ValidationMessages.Instance.RequiredCommandWasNotProvided()) &&
e.SymbolResult.Symbol == rootCommand);
}
[Fact]
public void A_command_with_subcommands_is_valid_to_invoke_if_it_has_a_handler()
{
var outer = new Command("outer");
var inner = new Command("inner")
{
Handler = CommandHandler.Create(() =>
{
})
};
var innerer = new Command("inner-er");
outer.AddCommand(inner);
inner.AddCommand(innerer);
var result = outer.Parse("outer inner");
result.Errors.Should().BeEmpty();
result.CommandResult.Command.Should().Be(inner);
}
[Fact]
public void When_an_option_is_specified_more_than_once_but_only_allowed_once_then_an_informative_error_is_returned()
{
var parser = new Parser(
new Option("-x")
{
Argument = new Argument
{
Arity = ArgumentArity.ExactlyOne
}
});
var result = parser.Parse("-x 1 -x 2");
result.Errors
.Select(e => e.Message)
.Should()
.Contain("Option '-x' expects a single argument but 2 were provided.");
}
[Fact]
public void When_arity_is_ExactlyOne_it_validates_against_extra_arguments()
{
var parser = new Parser(
new Option("-x")
{
Argument = new Argument<int>()
});
var result = parser.Parse("-x 1 -x 2");
result.Errors
.Select(e => e.Message)
.Should()
.Contain("Option '-x' expects a single argument but 2 were provided.");
}
[Fact]
public void When_an_option_has_a_default_value_it_is_not_valid_to_specify_the_option_without_an_argument()
{
var parser = new Parser(
new Option("-x")
{
Argument = new Argument<int>(() => 123)
});
var result = parser.Parse("-x");
result.Errors
.Select(e => e.Message)
.Should()
.Contain("Required argument missing for option: -x");
}
[Fact]
public void When_an_option_has_a_default_value_then_the_default_should_apply_if_not_specified()
{
var parser = new Parser(
new Option("-x")
{
Argument = (Argument) new Argument<int>(() => 123)
},
new Option("-y")
{
Argument = (Argument) new Argument<int>(() => 456)
});
var result = parser.Parse("");
result.Errors.Should().BeEmpty();
result.RootCommandResult.ValueForOption("-x").Should().Be(123);
result.RootCommandResult.ValueForOption("-y").Should().Be(456);
}
}
}
| 33.838037 | 136 | 0.46247 | [
"MIT"
] | michaelgwelch/command-line-api | src/System.CommandLine.Tests/ParsingValidationTests.cs | 27,580 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyFile
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
/// <summary>
/// Test Infrastructure for AutoRest Swagger BAT
/// </summary>
public partial class AutoRestSwaggerBATFileService : ServiceClient<AutoRestSwaggerBATFileService>, IAutoRestSwaggerBATFileService
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Gets the IFiles.
/// </summary>
public virtual IFiles Files { get; private set; }
/// <summary>
/// Initializes a new instance of the AutoRestSwaggerBATFileService class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AutoRestSwaggerBATFileService(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestSwaggerBATFileService class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AutoRestSwaggerBATFileService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestSwaggerBATFileService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestSwaggerBATFileService(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestSwaggerBATFileService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestSwaggerBATFileService(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// An optional partial-method to perform custom initialization.
///</summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
Files = new Files(this);
BaseUri = new System.Uri("http://localhost");
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
}
}
}
| 38.891026 | 162 | 0.598319 | [
"MIT"
] | brywang-msft/autorest | src/generator/AutoRest.CSharp.Tests/Expected/AcceptanceTests/BodyFile/AutoRestSwaggerBATFileService.cs | 6,067 | C# |
using Elreg.BusinessObjects.Options;
namespace Elreg.RaceOptionsService
{
public class VcuSerialPortService : ServiceBase<VcuSerialPortSettings>
{
public VcuSerialPortSettings VcuSerialPortSettings
{
get { return Object; }
}
protected override string Filename
{
get { return "VcuSerialPortSettings.xml"; }
}
}
}
| 23.055556 | 75 | 0.612048 | [
"MIT"
] | Heinzman/DigiRcMan | VisualStudio/Sources/RaceOptionsService/VcuSerialPortService.cs | 415 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Cynthia.Card
{
public interface ICardsPosition
{
float Size { get; set; }
float Width { get; set; }
bool IsCanDrag { get; set; }//其中卡牌是否可拖动
bool IsCanSelect { get; set; }//其中卡牌是否可被选中
int MaxCards { get; set; }
int GetCardCount();//卡牌的数量
void ResetCards();//固定位置
void CardsCanDrag(bool isCanDrag);//设定是否可拖动
void CardsCanSelect(bool isCanSelect);//设定是否可选中
void AddCard(CardMoveInfo card, int cardIndex);//在指定位置添加卡牌
void RemoveCard(int cardIndex);//删除卡牌
void CreateCard(CardMoveInfo card, int cardIndex);//指定位置创建卡牌
void SetCards(IEnumerable<CardMoveInfo> Cards);//设定初始卡牌
void SetCards(IEnumerable<GameCard> Cards);//设定初始卡牌
}
public interface ITemCard
{
bool IsTem();
void AddTemCard(GameCard cardInfo, int index);
}
} | 33 | 68 | 0.650993 | [
"MIT"
] | red-gezi/Cynthia.Card.Unity | src/Cynthia.Unity.Card/Assets/Script/Interface/ICardsPosition.cs | 1,109 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public delegate void PickupDelegate();
public delegate void InvenOnOffDelegate();
public enum MoveMode : byte
{
WALK = 0,
RUN
}
public class Player : MonoBehaviour, IControllable, IBattle, IHealth, IMana, IEquippableCharacter
{
// 이동용 데이터
public float walkSpeed = 3.0f;
public float runSpeed = 6.0f;
public float turnSpeed = 5.0f;
// 장비 데이터
public GameObject weaponAttachTarget = null;
public GameObject shield = null;
Weapon myWeapon = null;
ItemData_Weapon equipItem = null;
public ItemData_Weapon EquipItem { get => equipItem; }
// 공격용 데이터
public float attackPower = 15.0f;
public float critical = 0.2f;
public bool IsAttack { get; set; }
// 방어용 데이터
private float defencePower = 10.0f;
private float hp = 70.0f;
private float maxHP = 100.0f;
public float HP
{
get => hp;
set
{
hp = Mathf.Clamp(value, 0, MaxHP);
onHealthChange?.Invoke();
}
}
public float MaxHP { get => maxHP; }
public HealthDelegate onHealthChange { get; set; }
// 락온용 데이터
public GameObject lockOnEffect = null;
private Transform lockOnTarget = null;
private float lockOnRange = 5.0f;
// 아이템 사용
public PickupDelegate onPickupAction = null;
// 인벤토리
private Inventory inven = null;
public Inventory Inven { get => inven; }
public InvenOnOffDelegate onInventoryOnOff = null;
// 마나
private float mp = 50.0f;
private float maxMP = 100.0f;
public float MP
{
get => mp;
set
{
mp = Mathf.Clamp(value, 0, MaxMP);
onManaChange?.Invoke();
}
}
public float MaxMP { get => maxMP; }
public ManaDelegate onManaChange { get; set; }
public bool UseRigidbody { get => false; }
public int invenSlotCount = 8;
// 기타 데이터
private Animator anim = null;
private CharacterController controller = null;
private Vector3 inputDir = Vector2.zero;
private Quaternion targetRotation = Quaternion.identity;
private MoveMode moveMode = MoveMode.RUN;
void Awake()
{
myWeapon = weaponAttachTarget.GetComponentInChildren<Weapon>();
inven = new Inventory(invenSlotCount);
}
void Update()
{
if (myWeapon != null)
{
// 무기에 닿았던 적들 전부 데미지 주기
while (myWeapon.HitTargetCount() > 0)
{
IBattle target = myWeapon.GetHitTarget();
Attack(target);
}
}
// 록온을 했을 때 대상을 계속 바라보기
if(lockOnTarget != null)
{
//this.transform.LookAt(lockOnTarget.position);
Vector3 dir = lockOnTarget.position - this.transform.position;
targetRotation = Quaternion.LookRotation(dir);
}
}
public void ControllerConnect()
{
anim = GetComponent<Animator>();
controller = GetComponent<CharacterController>();
}
public void MoveInput(Vector2 dir)
{
// dir.x : a(-1) d(+1)
// dir.y : s(-1) w(+1)
inputDir.x = dir.x;
inputDir.y = 0;
inputDir.z = dir.y;
inputDir.Normalize();
if (inputDir.sqrMagnitude > 0.0f)
{
inputDir = Quaternion.Euler(0, Camera.main.transform.rotation.eulerAngles.y, 0) * inputDir;
targetRotation = Quaternion.LookRotation(inputDir);
inputDir.y = -9.8f;
}
}
public void MoveUpdate()
{
if (inputDir.magnitude > 0.0f)
{
float speed = 1.0f;
if (moveMode == MoveMode.WALK)
{
anim.SetFloat("Speed", 0.5f);
speed = walkSpeed;
}
else if (moveMode == MoveMode.RUN)
{
anim.SetFloat("Speed", 1.0f);
speed = runSpeed;
}
else
{
anim.SetFloat("Speed", 0.0f);
}
controller.Move(inputDir * speed * Time.deltaTime);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, turnSpeed * Time.deltaTime);
}
else
{
anim.SetFloat("Speed", 0.0f);
}
}
public void MoveModeChange()
{
if( moveMode == MoveMode.WALK )
{
moveMode = MoveMode.RUN;
}
else
{
moveMode = MoveMode.WALK;
}
}
public void ShowArms(bool isShow)
{
// equip이 true면 무기와 방패가 보인다. false 보이지 않는다.
weaponAttachTarget.SetActive(isShow);
shield.SetActive(isShow);
}
public void EquipWeapon(ItemData_Weapon weapon)
{
if (weapon != equipItem) // 다른 무기를 장착하라고 하면 장착
{
equipItem = weapon;
Instantiate(weapon.prefab, weaponAttachTarget.transform);
myWeapon = weaponAttachTarget.GetComponentInChildren<Weapon>();
}
}
public void UnEquipWeapon()
{
while( weaponAttachTarget.transform.childCount > 0 )
{
Transform del = weaponAttachTarget.transform.GetChild(0);
del.parent = null;
Destroy(del.gameObject);
}
equipItem = null;
myWeapon = null;
}
public bool IsEquipWeapon()
{
return (weaponAttachTarget.transform.childCount > 0); // 장비중이면 true, 아니면 false
}
public void AttackInput()
{
//Debug.Log("Attack");
anim.SetFloat("ComboState",
Mathf.Repeat(anim.GetCurrentAnimatorStateInfo(0).normalizedTime, 1.0f));
anim.ResetTrigger("Attack");
anim.SetTrigger("Attack");
}
public void LockOnInput()
{
//Debug.Log("LockOnInput");
if( lockOnTarget == null )
{
LockOn();
}
else
{
LockOff();
}
}
void LockOn()
{
Collider[] cols = Physics.OverlapSphere(
this.transform.position, lockOnRange, LayerMask.GetMask("Enemy"));
// LayerMask.GetMask("Enemy") //0b_1000000
// 1<<LayerMask.NameToLayer("Enemy") //0b_1000000
// LayerMask.GetMask("Enemy","Default","Water") //0b_1010001
// LayerMask.NameToLayer("Enemy") //6이 리턴
if( cols.Length > 0 )
{
// 가장 가까운 적을 찾는 코드 작성
Collider nearest = null;
float nearestDistance = float.MaxValue;
foreach(Collider col in cols)
{
float distance = (col.transform.position - this.transform.position).sqrMagnitude;
if(distance < nearestDistance)
{
nearestDistance = distance;
nearest = col;
}
}
lockOnTarget = nearest.transform;
lockOnEffect.transform.position = lockOnTarget.position;
lockOnEffect.transform.parent = lockOnTarget;
lockOnEffect.SetActive(true);
}
}
void LockOff()
{
lockOnTarget = null;
lockOnEffect.transform.parent = null;
lockOnEffect.SetActive(false);
}
public void LockOff(Transform target)
{
if(target == lockOnTarget)
{
LockOff();
}
}
public void Attack(IBattle target)
{
if (target != null)
{
float damage = attackPower;
if (Random.Range(0.0f, 1.0f) < critical)
{
damage *= 2.0f;
}
target.TakeDamage(damage);
}
}
public void TakeDamage(float damage)
{
//Debug.Log($"{gameObject.name} : {damage} 데미지 입음");
float finalDamage = damage - defencePower;
if (finalDamage < 1.0f)
{
finalDamage = 1.0f;
}
hp -= finalDamage;
if (hp <= 0.0f)
{
//Die();
}
HP = hp;
}
public void PickupInput()
{
onPickupAction?.Invoke();
}
public void InventoryOnOffInput()
{
onInventoryOnOff?.Invoke();
}
}
| 25.667702 | 115 | 0.538294 | [
"MIT"
] | go2665/atents220128_2 | 3D_Character/Assets/Scripts/Character/Player/Player.cs | 8,535 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using WCSharp.Shared;
using WCSharp.Sync;
using static War3Api.Common;
namespace WCSharp.DateTime
{
internal class DateTimeSystem
{
private readonly Action<WcDateTime> action;
private readonly DateTimeSyncMethod method;
private readonly Dictionary<int, WcDateTime> timestamps;
public DateTimeSystem(DateTimeSyncMethod method, Action<WcDateTime> action = null)
{
this.method = method;
this.action = action;
this.timestamps = new Dictionary<int, WcDateTime>();
}
public void Run()
{
var message = new DateTimeSyncMessage
{
PlayerId = GetPlayerId(GetLocalPlayer()),
Seconds = WcDateTime.LocalTime.TotalSeconds
};
SyncSystem.Subscribe<DateTimeSyncMessage>(HandleDateTimeSyncMessage);
SyncSystem.Send(message);
}
private void HandleDateTimeSyncMessage(DateTimeSyncMessage message)
{
this.timestamps[message.PlayerId] = new WcDateTime(message.Seconds);
if (Util.EnumeratePlayers(PLAYER_SLOT_STATE_PLAYING, MAP_CONTROL_USER).All(x => this.timestamps.ContainsKey(GetPlayerId(x))))
{
var sync = this.method switch
{
DateTimeSyncMethod.Earliest => ResolveEarliest(),
DateTimeSyncMethod.Latest => ResolveLatest(),
DateTimeSyncMethod.Average => ResolveAverage(),
_ => ResolveBestFit(),
};
SyncSystem.Unsubscribe<DateTimeSyncMessage>(HandleDateTimeSyncMessage);
WcDateTime.StoreSynchronisedTime(sync.TotalSeconds, this.method);
this.action?.Invoke(sync);
}
}
private WcDateTime ResolveEarliest()
{
return this.timestamps.Values.Min();
}
private WcDateTime ResolveLatest()
{
return this.timestamps.Values.Max();
}
private WcDateTime ResolveAverage()
{
var count = this.timestamps.Count;
var averageSeconds = this.timestamps.Values.Sum(x => x.TotalSeconds / count);
return new WcDateTime(averageSeconds);
}
private WcDateTime ResolveBestFit()
{
if (this.timestamps.Count % 2 == 0)
{
var ordered = this.timestamps.Values
.OrderBy(x => x.TotalSeconds)
.ToList();
var middle = this.timestamps.Count / 2;
var t1 = ordered[middle - 1];
var t2 = ordered[middle];
var avg = this.timestamps.Values.Sum(x => x.TotalSeconds / this.timestamps.Count);
if (Math.Abs(t1.TotalSeconds - avg) < Math.Abs(t2.TotalSeconds - avg))
{
return t1;
}
else
{
return t2;
}
}
else
{
var ordered = this.timestamps.Values
.OrderBy(x => x.TotalSeconds)
.ToList();
return ordered[this.timestamps.Count / 2];
}
}
}
}
| 24.809524 | 128 | 0.699424 | [
"MIT"
] | Orden4/WCSharp | WCSharp.DateTime/DateTimeSystem.cs | 2,607 | C# |
using Microsoft.Rest;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Bot.Connector
{
public static class ErrorHandling
{
public static async Task HandleErrorAsync(this HttpOperationResponse<object> result)
{
if (!result.Response.IsSuccessStatusCode)
{
ErrorResponse errorMessage = result.Body as ErrorResponse;
string _requestContent = null;
if (result.Request != null && result.Request.Content != null)
{
try
{
_requestContent = await result.Request.Content.ReadAsStringAsync().ConfigureAwait(false);
}
catch (ObjectDisposedException)
{
//result.Request.Content is disposed.
_requestContent = null;
}
}
string _responseContent = null;
if (result.Response != null && result.Response.Content != null)
{
try
{
_responseContent = await result.Response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
catch (ObjectDisposedException)
{
_responseContent = null;
}
}
throw new HttpOperationException(String.IsNullOrEmpty(errorMessage?.Error?.Message) ? result.Response.ReasonPhrase : errorMessage?.Error?.Message)
{
Request = new HttpRequestMessageWrapper(result.Request, _requestContent),
Response = new HttpResponseMessageWrapper(result.Response, _responseContent),
Body = result.Body
};
}
}
public static async Task<ErrorResponse> HandleErrorAsync(this HttpOperationResponse<ErrorResponse> result)
{
if (!result.Response.IsSuccessStatusCode)
{
ErrorResponse errorMessage = result.Body as ErrorResponse;
string _requestContent = null;
if (result.Request != null && result.Request.Content != null)
{
try
{
_requestContent = await result.Request.Content.ReadAsStringAsync().ConfigureAwait(false);
}
catch (ObjectDisposedException)
{
//result.Request.Content is disposed.
_requestContent = null;
}
}
string _responseContent = null;
if (result.Response != null && result.Response.Content != null)
{
try
{
_responseContent = await result.Response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
catch (ObjectDisposedException)
{
_responseContent = null;
}
}
throw new HttpOperationException(String.IsNullOrEmpty(errorMessage?.Error?.Message) ? result.Response.ReasonPhrase : errorMessage?.Error?.Message)
{
Request = new HttpRequestMessageWrapper(result.Request, _requestContent),
Response = new HttpResponseMessageWrapper(result.Response, _responseContent),
Body = result.Body
};
}
return result.Body;
}
public static async Task<ObjectT> HandleErrorAsync<ObjectT>(this HttpOperationResponse<object> result)
{
if (!result.Response.IsSuccessStatusCode)
{
ErrorResponse errorMessage = result.Body as ErrorResponse;
string _requestContent = null;
if (result.Request != null && result.Request.Content != null)
{
try
{
_requestContent = await result.Request.Content.ReadAsStringAsync().ConfigureAwait(false);
}
catch (ObjectDisposedException)
{
//result.Request.Content is disposed.
_requestContent = null;
}
}
string _responseContent = null;
if (result.Response != null && result.Response.Content != null)
{
try
{
_responseContent = await result.Response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
catch (ObjectDisposedException)
{
_responseContent = null;
}
}
throw new HttpOperationException(String.IsNullOrEmpty(errorMessage?.Error?.Message) ? result.Response.ReasonPhrase : errorMessage?.Error?.Message)
{
Request = new HttpRequestMessageWrapper(result.Request, _requestContent),
Response = new HttpResponseMessageWrapper(result.Response, _responseContent),
Body = result.Body
};
}
if (typeof(ObjectT).IsArray)
{
IList list = (IList)result.Body;
if (list == null)
{
return default(ObjectT);
}
IList array = (IList)Array.CreateInstance(typeof(ObjectT).GetElementType(), list.Count);
int i = 0;
foreach (var el in list)
array[i++] = el;
return (ObjectT)array;
}
return (ObjectT)result.Body;
}
}
} | 40.545455 | 163 | 0.482543 | [
"MIT"
] | KenichiKawamura/MS-BotBuilder | CSharp/Library/Microsoft.Bot.Connector/ErrorHandling.cs | 6,246 | C# |
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: global::Android.Runtime.ResourceDesignerAttribute("BindingContextChanged.Droid.Resource", IsApplication=true)]
namespace BindingContextChanged.Droid
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")]
public partial class Resource
{
static Resource()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
public static void UpdateIdValues()
{
global::Xamarin.Forms.Platform.Android.Resource.Attribute.actionBarSize = global::BindingContextChanged.Droid.Resource.Attribute.actionBarSize;
}
public partial class Attribute
{
static Attribute()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Attribute()
{
}
}
public partial class Drawable
{
// aapt resource value: 0x7f020000
public const int icon = 2130837504;
static Drawable()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Drawable()
{
}
}
}
}
#pragma warning restore 1591
| 23.539683 | 146 | 0.627107 | [
"Apache-2.0"
] | Alshaikh-Abdalrahman/jedoo | UserInterface/ListView/BindingContextChanged/Droid/Resources/Resource.designer.cs | 1,483 | C# |
using System.Threading.Tasks;
using Minesweeper.Core.ViewModels.Modals;
namespace Minesweeper.Core.Interfaces.Services
{
/// <summary>
/// Defines modal service functionality.
/// </summary>
public interface IModalService
{
/// <summary>
/// Displays the confirm modal and returns a <see cref="Task"/> whose result represents
/// the closing of the modal.
/// </summary>
/// <param name="viewModel">The confirm modal view model.</param>
/// <returns></returns>
Task ShowConfirmModal(ConfirmModalViewModel viewModel);
}
}
| 30.1 | 95 | 0.644518 | [
"MIT"
] | roknr/minesweeper | Source/Minesweeper.Core/Interfaces/Services/IModalService.cs | 602 | C# |
// Copyright 2004-2021 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 Castle.DynamicProxy.Tests.Interfaces
{
public interface IIdenticalTwo
{
string Foo();
}
public interface IIdenticalOne
{
string Foo();
}
}
| 29.333333 | 75 | 0.738636 | [
"Apache-2.0"
] | Havunen/Core | src/Castle.Core.Tests/DynamicProxy.Tests/Interfaces/IdenticalInterfaces.cs | 792 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreKeeper : MonoBehaviour {
[SerializeField] int score = 0;
public void IncrementScore() {
score++;
}
public int Score() {
return score;
}
}
| 17.470588 | 42 | 0.6633 | [
"MIT"
] | Yotam124/gamedev-5780-code | 03-art-old/Assets/Scripts/ScoreKeeper.cs | 299 | C# |
using AutoMapper;
using AutoMapper.QueryableExtensions;
using System.Diagnostics.CodeAnalysis;
using TaskManagerWebAPI.Repositories;
namespace TaskManagerWebAPI.Services
{
/// <inheritdoc cref="IProjectService"/>
public class ProjectService : IProjectService
{
private readonly IMapper _mapper;
private readonly IProjectRepository _projectRepository;
private readonly ITaskRepository _taskRepository;
/// <summary/>
public ProjectService(IMapper mapper, IProjectRepository projectRepository, ITaskRepository taskRepository)
{
_mapper = mapper;
_projectRepository = projectRepository;
_taskRepository = taskRepository;
}
/// <inheritdoc/>
public async Task<Models.ProjectResponse> Create(Models.CreateProjectRequest projectRequest)
{
var createdProject = await _projectRepository.Create(
_mapper.Map<Entities.Project>(projectRequest));
return _mapper.Map<Models.ProjectResponse>(createdProject);
}
/// <inheritdoc/>
public async Task<Models.ProjectResponse?> Get(Guid projectId)
{
var foundProject = await _projectRepository.Get(projectId);
if (foundProject == null)
return null;
return _mapper.Map<Models.ProjectResponse>(foundProject);
}
/// <inheritdoc/>
public async Task<Models.ProjectResponse?> Update(Guid projectId, Models.UpdateProjectRequest projectRequest)
{
var response = await _projectRepository.Update(_mapper.Map<Entities.Project>(projectRequest));
if (response == null)
return null;
return _mapper.Map<Models.ProjectResponse>(response);
}
/// <inheritdoc/>
public async Task<Models.ProjectResponse?> Delete(Guid projectId)
{
var foundProject = await _projectRepository.Get(projectId);
if (foundProject == null)
return null;
var response = await _projectRepository.Delete(projectId);
return _mapper.Map<Models.ProjectResponse>(response);
}
/// <inheritdoc/>
public async Task<IQueryable<Models.ProjectResponse>> GetAll()
{
var response = await _projectRepository.All();
return response.ProjectTo<Models.ProjectResponse>(_mapper.ConfigurationProvider);
}
/// <inheritdoc/>
public async Task<IQueryable<Models.TaskResponse>?> GetProjectTasks(Guid projectId)
{
var foundProject = await _projectRepository.Get(projectId);
if (foundProject == null)
return null;
var response = (await _taskRepository.All()).Where(task => task.ProjectId == projectId);
return response.ProjectTo<Models.TaskResponse>(_mapper.ConfigurationProvider);
}
/// <inheritdoc/>
public async Task<int> SaveChanges()
{
return await _projectRepository.Save();
}
}
}
| 36.447059 | 117 | 0.635571 | [
"Unlicense"
] | akikodev/TaskManagerWebAPI | TaskManagerWebAPI/Services/ProjectService.cs | 3,100 | C# |
//*********************************************************
// Copyright (c) Dominic Maas. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//*********************************************************
using Windows.UI.Xaml.Controls;
using SoundByte.UWP.Services;
using Windows.UI.Xaml.Navigation;
namespace SoundByte.UWP.Views.Me
{
/// <summary>
/// Let the user view their playlists
/// </summary>
public sealed partial class PlaylistsView
{
/// <summary>
/// The playlist model that contains the users playlists / liked playlists
/// </summary>
private Models.UserPlaylistModel PlaylistModel { get; } = new Models.UserPlaylistModel();
public PlaylistsView()
{
InitializeComponent();
NavigationCacheMode = NavigationCacheMode.Enabled;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
TelemetryService.Current.TrackPage("User Playlist Page");
}
public void NavigatePlaylist(object sender, ItemClickEventArgs e)
{
App.NavigateTo(typeof(Playlist), e.ClickedItem as Core.API.Endpoints.Playlist);
}
}
}
| 33.302326 | 97 | 0.610335 | [
"MIT"
] | Hrishi1999/SoundByte | SoundByte.UWP/Views/Me/PlaylistsView.xaml.cs | 1,434 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// La información general de un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos valores de atributo para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("UnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("UnitTests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si es necesario obtener acceso a un tipo en este ensamblado desde
// COM, establezca el atributo ComVisible en true en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM.
[assembly: Guid("5e071a3d-72a7-444d-a173-4ced495cd541")]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión
// mediante el carácter '*', como se muestra a continuación:
//[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 40.918919 | 113 | 0.756275 | [
"Apache-2.0"
] | bitrvmpd/wuffSonic | UnitTests/Properties/AssemblyInfo.cs | 1,532 | C# |
namespace Cpnucleo.Infra.Data.Repositories;
internal class WorkflowRepository : GenericRepository<Workflow>, IWorkflowRepository
{
public WorkflowRepository(CpnucleoContext context)
: base(context)
{
}
public async Task<int> GetQuantidadeColunasAsync()
{
System.Collections.Generic.IEnumerable<Workflow> result = await AllAsync(true);
return result.Count();
}
public string GetTamanhoColuna(int colunas)
{
colunas = colunas == 1 ? 2 : colunas;
int i = 12 / colunas;
return i.ToString();
}
}
| 22.384615 | 87 | 0.661512 | [
"MIT"
] | jonathanperis/cpnucleo | src/Cpnucleo.Infra.Data/Repositories/WorkflowRepository.cs | 584 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Abp.Dependency;
namespace GSoft.AbpZeroTemplate.Authentication.TwoFactor.Google
{
/// <summary>
/// This code taken from https://github.com/BrandonPotter/GoogleAuthenticator
/// </summary>
public class GoogleTwoFactorAuthenticateService : ITransientDependency
{
public static DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public TimeSpan DefaultClockDriftTolerance { get; set; }
public bool UseManagedSha1Algorithm { get; set; }
public bool TryUnmanagedAlgorithmOnFailure { get; set; }
public GoogleTwoFactorAuthenticateService() : this(true, true) { }
public GoogleTwoFactorAuthenticateService(bool useManagedSha1, bool useUnmanagedOnFail)
{
DefaultClockDriftTolerance = TimeSpan.FromMinutes(5);
UseManagedSha1Algorithm = useManagedSha1;
TryUnmanagedAlgorithmOnFailure = useUnmanagedOnFail;
}
public GoogleAuthenticatorSetupCode GenerateSetupCode(string accountTitleNoSpaces, string accountSecretKey, int qrCodeWidth, int qrCodeHeight)
{
return GenerateSetupCode(null, accountTitleNoSpaces, accountSecretKey, qrCodeWidth, qrCodeHeight);
}
public GoogleAuthenticatorSetupCode GenerateSetupCode(string issuer, string accountTitleNoSpaces, string accountSecretKey, int qrCodeWidth, int qrCodeHeight)
{
return GenerateSetupCode(issuer, accountTitleNoSpaces, accountSecretKey, qrCodeWidth, qrCodeHeight, false);
}
public GoogleAuthenticatorSetupCode GenerateSetupCode(string issuer, string accountTitleNoSpaces, string accountSecretKey, int qrCodeWidth, int qrCodeHeight, bool useHttps)
{
accountTitleNoSpaces = accountTitleNoSpaces?.Replace(" ", "") ?? throw new NullReferenceException("Account Title is null");
var setupCode = new GoogleAuthenticatorSetupCode
{
Account = accountTitleNoSpaces,
AccountSecretKey = accountSecretKey
};
var encodedSecretKey = EncodeAccountSecretKey(accountSecretKey);
setupCode.ManualEntryKey = encodedSecretKey;
string provisionUrl = UrlEncode(string.IsNullOrEmpty(issuer) ?
$"otpauth://totp/{accountTitleNoSpaces}?secret={encodedSecretKey}" :
$"otpauth://totp/{accountTitleNoSpaces}?secret={encodedSecretKey}&issuer={UrlEncode(issuer)}");
var protocol = useHttps ? "https" : "http";
var url =
$"{protocol}://chart.googleapis.com/chart?cht=qr&chs={qrCodeWidth}x{qrCodeHeight}&chl={provisionUrl}";
setupCode.QrCodeSetupImageUrl = url;
return setupCode;
}
private string UrlEncode(string value)
{
var stringBuilder = new StringBuilder();
const string validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
foreach (var symbol in value)
{
if (validChars.IndexOf(symbol) != -1)
{
stringBuilder.Append(symbol);
}
else
{
stringBuilder.Append('%' + $"{(int)symbol:X2}");
}
}
return stringBuilder.ToString().Replace(" ", "%20");
}
private string EncodeAccountSecretKey(string accountSecretKey)
{
return Base32Encode(Encoding.UTF8.GetBytes(accountSecretKey));
}
private string Base32Encode(byte[] data)
{
var inByteSize = 8;
var outByteSize = 5;
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".ToCharArray();
int i = 0, index = 0;
var result = new StringBuilder((data.Length + 7) * inByteSize / outByteSize);
while (i < data.Length)
{
var currentByte = data[i] >= 0 ? data[i] : (data[i] + 256);
int digit;
if (index > inByteSize - outByteSize)
{
int nextByte;
if (i + 1 < data.Length)
nextByte = (data[i + 1] >= 0) ? data[i + 1] : (data[i + 1] + 256);
else
nextByte = 0;
digit = currentByte & (0xFF >> index);
index = (index + outByteSize) % inByteSize;
digit <<= index;
digit |= nextByte >> (inByteSize - index);
i++;
}
else
{
digit = (currentByte >> (inByteSize - (index + outByteSize))) & 0x1F;
index = (index + outByteSize) % inByteSize;
if (index == 0)
i++;
}
result.Append(alphabet[digit]);
}
return result.ToString();
}
public string GeneratePinAtInterval(string accountSecretKey, long counter, int digits = 6)
{
return GenerateHashedCode(accountSecretKey, counter, digits);
}
internal string GenerateHashedCode(string secret, long iterationNumber, int digits = 6)
{
var key = Encoding.UTF8.GetBytes(secret);
return GenerateHashedCode(key, iterationNumber, digits);
}
internal string GenerateHashedCode(byte[] key, long iterationNumber, int digits = 6)
{
var counter = BitConverter.GetBytes(iterationNumber);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(counter);
}
var hmac = GetHmacSha1Algorithm(key);
var hash = hmac.ComputeHash(counter);
var offset = hash[hash.Length - 1] & 0xf;
// Convert the 4 bytes into an integer, ignoring the sign.
var binary =
((hash[offset] & 0x7f) << 24)
| (hash[offset + 1] << 16)
| (hash[offset + 2] << 8)
| (hash[offset + 3]);
var password = binary % (int)Math.Pow(10, digits);
return password.ToString(new string('0', digits));
}
private long GetCurrentCounter()
{
return GetCurrentCounter(DateTime.UtcNow, Epoch, 30);
}
private long GetCurrentCounter(DateTime now, DateTime epoch, int timeStep)
{
return (long)(now - epoch).TotalSeconds / timeStep;
}
private HMACSHA1 GetHmacSha1Algorithm(byte[] key)
{
return new HMACSHA1(key);
}
public bool ValidateTwoFactorPin(string accountSecretKey, string twoFactorCodeFromClient)
{
return ValidateTwoFactorPin(accountSecretKey, twoFactorCodeFromClient, DefaultClockDriftTolerance);
}
public bool ValidateTwoFactorPin(string accountSecretKey, string twoFactorCodeFromClient, TimeSpan timeTolerance)
{
var codes = GetCurrentPins(accountSecretKey, timeTolerance);
return codes.Any(c => c == twoFactorCodeFromClient);
}
public string[] GetCurrentPins(string accountSecretKey, TimeSpan timeTolerance)
{
var codes = new List<string>();
var iterationCounter = GetCurrentCounter();
var iterationOffset = 0;
if (timeTolerance.TotalSeconds > 30)
{
iterationOffset = Convert.ToInt32(timeTolerance.TotalSeconds / 30.00);
}
var iterationStart = iterationCounter - iterationOffset;
var iterationEnd = iterationCounter + iterationOffset;
for (var counter = iterationStart; counter <= iterationEnd; counter++)
{
codes.Add(GeneratePinAtInterval(accountSecretKey, counter));
}
return codes.ToArray();
}
}
} | 37.49537 | 180 | 0.583652 | [
"Apache-2.0"
] | NTD98/ASP_ANGULAR | asset-management-api/src/GSoft.AbpZeroTemplate.Core/Authentication/TwoFactor/Google/GoogleTwoFactorAuthenticateService.cs | 8,099 | C# |
//
// Copyright (c) Stanislav Grigoriev. All rights reserved.
// grigorievstas9@gmail.com
// https://github.com/StanislavGrigoriev/EasyCNTK
//
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//
using System.Collections.Generic;
using CNTK;
namespace EasyCNTK.Learning.Optimizers
{
/// <summary>
/// Adam Optimizer. Combines and enhances benefits<seealso cref="RMSProp"/>, <seealso cref="AdaDelta"/>, <seealso cref="AdaGrad"/>
/// </summary>
public sealed class Adam : Optimizer
{
private double _momentum;
private double _l1RegularizationWeight;
private double _l2RegularizationWeight;
private double _gradientClippingThresholdPerSample;
private double _epsilon;
private double _varianceMomentumSchedule;
private bool _unitGain;
public override double LearningRate { get; }
public override int MinibatchSize { get; set; }
/// <summary>
/// Initializes Adam Optimizer
/// </summary>
/// <param name="learningRate">Learning speed</param>
/// <param name="momentum">Moment</param>
/// <param name="minibatchSize">The mini-packet size is required by CNTK to scale optimizer parameters for more effective training. If equal to 0, then the mitibatch size will be used during training.</param>
/// <param name="l1RegularizationWeight">Coefficient L1 of norm, if 0 - regularization is not applied</param>
/// <param name="l2RegularizationWeight">Coefficient L2 of norm, if 0 - regularization is not applied</param>
/// <param name="gradientClippingThresholdPerSample">The gradient cutoff threshold for each training example is used primarily to combat the explosive gradient in deep recursive networks.
/// The default is set to<seealso cref="double.PositiveInfinity"/> - clipping is not used. To use, set the required threshold..</param>
/// <param name="epsilon">Constant for stabilization (protection against division by 0). The "e" parameter is in the formula for updating parameters: http://ruder.io/optimizing-gradient-descent/index.html#adam</param>
/// <param name="varianceMomentumSchedule">"Beta2" parameter in the formula for calculating the moment: http://ruder.io/optimizing-gradient-descent/index.html#adam</param>
/// <param name="unitGain">Indicates that the torque is used in gain mode.</param>
public Adam(double learningRate,
double momentum,
int minibatchSize = 0,
double l1RegularizationWeight = 0,
double l2RegularizationWeight = 0,
double gradientClippingThresholdPerSample = double.PositiveInfinity,
double epsilon = 1e-8,
double varianceMomentumSchedule = 0.9999986111120757,
bool unitGain = true)
{
LearningRate = learningRate;
_momentum = momentum;
_l1RegularizationWeight = l1RegularizationWeight;
_l2RegularizationWeight = l2RegularizationWeight;
_gradientClippingThresholdPerSample = gradientClippingThresholdPerSample;
_epsilon = epsilon;
_varianceMomentumSchedule = varianceMomentumSchedule;
_unitGain = unitGain;
MinibatchSize = minibatchSize;
}
public override Learner GetOptimizer(IList<Parameter> learningParameters)
{
var learningOptions = new AdditionalLearningOptions()
{
l1RegularizationWeight = _l1RegularizationWeight,
l2RegularizationWeight = _l2RegularizationWeight,
gradientClippingWithTruncation = _gradientClippingThresholdPerSample != double.PositiveInfinity,
gradientClippingThresholdPerSample = _gradientClippingThresholdPerSample
};
var learner = CNTKLib.AdamLearner(
parameters: new ParameterVector((System.Collections.ICollection)learningParameters),
learningRateSchedule: new TrainingParameterScheduleDouble(LearningRate, (uint)MinibatchSize),
momentumSchedule: new TrainingParameterScheduleDouble(_momentum, (uint)MinibatchSize),
unitGain: _unitGain,
varianceMomentumSchedule: new TrainingParameterScheduleDouble(_varianceMomentumSchedule, (uint)MinibatchSize),
epsilon: _epsilon,
adamax: false,
additionalOptions: learningOptions);
return learner;
}
}
}
| 53.045455 | 235 | 0.680805 | [
"MIT"
] | byteshadow/EasyCNTK | Source/EasyCNTK/Learning/Optimizers/Adam.cs | 4,668 | 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("OddOrEvenIntegers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OddOrEvenIntegers")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("0aa2f7fb-398c-4895-80bf-8557419bbc94")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.027027 | 84 | 0.746979 | [
"MIT"
] | siderisltd/Telerik-Academy | All Courses Homeworks/C#_Part_1/3. OperatorsAndExpressions/OddOrEvenIntegers/Properties/AssemblyInfo.cs | 1,410 | C# |
using BizHawk.Common;
namespace BizHawk.Emulation.Cores.Nintendo.NES
{
// smb2j (us pirate)
internal sealed class Mapper040 : NesBoardBase
{
int prg = 0;
int irqcnt = 0;
bool irqactive = false;
public override bool Configure(EDetectionOrigin origin)
{
switch (Cart.BoardType)
{
case "MAPPER040":
AssertChr(8); AssertPrg(64); AssertVram(0); AssertWram(0);
break;
default:
return false;
}
SetMirrorType(Cart.PadH, Cart.PadV);
return true;
}
public override byte ReadWram(int addr)
{
// bank 6 fixed
return Rom[addr + 0xc000];
}
public override byte ReadPrg(int addr)
{
if ((addr & 0x6000) == 0x4000)
addr += prg;
return Rom[addr + 0x8000];
}
public override void WritePrg(int addr, byte value)
{
switch (addr & 0x6000)
{
case 0x0000:
irqcnt = 0;
IrqSignal = false;
irqactive = false;
break;
case 0x2000:
irqactive = true;
break;
case 0x6000:
prg = value & 7; // bank number
// adjust for easy usage
prg *= 0x2000;
prg -= 0xc000;
break;
}
}
public override void ClockCpu()
{
if (irqactive)
{
irqcnt++;
if (irqcnt >= 4096)
{
irqcnt = 4096;
IrqSignal = true;
}
}
}
public override void SyncState(Serializer ser)
{
base.SyncState(ser);
ser.Sync(nameof(prg), ref prg);
ser.Sync(nameof(irqcnt), ref irqcnt);
ser.Sync(nameof(irqactive), ref irqactive);
}
}
}
| 19.259259 | 64 | 0.573718 | [
"MIT"
] | NarryG/bizhawk-vanguard | src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper040.cs | 1,562 | C# |
using System;
namespace GoodNews.Models.DBModels
{
public interface IDatabaseModel
{
string Id { get; set; }
DateTime CreatedAt { get; set; }
}
} | 17.4 | 40 | 0.62069 | [
"BSD-3-Clause"
] | gd-nws/api | src/GoodNews/Models/DBModels/IDatabaseModel.cs | 174 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** 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.AzureNative.Insights.Inputs
{
/// <summary>
/// Azure Monitor Metrics destination.
/// </summary>
public sealed class DestinationsSpecAzureMonitorMetricsArgs : Pulumi.ResourceArgs
{
/// <summary>
/// A friendly name for the destination.
/// This name should be unique across all destinations (regardless of type) within the data collection rule.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
public DestinationsSpecAzureMonitorMetricsArgs()
{
}
}
}
| 29.7 | 116 | 0.666667 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Insights/Inputs/DestinationsSpecAzureMonitorMetricsArgs.cs | 891 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using HairSalon;
namespace HairSalon.Models
{
public class DB
{
public static MySqlConnection Connection()
{
MySqlConnection conn = new MySqlConnection(DBConfiguration.ConnectionString);
return conn;
}
}
}
| 20.789474 | 89 | 0.686076 | [
"MIT"
] | kevinahn7/HairSalon | HairSalon/Models/Database.cs | 397 | C# |
using Ayehu.Sdk.ActivityCreation.Interfaces;
using Ayehu.Sdk.ActivityCreation.Extension;
using System.Text;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Data;
using System.Diagnostics;
namespace Ayehu.Sdk.ActivityCreation
{
public class ActivityClass : IActivity
{
public string HostName;
public string UserName;
public string Password;
public string VMName;
public ICustomActivityResult Execute()
{
StringWriter sw = new StringWriter();
DataTable dt = new DataTable("resultSet");
dt.Columns.Add("Result", typeof(String));
string sResult = "";
string command_path = "VMWare.exe";
DataTable dtParams = new DataTable("Params");
dtParams.Columns.Add("Command");
dtParams.Columns.Add("UserName");
dtParams.Columns.Add("Password");
dtParams.Columns.Add("HostName");
dtParams.Columns.Add("VMName");
DataRow rParams = dtParams.NewRow();
rParams["Command"] = "VMMarkTemplate";
rParams["UserName"] = UserName;
rParams["Password"] = Password;
rParams["HostName"] = HostName;
rParams["VMName"] = VMName;
dtParams.Rows.Add(rParams);
dtParams.WriteXml(sw, XmlWriteMode.WriteSchema, false);
Process prVMWare = new Process();
prVMWare.StartInfo.FileName = command_path;
prVMWare.StartInfo.Arguments = "\"" + sw.ToString().Replace("\"", "\\\"") + "\"";
prVMWare.StartInfo.UseShellExecute = false;
prVMWare.StartInfo.CreateNoWindow = true;
prVMWare.StartInfo.RedirectStandardError = true;
prVMWare.StartInfo.RedirectStandardInput = true;
prVMWare.StartInfo.RedirectStandardOutput = true;
prVMWare.Start();
StreamReader srResult = prVMWare.StandardOutput;
sResult = srResult.ReadToEnd();
srResult.Close();
prVMWare.Close();
if (sResult == "")
{
return this.GenerateActivityResult(dt);
}
else
{
return this.GenerateActivityResult(sResult);
}
}
}
}
| 32.157895 | 94 | 0.569967 | [
"MIT"
] | Ayehu/activities | VMWare/VMMarkTemplate.cs | 2,444 | C# |
/* Copyright (c) Citrix Systems, 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.
*
* 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 HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using XenAdmin.Core;
using XenAPI;
namespace XenAdmin.Controls
{
public class SrPickerLunPerVDIItem : SrPickerVmItem
{
public SrPickerLunPerVDIItem(SR sr, Host aff, VDI[] vdis)
: base(sr, aff, vdis)
{
}
protected override bool CanBeEnabled
{
get
{
if(TheSR.HBALunPerVDI())
return !TheSR.IsBroken(false) && TheSR.CanBeSeenFrom(Affinity);
return base.CanBeEnabled;
}
}
protected override bool UnsupportedSR => false;
}
public class SrPickerMigrateItem : SrPickerItem
{
public SrPickerMigrateItem(SR sr, Host aff, VDI[] vdis)
: base(sr, aff, vdis)
{
}
/// <summary>
/// We can move VDIs to a local SR only if the VDI is attached to VMs
/// that have a home server that can see the SR
/// </summary>
private static bool HomeHostCanSeeTargetSr(VDI vdi, SR targetSr)
{
var vms = vdi.GetVMs();
var homeHosts = (from VM vm in vms
let host = vm.Home()
where host != null
select host).ToList();
return homeHosts.Count > 0 && homeHosts.All(targetSr.CanBeSeenFrom);
}
protected override string DisabledReason
{
get
{
if (ExistingVDILocation())
return Messages.CURRENT_LOCATION;
if (TheSR.IsLocalSR())
{
foreach (var vdi in existingVDIs)
{
var homeHosts = new List<Host>();
var vms = vdi.GetVMs();
foreach (var vm in vms)
{
var homeHost = vm.Home();
if (homeHost != null)
{
homeHosts.Add(homeHost);
if (!TheSR.CanBeSeenFrom(homeHost))
return vm.power_state == vm_power_state.Running
? Messages.SRPICKER_ERROR_LOCAL_SR_MUST_BE_RESIDENT_HOSTS
: string.Format(Messages.SR_CANNOT_BE_SEEN, Helpers.GetName(homeHost));
}
}
if (homeHosts.Count == 0)
return Messages.SR_IS_LOCAL;
}
}
if (!TheSR.CanBeSeenFrom(Affinity))
return TheSR.Connection != null
? string.Format(Messages.SR_CANNOT_BE_SEEN, Affinity == null ? Helpers.GetName(TheSR.Connection) : Helpers.GetName(Affinity))
: Messages.SR_DETACHED;
if (!TheSR.SupportsStorageMigration())
return Messages.UNSUPPORTED_SR_TYPE;
return base.DisabledReason;
}
}
protected override bool CanBeEnabled
{
get
{
return existingVDIs.Length > 0 &&
!ExistingVDILocation() &&
(!TheSR.IsLocalSR() || existingVDIs.All(v => HomeHostCanSeeTargetSr(v, TheSR))) &&
TheSR.SupportsVdiCreate() &&
!TheSR.IsDetached() && TheSR.VdiCreationCanProceed(DiskSize) &&
TheSR.SupportsStorageMigration();
}
}
}
public class SrPickerCopyItem : SrPickerItem
{
public SrPickerCopyItem(SR sr, Host aff, VDI[] vdis)
: base(sr, aff, vdis)
{
}
protected override bool CanBeEnabled =>
!TheSR.IsDetached() && TheSR.SupportsVdiCreate() &&
TheSR.VdiCreationCanProceed(DiskSize);
protected override string DisabledReason
{
get
{
if (TheSR.IsDetached())
return Messages.SR_DETACHED;
return base.DisabledReason;
}
}
}
public class SrPickerMoveItem : SrPickerItem
{
public SrPickerMoveItem(SR sr, Host aff, VDI[] vdis)
: base(sr, aff, vdis)
{
}
protected override bool CanBeEnabled =>
!TheSR.IsDetached() && !ExistingVDILocation() &&
TheSR.SupportsVdiCreate() && TheSR.VdiCreationCanProceed(DiskSize);
protected override string DisabledReason
{
get
{
if (TheSR.IsDetached())
return Messages.SR_DETACHED;
if (ExistingVDILocation())
return Messages.CURRENT_LOCATION;
return base.DisabledReason;
}
}
}
public class SrPickerInstallFromTemplateItem : SrPickerItem
{
public SrPickerInstallFromTemplateItem(SR sr, Host aff, VDI[] vdis)
: base(sr, aff, vdis)
{
}
protected override bool CanBeEnabled =>
TheSR.SupportsVdiCreate() && !TheSR.IsDetached() && TheSR.VdiCreationCanProceed(DiskSize);
protected override string DisabledReason
{
get
{
if (TheSR.IsDetached())
return Messages.SR_DETACHED;
return base.DisabledReason;
}
}
}
public class SrPickerVmItem : SrPickerItem
{
public SrPickerVmItem(SR sr, Host aff, VDI[] vdis)
: base(sr, aff, vdis)
{
}
protected override bool CanBeEnabled =>
TheSR.CanBeSeenFrom(Affinity) &&
TheSR.SupportsVdiCreate() && !TheSR.IsBroken(false) && !TheSR.IsFull() &&
TheSR.VdiCreationCanProceed(DiskSize);
protected override string DisabledReason
{
get
{
if (Affinity == null && !TheSR.shared)
return Messages.SR_IS_LOCAL;
if (!TheSR.CanBeSeenFrom(Affinity))
return TheSR.Connection != null
? string.Format(Messages.SR_CANNOT_BE_SEEN, Affinity == null ? Helpers.GetName(TheSR.Connection) : Helpers.GetName(Affinity))
: Messages.SR_DETACHED;
return base.DisabledReason;
}
}
}
public abstract class SrPickerItem : CustomTreeNode, IComparable<SrPickerItem>
{
public SR TheSR { get; }
public bool Show { get; private set; }
protected readonly Host Affinity;
protected long DiskSize { get; private set; }
protected readonly VDI[] existingVDIs;
protected SrPickerItem(SR sr, Host aff, VDI[] vdis)
{
existingVDIs = vdis ?? new VDI[0];
TheSR = sr;
Affinity = aff;
DiskSize = existingVDIs.Sum(vdi =>
sr.GetSRType(true) == SR.SRTypes.gfs2 ? vdi.physical_utilisation : vdi.virtual_size);
Update();
}
protected virtual bool UnsupportedSR => TheSR.HBALunPerVDI();
protected abstract bool CanBeEnabled { get; }
protected virtual void SetImage()
{
Image = Images.GetImage16For(TheSR);
}
public void UpdateDiskSize(long diskSize)
{
DiskSize = diskSize;
Update();
}
private void Update()
{
Text = TheSR.Name();
SetImage();
if (UnsupportedSR || !TheSR.SupportsVdiCreate() ||
!TheSR.Show(Properties.Settings.Default.ShowHiddenVMs))
return;
if (CanBeEnabled)
{
Description = string.Format(Messages.SRPICKER_DISK_FREE, Util.DiskSizeString(TheSR.FreeSpace(), 2),
Util.DiskSizeString(TheSR.physical_size, 2));
Enabled = true;
Show = true;
}
else
{
Description = DisabledReason;
Enabled = false;
Show = true;
}
}
protected bool ExistingVDILocation()
{
return existingVDIs.Length > 0 && existingVDIs.All(vdi => vdi.SR.opaque_ref == TheSR.opaque_ref);
}
protected virtual string DisabledReason
{
get
{
if (TheSR.IsBroken(false))
return Messages.SR_IS_BROKEN;
if (TheSR.IsFull())
return Messages.SRPICKER_SR_FULL;
if (DiskSize > TheSR.physical_size)
return string.Format(Messages.SR_PICKER_DISK_TOO_BIG, Util.DiskSizeString(DiskSize, 2),
Util.DiskSizeString(TheSR.physical_size, 2));
if (DiskSize > TheSR.FreeSpace())
return string.Format(Messages.SR_PICKER_INSUFFICIENT_SPACE, Util.DiskSizeString(DiskSize, 2),
Util.DiskSizeString(TheSR.FreeSpace(), 2));
if (DiskSize > SR.DISK_MAX_SIZE)
return string.Format(Messages.SR_DISKSIZE_EXCEEDS_DISK_MAX_SIZE,
Util.DiskSizeString(SR.DISK_MAX_SIZE, 0));
return "";
}
}
public int CompareTo(SrPickerItem other)
{
return base.CompareTo(other);
}
protected override int SameLevelSortOrder(CustomTreeNode other)
{
SrPickerItem otherItem = other as SrPickerItem;
if (otherItem == null) //shouldn't ever happen!!!
return -1;
if (!otherItem.Enabled && Enabled)
return -1;
if (otherItem.Enabled && !Enabled)
return 1;
return base.SameLevelSortOrder(otherItem);
}
public static SrPickerItem Create(SR sr, SrPicker.SRPickerType usage, Host aff, VDI[] vdis)
{
switch (usage)
{
case SrPicker.SRPickerType.Migrate:
return new SrPickerMigrateItem(sr, aff, vdis);
case SrPicker.SRPickerType.Copy:
return new SrPickerCopyItem(sr, aff, vdis);
case SrPicker.SRPickerType.Move:
return new SrPickerMoveItem(sr, aff, vdis);
case SrPicker.SRPickerType.InstallFromTemplate:
return new SrPickerInstallFromTemplateItem(sr, aff, vdis);
case SrPicker.SRPickerType.VM:
return new SrPickerVmItem(sr, aff, vdis);
case SrPicker.SRPickerType.LunPerVDI:
return new SrPickerLunPerVDIItem(sr, aff, vdis);
default:
throw new ArgumentException("There is no SRPickerItem for the type: " + usage);
}
}
}
}
| 35.169399 | 150 | 0.521675 | [
"BSD-2-Clause"
] | CitrixChris/xenadmin | XenAdmin/Controls/SrPickerItem.cs | 12,874 | C# |
using Microsoft.Xna.Framework;
using Monocle;
using System.Collections;
using Celeste.Mod.Entities;
using MonoMod.Utils;
using Celeste.Mod.JungleHelper.Components;
using System;
namespace Celeste.Mod.JungleHelper.Entities {
[CustomEntity("JungleHelper/Hawk")]
public class Hawk : Entity {
private enum States {
Wait,
Fling,
Move
}
private static readonly Vector2 spriteOffset = new Vector2(0f, 8f);
private Sprite sprite;
private States state = States.Wait;
private Vector2 flingSpeed;
private float flingAccel;
private float hawkSpeed;
private readonly float speedWithPlayer;
private readonly float speedWithoutPlayer;
private readonly float initialY;
private PlayerCollider playerCollider;
public Hawk(EntityData data, Vector2 levelOffset) : base(data.Position + levelOffset) {
Tag |= Tags.TransitionUpdate;
Position = data.Position + levelOffset;
speedWithPlayer = data.Float("mainSpeed");
speedWithoutPlayer = data.Float("slowerSpeed");
initialY = Y;
Add(sprite = JungleHelperModule.CreateReskinnableSprite(data, "hawk"));
sprite.Play("hover");
sprite.Position = spriteOffset;
sprite.OnFrameChange = delegate {
BirdNPC.FlapSfxCheck(sprite);
};
Collider = new CircleColliderWithRectangles(16);
Add(playerCollider = new PlayerCollider(OnPlayer));
Add(new TransitionListener {
OnOutBegin = delegate {
// make hawk invisible during this
Visible = false;
//if we're transitioning out of a room while still attached to the hawk...
if (state == States.Fling) {
// do the usual throw!
Player player = SceneAs<Level>()?.Tracker.GetEntity<Player>();
if (player != null) {
player.StateMachine.State = 0;
player.DummyGravity = true;
player.DummyFriction = true;
player.ForceCameraUpdate = false;
player.DummyAutoAnimate = true;
playerLaunch(player);
player.Speed = new Vector2(hawkSpeed * 0.7f, 0);
}
};
RemoveSelf();
}
});
}
private void OnPlayer(Player player) {
if ((CollideFirst<Solid>(Position) == null) && (state == States.Wait || state == States.Move)) {
flingSpeed = player.Speed * 0.4f;
flingSpeed.Y = 120f;
flingAccel = 1000f;
player.Speed = Vector2.Zero;
state = States.Fling;
if (hawkSpeed == 0f) {
sprite.Play("throw");
}
Add(new Coroutine(doFlingRoutine(player)));
}
}
private IEnumerator hitboxDelay() {
Collidable = false;
yield return 0.4f;
Collidable = true;
}
public override void Update() {
base.Update();
if (state != States.Wait) {
sprite.Position = Calc.Approach(sprite.Position, spriteOffset, 32f * Engine.DeltaTime);
}
switch (state) {
case States.Move:
// move without player
X += speedWithoutPlayer * Engine.DeltaTime;
// drag hawk towards its initial Y position.
Y = Calc.Approach(Y, initialY, 20f * Engine.DeltaTime);
break;
case States.Wait:
// wait for the player
break;
case States.Fling:
// carry the player: apply the momentum from the player and drag it progressively to 0
if (flingAccel > 0f) {
flingSpeed = Calc.Approach(flingSpeed, Vector2.Zero, flingAccel * Engine.DeltaTime);
}
Position += flingSpeed * Engine.DeltaTime;
break;
}
// don't catch the player if the hawk is inside a solid.
playerCollider.Active = !CollideCheck<Solid>();
if (X >= (SceneAs<Level>().Bounds.Right + 5)) {
// bird is off-screen! drop the player.
RemoveSelf();
Player player = SceneAs<Level>().Tracker.GetEntity<Player>();
if (player != null) {
if (state == States.Fling && player.StateMachine.State == 11) {
player.StateMachine.State = 0;
player.DummyGravity = true;
player.DummyFriction = true;
player.ForceCameraUpdate = false;
player.DummyAutoAnimate = true;
}
}
}
}
private IEnumerator doFlingRoutine(Player player) {
sprite.Play("fly");
hawkSpeed = 0;
sprite.Scale.X = 1f;
while (state == States.Fling) {
yield return null;
// stop the fling when player dies.
if (player.Dead)
break;
// drag hawk towards its initial Y position.
Y = Calc.Approach(Y, initialY, 20f * Engine.DeltaTime);
// make speed approach the target speed.
if (hawkSpeed != speedWithPlayer) {
hawkSpeed = Calc.Approach(hawkSpeed, speedWithPlayer, speedWithPlayer / 10);
}
X += hawkSpeed * Engine.DeltaTime;
// make sure the player is in a dummy state.
player.StateMachine.State = 11;
player.DummyMoving = false;
player.DummyMaxspeed = false;
player.DummyGravity = false;
player.DummyFriction = false;
player.ForceCameraUpdate = true;
player.DummyAutoAnimate = false;
player.Facing = Facings.Right;
player.Sprite.Play("fallSlow_carry");
// move the player.
bool hitSomething = false;
player.MoveToX(X, collision => hitSomething = true);
player.MoveToY(Y + 16, collision => hitSomething = true);
if (hitSomething) {
// player hit something while getting moved! drop them.
player.StateMachine.State = 0;
break;
}
if (Input.Jump.Pressed) {
// player escapes!
player.StateMachine.State = 0;
playerLaunch(player);
player.Speed = new Vector2(hawkSpeed * 0.7f, 0);
break;
}
if ((Input.DashPressed || Input.CrouchDashPressed) && player.CanDash) {
// player dashes out of hawk, let them do that.
player.StateMachine.State = player.StartDash();
break;
}
}
if (!player.Dead) {
// reset dummy settings to default.
player.DummyMoving = false;
player.DummyMaxspeed = true;
player.DummyGravity = true;
player.DummyFriction = true;
player.ForceCameraUpdate = false;
player.DummyAutoAnimate = true;
}
// get back to the "moving" state.
Add(new Coroutine(hitboxDelay()));
Add(new Coroutine(moveRoutine()));
}
private void playerLaunch(Player player) {
DynData<Player> playerData = new DynData<Player>(player);
player.StateMachine.State = 0;
playerData.Set("forceMoveX", 1);
playerData.Set("forceMoveXTimer", 0.2f);
playerData.Set("launched", true);
}
private IEnumerator moveRoutine() {
sprite.Play("fly");
sprite.Rotation = 0f;
sprite.Scale = Vector2.One;
X += 80f * Engine.DeltaTime;
yield return 0.1f;
state = States.Move;
}
}
} | 37.373913 | 108 | 0.496394 | [
"MIT"
] | Jackal-Celeste/JungleHelper | Code/Entities/Hawk.cs | 8,598 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using JetBrains.Annotations;
using JetBrains.Application.FileSystemTracker;
using JetBrains.Collections.Viewable;
using JetBrains.Diagnostics;
using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.ProjectModel.Impl;
using JetBrains.ProjectModel.Properties;
using JetBrains.ProjectModel.Properties.Managed;
using JetBrains.Rd.Base;
using JetBrains.ReSharper.Plugins.Unity.Core.ProjectModel;
using JetBrains.ReSharper.Plugins.Unity.Core.ProjectModel.Caches;
using JetBrains.ReSharper.Resources.Shell;
using JetBrains.Util;
using JetBrains.Util.Logging;
using Vestris.ResourceLib;
namespace JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration
{
[SolutionComponent]
public class UnityVersion
{
private readonly UnityProjectFileCacheProvider myUnityProjectFileCache;
private readonly ISolution mySolution;
private readonly IFileSystemTracker myFileSystemTracker;
private readonly VirtualFileSystemPath mySolutionDirectory;
private Version myVersionFromProjectVersionTxt;
private Version myVersionFromEditorInstanceJson;
private static readonly ILogger ourLogger = Logger.GetLogger<UnityVersion>();
public readonly ViewableProperty<Version> ActualVersionForSolution = new ViewableProperty<Version>(new Version(0,0));
public UnityVersion(UnityProjectFileCacheProvider unityProjectFileCache,
ISolution solution, IFileSystemTracker fileSystemTracker, Lifetime lifetime,
UnitySolutionTracker unitySolutionTracker)
{
myUnityProjectFileCache = unityProjectFileCache;
mySolution = solution;
myFileSystemTracker = fileSystemTracker;
// SolutionDirectory isn't absolute in tests, and will throw if used with FileSystemTracker
mySolutionDirectory = solution.SolutionDirectory;
if (!mySolutionDirectory.IsAbsolute)
mySolutionDirectory = solution.SolutionDirectory.ToAbsolutePath(FileSystemUtil.GetCurrentDirectory().ToVirtualFileSystemPath());
unitySolutionTracker.IsUnityProjectFolder.WhenTrue(lifetime, SetActualVersionForSolution);
unitySolutionTracker.HasUnityReference.WhenTrue(lifetime, SetActualVersionForSolution);
}
private void SetActualVersionForSolution(Lifetime lt)
{
var projectVersionTxtPath =
mySolutionDirectory.Combine("ProjectSettings/ProjectVersion.txt");
myFileSystemTracker.AdviseFileChanges(lt,
projectVersionTxtPath,
_ =>
{
myVersionFromProjectVersionTxt = TryGetVersionFromProjectVersion(projectVersionTxtPath);
UpdateActualVersionForSolution();
});
myVersionFromProjectVersionTxt = TryGetVersionFromProjectVersion(projectVersionTxtPath);
var editorInstanceJsonPath = mySolutionDirectory.Combine("Library/EditorInstance.json");
myFileSystemTracker.AdviseFileChanges(lt,
editorInstanceJsonPath,
_ =>
{
myVersionFromEditorInstanceJson =
TryGetApplicationPathFromEditorInstanceJson(editorInstanceJsonPath);
UpdateActualVersionForSolution();
});
myVersionFromEditorInstanceJson =
TryGetApplicationPathFromEditorInstanceJson(editorInstanceJsonPath);
UpdateActualVersionForSolution();
}
[NotNull]
public Version GetActualVersion([CanBeNull] IProject project)
{
// Project might be null for e.g. decompiled files
if (project == null)
return new Version(0, 0);
var version = myUnityProjectFileCache.GetUnityVersion(project);
return version ?? GetActualVersionForSolution();
}
[NotNull]
private Version GetActualVersionForSolution()
{
if (myVersionFromEditorInstanceJson != null)
return myVersionFromEditorInstanceJson;
if (myVersionFromProjectVersionTxt != null)
return myVersionFromProjectVersionTxt;
if (mySolution.IsVirtualSolution())
return new Version(0, 0);
foreach (var project in GetTopLevelProjectWithReadLock(mySolution))
{
var version = myUnityProjectFileCache.GetUnityVersion(project);
if (version != null)
return version;
}
return GetVersionForTests(mySolution);
}
[NotNull]
public VirtualFileSystemPath GetActualAppPathForSolution()
{
if (mySolution.IsVirtualSolution())
return VirtualFileSystemPath.GetEmptyPathFor(InteractionContext.SolutionContext);
foreach (var project in GetTopLevelProjectWithReadLock(mySolution))
{
var path = myUnityProjectFileCache.GetAppPath(project);
if (path != null)
return path;
}
return VirtualFileSystemPath.GetEmptyPathFor(InteractionContext.SolutionContext);
}
[CanBeNull]
private Version TryGetApplicationPathFromEditorInstanceJson(VirtualFileSystemPath editorInstanceJsonPath)
{
var val = EditorInstanceJson.TryGetValue(editorInstanceJsonPath, "version");
return val != null ? Parse(val) : null;
}
[CanBeNull]
private Version TryGetVersionFromProjectVersion(VirtualFileSystemPath projectVersionTxtPath)
{
// Get the version from ProjectSettings/ProjectVersion.txt
if (!projectVersionTxtPath.ExistsFile)
return null;
var text = projectVersionTxtPath.ReadAllText2().Text;
var match = Regex.Match(text, @"^m_EditorVersion:\s+(?<version>.*)\s*$", RegexOptions.Multiline);
var groups = match.Groups;
return match.Success ? Parse(groups["version"].Value) : null;
}
private static Version GetVersionForTests(ISolution solution)
{
// The project file data provider/cache doesn't work in tests, because there is no .csproj file we can parse.
// Instead, pull the version directly from the project defines in the project model. We can't rely on this
// as our main strategy because Unity doesn't write defines for Release configuration (another reason we for
// us to hide the project configuration selector)
var unityVersion = new Version(0, 0);
foreach (var project in GetTopLevelProjectWithReadLock(solution))
{
foreach (var configuration in project.ProjectProperties.GetActiveConfigurations<IManagedProjectConfiguration>())
{
// Get the version define from the project configuration, if set. The solution might be initialised
// before the test aspect attribute has a chance to update the project configuration, so fall back
// to the properties collection.
var defineConstants = configuration.DefineConstants ?? string.Empty;
unityVersion = UnityProjectFileCacheProvider.GetVersionFromDefines(defineConstants, unityVersion);
if (unityVersion.Major == 0)
{
configuration.PropertiesCollection.TryGetValue("DefineConstants", out var defineConstantsProp);
unityVersion =
UnityProjectFileCacheProvider.GetVersionFromDefines(defineConstantsProp ?? string.Empty,
unityVersion);
}
}
}
return unityVersion;
}
private static ICollection<IProject> GetTopLevelProjectWithReadLock(ISolution solution)
{
ICollection<IProject> projects;
using (ReadLockCookie.Create())
{
projects = solution.GetTopLevelProjects();
}
return projects;
}
[CanBeNull]
public static Version Parse(string input)
{
if (string.IsNullOrEmpty(input))
return null;
const string pattern = @"(?<major>\d+)\.(?<minor>\d+)\.(?<build>\d+)(?<type>[a-z])(?<revision>\d+)";
var match = Regex.Match(input, pattern);
var groups = match.Groups;
Version version = null;
if (match.Success)
{
var typeWithRevision = "0";
try
{
var typeChar = groups["type"].Value.ToCharArray()[0];
var shiftedChar = 16 + typeChar; // Because `f1` = `1021` and `b10` = `9810`, which will break sorting
var revision = Convert.ToInt32(groups["revision"].Value);
typeWithRevision = shiftedChar.ToString("D3") + revision.ToString("D3");
}
catch (Exception e)
{
ourLogger.Error($"Unable to parse part of version. type={groups["type"].Value} revision={groups["revision"].Value}", e);
}
version = Version.Parse($"{groups["major"].Value}.{groups["minor"].Value}.{groups["build"].Value}.{typeWithRevision}");
}
return version;
}
public static string VersionToString([NotNull] Version version)
{
if (version == null)
throw new ArgumentNullException(nameof(version));
var type = string.Empty;
var rev = string.Empty;
try
{
var revisionString = version.Revision.ToString(); // first 3 is char, next 1+ ones - revision
if (revisionString.Length > 3)
{
var charValue = Convert.ToInt32(revisionString.Substring(0, 3)) - 16;
type = ((char)charValue).ToString();
rev = Convert.ToInt32(revisionString.Substring(3)).ToString();
}
}
catch (Exception e)
{
ourLogger.Error($"Unable do VersionToString. Input version={version}", e);
}
var build = version.Build >= 0 ? $".{version.Build}" : string.Empty;
return $"{version.Major}.{version.Minor}{build}{type}{rev}";
}
public static bool RequiresRiderPackage(Version version)
{
return version >= new Version(2019,2);
}
private static ConcurrentDictionary<VirtualFileSystemPath, Version> myUnityPathToVersion = new ConcurrentDictionary<VirtualFileSystemPath, Version>();
public static Version GetVersionByAppPath(VirtualFileSystemPath appPath)
{
if (appPath == null || appPath.Exists == FileSystemPath.Existence.Missing)
return null;
return myUnityPathToVersion.GetOrAdd(appPath, p => GetVersionByAppPathInternal(p));
}
private static Version GetVersionByAppPathInternal(VirtualFileSystemPath appPath)
{
Version version = null;
ourLogger.CatchWarn(() => // RIDER-23674
{
switch (PlatformUtil.RuntimePlatform)
{
case PlatformUtil.Platform.Windows:
ourLogger.CatchWarn(() =>
{
var fileVersion = FileVersionInfo.GetVersionInfo(appPath.FullPath).FileVersion;
if (!string.IsNullOrEmpty(fileVersion))
version = Version.Parse(Version.Parse(fileVersion).ToString(3));
});
var resource = new VersionResource();
resource.LoadFrom(appPath.FullPath);
var unityVersionList = resource.Resources.Values.OfType<StringFileInfo>()
.Where(c => c.Default.Strings.Keys.Any(b => b == "Unity Version")).ToArray();
if (unityVersionList.Any())
{
var unityVersion = unityVersionList.First().Default.Strings["Unity Version"].StringValue;
version = Parse(unityVersion);
}
break;
case PlatformUtil.Platform.MacOsX:
var infoPlistPath = appPath.Combine("Contents/Info.plist");
if (infoPlistPath.ExistsFile)
{
var docs = XDocument.Load(infoPlistPath.FullPath);
var keyValuePairs = docs.Descendants("dict")
.SelectMany(d => d.Elements("key").Zip(d.Elements().Where(e => e.Name != "key"),
(k, v) => new {Key = k, Value = v}))
.GroupBy(x => x.Key.Value)
.Select(g =>
g.First()) // avoid exception An item with the same key has already been added.
.ToDictionary(i => i.Key.Value, i => i.Value.Value);
version = Parse(keyValuePairs["CFBundleVersion"]);
}
break;
case PlatformUtil.Platform.Linux:
version = Parse(appPath.FullPath); // parse from path
break;
}
});
return version;
}
public void UpdateActualVersionForSolution()
{
ActualVersionForSolution.SetValue(GetActualVersionForSolution());
}
}
} | 44.408805 | 158 | 0.591913 | [
"Apache-2.0"
] | rwx788/resharper-unity | resharper/resharper-unity/src/Unity/UnityEditorIntegration/UnityVersion.cs | 14,122 | C# |
/*
The MIT License (MIT)
Copyright (c) 2019 - Marcelo O. Mendes
All rights reserved.
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 Cardinal.ClickSign.Enumerators
{
/// <summary>
/// Enumerador com os tipos de status de validação.
/// </summary>
public enum SignatureValidationStatus
{
/// <summary>
/// Desconhecido.
/// </summary>
Unknow,
/// <summary>
/// Conferido.
/// </summary>
Conferred,
/// <summary>
/// CPF não encontrato.
/// </summary>
CpfNotFound,
/// <summary>
/// CPF divergente.
/// </summary>
Divergent
}
}
| 29.910714 | 78 | 0.688358 | [
"MIT"
] | kandrakah/Cardinal.ClickSign | Cardinal.ClickSign/Enumerators/SignatureValidationStatus.cs | 1,680 | C# |
using System;
using System.IO;
using System.Text;
using System.Buffers;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Net.Http.Headers;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
namespace Lib.AspNetCore.Mvc.Ndjson.NewtonsoftJson
{
internal class NewtonsoftNdjsonWriterFactory : INdjsonWriterFactory
{
private class NewtonsoftNdjsonArrayPool : IArrayPool<char>
{
private readonly ArrayPool<char> _inner;
public NewtonsoftNdjsonArrayPool(ArrayPool<char> inner)
{
if (inner == null)
{
throw new ArgumentNullException(nameof(inner));
}
_inner = inner;
}
public char[] Rent(int minimumLength)
{
return _inner.Rent(minimumLength);
}
public void Return(char[] array)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
_inner.Return(array);
}
}
private class NewtonsoftNdjsonWriter : INdjsonWriter
{
private readonly TextWriter _textResponseStreamWriter;
private readonly JsonTextWriter _jsonResponseStreamWriter;
private readonly JsonSerializer _jsonSerializer;
public NewtonsoftNdjsonWriter(TextWriter textResponseStreamWriter, JsonSerializerSettings jsonSerializerSettings, NewtonsoftNdjsonArrayPool jsonArrayPool)
{
_textResponseStreamWriter = textResponseStreamWriter;
_jsonResponseStreamWriter = new JsonTextWriter(textResponseStreamWriter)
{
ArrayPool = jsonArrayPool,
CloseOutput = false,
AutoCompleteOnClose = false
};
_jsonSerializer = JsonSerializer.Create(jsonSerializerSettings);
}
public Task WriteAsync(object value)
{
return WriteAsync(value, CancellationToken.None);
}
public async Task WriteAsync(object value, CancellationToken cancellationToken)
{
_jsonSerializer.Serialize(_jsonResponseStreamWriter, value);
await _textResponseStreamWriter.WriteAsync("\n");
await _textResponseStreamWriter.FlushAsync();
}
public void Dispose()
{
_textResponseStreamWriter?.Dispose();
((IDisposable)_jsonResponseStreamWriter)?.Dispose();
}
}
private static readonly string CONTENT_TYPE = new MediaTypeHeaderValue("application/x-ndjson")
{
Encoding = Encoding.UTF8
}.ToString();
private readonly IHttpResponseStreamWriterFactory _httpResponseStreamWriterFactory;
private readonly MvcNewtonsoftJsonOptions _options;
private readonly NewtonsoftNdjsonArrayPool _jsonArrayPool;
public NewtonsoftNdjsonWriterFactory(IHttpResponseStreamWriterFactory httpResponseStreamWriterFactory, IOptions<MvcNewtonsoftJsonOptions> options, ArrayPool<char> innerJsonArrayPool)
{
_httpResponseStreamWriterFactory = httpResponseStreamWriterFactory ?? throw new ArgumentNullException(nameof(httpResponseStreamWriterFactory));
_options = options?.Value ?? throw new ArgumentNullException(nameof(options));
if (innerJsonArrayPool == null)
{
throw new ArgumentNullException(nameof(innerJsonArrayPool));
}
_jsonArrayPool = new NewtonsoftNdjsonArrayPool(innerJsonArrayPool);
}
public INdjsonWriter CreateWriter(ActionContext context, IStatusCodeActionResult result)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (result == null)
{
throw new ArgumentNullException(nameof(result));
}
HttpResponse response = context.HttpContext.Response;
response.ContentType = CONTENT_TYPE;
if (result.StatusCode != null)
{
response.StatusCode = result.StatusCode.Value;
}
DisableResponseBuffering(context.HttpContext);
return new NewtonsoftNdjsonWriter(_httpResponseStreamWriterFactory.CreateWriter(response.Body, Encoding.UTF8), _options.SerializerSettings, _jsonArrayPool);
}
private static void DisableResponseBuffering(HttpContext context)
{
IHttpResponseBodyFeature responseBodyFeature = context.Features.Get<IHttpResponseBodyFeature>();
if (responseBodyFeature != null)
{
responseBodyFeature.DisableBuffering();
}
}
}
}
| 35.082192 | 190 | 0.625732 | [
"MIT"
] | tpeczek/Lib.AspNetCore.Mvc.Ndjson | Lib.AspNetCore.Mvc.Ndjson.NewtonsoftJson/NewtonsoftNdjsonWriterFactory.cs | 5,124 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 26.11.2020.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Add.Complete.Int16.NullableSingle{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Int16;
using T_DATA2 =System.Nullable<System.Single>;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_001__fields
public static class TestSet_001__fields
{
private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2";
private const string c_NameOf__COL_DATA1 ="COL_SMALLINT";
private const string c_NameOf__COL_DATA2 ="COL2_FLOAT";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("TEST_ID")]
public System.Int64? TEST_ID { get; set; }
[Column(c_NameOf__COL_DATA1)]
public T_DATA1 COL_DATA1 { get; set; }
[Column(c_NameOf__COL_DATA2)]
public T_DATA2 COL_DATA2 { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_DATA1 c_value1=7;
T_DATA2 c_value2=4;
System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2);
Assert.AreEqual
(11,
c_value1+c_value2);
var recs=db.testTable.Where(r => (r.COL_DATA1+r.COL_DATA2)==11 && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_value1,
r.COL_DATA1);
Assert.AreEqual
(c_value2,
r.COL_DATA2);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE ((CAST(").N("t",c_NameOf__COL_DATA1).T(" AS FLOAT) + ").N("t",c_NameOf__COL_DATA2).T(") = 11.0) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_001
//-----------------------------------------------------------------------
private static System.Int64 Helper__InsertRow(MyContext db,
T_DATA1 valueForColData1,
T_DATA2 valueForColData2)
{
var newRecord=new MyContext.TEST_RECORD();
newRecord.COL_DATA1 =valueForColData1;
newRecord.COL_DATA2 =valueForColData2;
db.testTable.Add(newRecord);
db.SaveChanges();
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL()
.T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL()
.T("RETURNING ").N("TEST_ID").EOL()
.T("INTO ").P("p2").T(";"));
Assert.IsTrue
(newRecord.TEST_ID.HasValue);
Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value);
return newRecord.TEST_ID.Value;
}//Helper__InsertRow
};//class TestSet_001__fields
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Add.Complete.Int16.NullableSingle
| 28.942308 | 173 | 0.55526 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/Add/Complete/Int16/NullableSingle/TestSet_001__fields.cs | 4,517 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Fp_attendance.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Fp_attendance.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 39.638889 | 180 | 0.588648 | [
"MIT"
] | RoisulIslamRumi/Fingerpring-Attendance-System | Gui/Properties/Resources.Designer.cs | 2,856 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// </auto-generated>
namespace Microsoft.Azure.Management.Network.Fluent.Models
{
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// ExpressRouteLink
/// </summary>
/// <remarks>
/// ExpressRouteLink child resource definition.
/// </remarks>
[Rest.Serialization.JsonTransformation]
public partial class ExpressRouteLinkInner : Management.ResourceManager.Fluent.SubResource
{
/// <summary>
/// Initializes a new instance of the ExpressRouteLinkInner class.
/// </summary>
public ExpressRouteLinkInner()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ExpressRouteLinkInner class.
/// </summary>
/// <param name="routerName">Name of Azure router associated with
/// physical port.</param>
/// <param name="interfaceName">Name of Azure router interface.</param>
/// <param name="patchPanelId">Mapping between physical port to patch
/// panel port.</param>
/// <param name="rackId">Mapping of physical patch panel to
/// rack.</param>
/// <param name="connectorType">Physical fiber port type. Possible
/// values include: 'LC', 'SC'</param>
/// <param name="adminState">Administrative state of the physical port.
/// Possible values include: 'Enabled', 'Disabled'</param>
/// <param name="provisioningState">The provisioning state of the
/// express route link resource. Possible values include: 'Succeeded',
/// 'Updating', 'Deleting', 'Failed'</param>
/// <param name="macSecConfig">MacSec configuration.</param>
/// <param name="name">Name of child port resource that is unique among
/// child port resources of the parent.</param>
/// <param name="etag">A unique read-only string that changes whenever
/// the resource is updated.</param>
public ExpressRouteLinkInner(string id = default(string), string routerName = default(string), string interfaceName = default(string), string patchPanelId = default(string), string rackId = default(string), ExpressRouteLinkConnectorType connectorType = default(ExpressRouteLinkConnectorType), ExpressRouteLinkAdminState adminState = default(ExpressRouteLinkAdminState), ProvisioningState provisioningState = default(ProvisioningState), ExpressRouteLinkMacSecConfig macSecConfig = default(ExpressRouteLinkMacSecConfig), string name = default(string), string etag = default(string))
: base(id)
{
RouterName = routerName;
InterfaceName = interfaceName;
PatchPanelId = patchPanelId;
RackId = rackId;
ConnectorType = connectorType;
AdminState = adminState;
ProvisioningState = provisioningState;
MacSecConfig = macSecConfig;
Name = name;
Etag = etag;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets name of Azure router associated with physical port.
/// </summary>
[JsonProperty(PropertyName = "properties.routerName")]
public string RouterName { get; private set; }
/// <summary>
/// Gets name of Azure router interface.
/// </summary>
[JsonProperty(PropertyName = "properties.interfaceName")]
public string InterfaceName { get; private set; }
/// <summary>
/// Gets mapping between physical port to patch panel port.
/// </summary>
[JsonProperty(PropertyName = "properties.patchPanelId")]
public string PatchPanelId { get; private set; }
/// <summary>
/// Gets mapping of physical patch panel to rack.
/// </summary>
[JsonProperty(PropertyName = "properties.rackId")]
public string RackId { get; private set; }
/// <summary>
/// Gets physical fiber port type. Possible values include: 'LC', 'SC'
/// </summary>
[JsonProperty(PropertyName = "properties.connectorType")]
public ExpressRouteLinkConnectorType ConnectorType { get; private set; }
/// <summary>
/// Gets or sets administrative state of the physical port. Possible
/// values include: 'Enabled', 'Disabled'
/// </summary>
[JsonProperty(PropertyName = "properties.adminState")]
public ExpressRouteLinkAdminState AdminState { get; set; }
/// <summary>
/// Gets the provisioning state of the express route link resource.
/// Possible values include: 'Succeeded', 'Updating', 'Deleting',
/// 'Failed'
/// </summary>
[JsonProperty(PropertyName = "properties.provisioningState")]
public ProvisioningState ProvisioningState { get; private set; }
/// <summary>
/// Gets or sets macSec configuration.
/// </summary>
[JsonProperty(PropertyName = "properties.macSecConfig")]
public ExpressRouteLinkMacSecConfig MacSecConfig { get; set; }
/// <summary>
/// Gets or sets name of child port resource that is unique among child
/// port resources of the parent.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Gets a unique read-only string that changes whenever the resource
/// is updated.
/// </summary>
[JsonProperty(PropertyName = "etag")]
public string Etag { get; private set; }
}
}
| 42.427586 | 588 | 0.633453 | [
"MIT"
] | Azure/azure-libraries-for-net | src/ResourceManagement/Network/Generated/Models/ExpressRouteLinkInner.cs | 6,152 | C# |
/*
* Copyright 2021 Swisscom Trust Services (Schweiz) AG
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace AIS.Utils
{
public static class ConfigParser
{
public static string GetStringNotNull(string propertyName, string nonNullableString)
{
if (string.IsNullOrEmpty(nonNullableString))
{
throw new ArgumentNullException($"Invalid configuration. {propertyName} is missing or empty");
}
return nonNullableString;
}
public static int GetIntNotNull(string propertyName, string value)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException($"Invalid configuration. {propertyName} is missing or empty");
}
return int.Parse(value);
}
}
}
| 31.883721 | 110 | 0.66229 | [
"Apache-2.0"
] | SwisscomTrustServices/itext-dotnet-ais | AisClient/AIS/Utils/ConfigParser.cs | 1,373 | C# |
using System.ComponentModel;
namespace BinksSwitch.Network.Entities
{
public enum Protocol
{
[Description("TCP")] Tcp,
[Description("UDP")] Udp,
[Description("ICMPv4")] Icmpv4,
[Description("ICMPv6")] Icmpv6,
[Description("IPv4")] Ipv4,
[Description("IPv6")] Ipv6,
[Description("ARP")] Arp,
[Description("LLDP")] Lldp
}
}
| 23.529412 | 39 | 0.58 | [
"MIT"
] | Sibyx/BinksSwitch | BinksSwitch/Network/Entities/Protocol.cs | 402 | C# |
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OptionsDemo.Services
{
public interface IOrderServices
{
int ShowMaxOrderCount();
}
/// <summary>
/// 选项
/// </summary>
public class OrderServices : IOrderServices
{
//readonly IOptions<OrderServicesOptions> servicesOptions;
// IOptionsSnapshot 数据热更新,感知配置的数据变化,适用于范围内单例
readonly IOptionsSnapshot<OrderServicesOptions> servicesOptions;
public OrderServices(IOptionsSnapshot<OrderServicesOptions> _servicesOptions)
{
servicesOptions = _servicesOptions;
}
public int ShowMaxOrderCount()
{
return servicesOptions.Value.MaxOrderCount;
}
}
public class OrderServicesOptions
{
public int MaxOrderCount { get; set; } = 100;
}
}
| 26.428571 | 85 | 0.669189 | [
"MIT"
] | xiaoMaPrincess/CodeSharing | CodeSharing/OptionsDemo/Services/OrderServices.cs | 979 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StandardRetryStream.cs" company="Naos Project">
// Copyright (c) Naos Project 2019. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.Database.Domain
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Naos.CodeAnalysis.Recipes;
using Naos.Recipes.RunWithRetry;
using OBeautifulCode.Assertion.Recipes;
/// <summary>
/// Wrapping stream to execute each operation against the backing stream with retry logic per the specified inputs.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = NaosSuppressBecause.CA1711_IdentifiersShouldNotHaveIncorrectSuffix_TypeNameAddedAsSuffixForTestsWhereTypeIsPrimaryConcern)]
public class StandardRetryStream : StandardStreamBase
{
private readonly IStandardStream backingStream;
private readonly int retryCount;
private readonly TimeSpan backOffDelay;
/// <summary>
/// Initializes a new instance of the <see cref="StandardRetryStream"/> class.
/// </summary>
/// <param name="backingStream">The backing stream.</param>
/// <param name="retryCount">The retry count.</param>
/// <param name="backOffDelay">The back off delay.</param>
public StandardRetryStream(
IStandardStream backingStream,
int retryCount,
TimeSpan backOffDelay)
: base(
backingStream.Name,
backingStream.SerializerFactory,
backingStream.DefaultSerializerRepresentation,
backingStream.DefaultSerializationFormat,
backingStream.ResourceLocatorProtocols)
{
backingStream.MustForArg(nameof(backingStream)).NotBeNull();
this.backingStream = backingStream;
this.retryCount = retryCount;
this.backOffDelay = backOffDelay;
}
/// <inheritdoc />
public override long Execute(
StandardGetNextUniqueLongOp operation)
{
var result = Run.WithRetry(
() => this.backingStream.Execute(operation),
this.retryCount,
this.backOffDelay);
return result;
}
/// <inheritdoc />
public override StreamRecord Execute(
StandardGetLatestRecordOp operation)
{
var result = Run.WithRetry(
() => this.backingStream.Execute(operation),
this.retryCount,
this.backOffDelay);
return result;
}
/// <inheritdoc />
public override TryHandleRecordResult Execute(
StandardTryHandleRecordOp operation)
{
var result = Run.WithRetry(
() => this.backingStream.Execute(operation),
this.retryCount,
this.backOffDelay);
return result;
}
/// <inheritdoc />
public override PutRecordResult Execute(
StandardPutRecordOp operation)
{
var result = Run.WithRetry(
() => this.backingStream.Execute(operation),
this.retryCount,
this.backOffDelay);
return result;
}
/// <inheritdoc />
public override IReadOnlyCollection<long> Execute(
StandardGetInternalRecordIdsOp operation)
{
var result = Run.WithRetry(
() => this.backingStream.Execute(operation),
this.retryCount,
this.backOffDelay);
return result;
}
/// <inheritdoc />
public override void Execute(
StandardUpdateHandlingStatusForStreamOp operation)
{
Run.WithRetry(
() => this.backingStream.Execute(operation),
this.retryCount,
this.backOffDelay);
}
/// <inheritdoc />
public override IReadOnlyDictionary<long, HandlingStatus> Execute(
StandardGetHandlingStatusOp operation)
{
var result = Run.WithRetry(
() => this.backingStream.Execute(operation),
this.retryCount,
this.backOffDelay);
return result;
}
/// <inheritdoc />
public override IReadOnlyList<StreamRecordHandlingEntry> Execute(
StandardGetHandlingHistoryOp operation)
{
var result = Run.WithRetry(
() => this.backingStream.Execute(operation),
this.retryCount,
this.backOffDelay);
return result;
}
/// <inheritdoc />
public override void Execute(
StandardUpdateHandlingStatusForRecordOp operation)
{
Run.WithRetry(
() => this.backingStream.Execute(operation),
this.retryCount,
this.backOffDelay);
}
/// <inheritdoc />
public override IReadOnlyCollection<StringSerializedIdentifier> Execute(
StandardGetDistinctStringSerializedIdsOp operation)
{
var result = Run.WithRetry(
() => this.backingStream.Execute(operation),
this.retryCount,
this.backOffDelay);
return result;
}
/// <inheritdoc />
public override string Execute(
StandardGetLatestStringSerializedObjectOp operation)
{
var result = Run.WithRetry(
() => this.backingStream.Execute(operation),
this.retryCount,
this.backOffDelay);
return result;
}
/// <inheritdoc />
public override CreateStreamResult Execute(
StandardCreateStreamOp operation)
{
var result = Run.WithRetry(
() => this.backingStream.Execute(operation),
this.retryCount,
this.backOffDelay);
return result;
}
/// <inheritdoc />
public override void Execute(
StandardDeleteStreamOp operation)
{
Run.WithRetry(
() => this.backingStream.Execute(operation),
this.retryCount,
this.backOffDelay);
}
/// <inheritdoc />
public override void Execute(
StandardPruneStreamOp operation)
{
Run.WithRetry(
() => this.backingStream.Execute(operation),
this.retryCount,
this.backOffDelay);
}
/// <inheritdoc />
public override IStreamRepresentation StreamRepresentation => this.backingStream.StreamRepresentation;
}
}
| 33.21028 | 230 | 0.550303 | [
"MIT"
] | NaosFramework/Naos.Database | Naos.Database.Domain/Protocols/Classes/Stream/Standard/StandardRetryStream.cs | 7,109 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Text.RegularExpressions
{
/// <summary>
/// RegexCompiler translates a block of RegexCode to MSIL, and creates a
/// subclass of the RegexRunner type.
/// </summary>
internal abstract class RegexCompiler
{
private static readonly FieldInfo s_runtextbegField = RegexRunnerField("runtextbeg");
private static readonly FieldInfo s_runtextendField = RegexRunnerField("runtextend");
private static readonly FieldInfo s_runtextstartField = RegexRunnerField("runtextstart");
private static readonly FieldInfo s_runtextposField = RegexRunnerField("runtextpos");
private static readonly FieldInfo s_runtextField = RegexRunnerField("runtext");
private static readonly FieldInfo s_runtrackposField = RegexRunnerField("runtrackpos");
private static readonly FieldInfo s_runtrackField = RegexRunnerField("runtrack");
private static readonly FieldInfo s_runstackposField = RegexRunnerField("runstackpos");
private static readonly FieldInfo s_runstackField = RegexRunnerField("runstack");
protected static readonly FieldInfo s_runtrackcountField = RegexRunnerField("runtrackcount");
private static readonly MethodInfo s_doubleStackMethod = RegexRunnerMethod("DoubleStack");
private static readonly MethodInfo s_doubleTrackMethod = RegexRunnerMethod("DoubleTrack");
private static readonly MethodInfo s_captureMethod = RegexRunnerMethod("Capture");
private static readonly MethodInfo s_transferCaptureMethod = RegexRunnerMethod("TransferCapture");
private static readonly MethodInfo s_uncaptureMethod = RegexRunnerMethod("Uncapture");
private static readonly MethodInfo s_isMatchedMethod = RegexRunnerMethod("IsMatched");
private static readonly MethodInfo s_matchLengthMethod = RegexRunnerMethod("MatchLength");
private static readonly MethodInfo s_matchIndexMethod = RegexRunnerMethod("MatchIndex");
private static readonly MethodInfo s_isBoundaryMethod = RegexRunnerMethod("IsBoundary");
private static readonly MethodInfo s_isECMABoundaryMethod = RegexRunnerMethod("IsECMABoundary");
private static readonly MethodInfo s_crawlposMethod = RegexRunnerMethod("Crawlpos");
private static readonly MethodInfo s_charInClassMethod = RegexRunnerMethod("CharInClass");
private static readonly MethodInfo s_checkTimeoutMethod = RegexRunnerMethod("CheckTimeout");
#if DEBUG
private static readonly MethodInfo s_dumpStateM = RegexRunnerMethod("DumpState");
#endif
private static readonly MethodInfo s_charIsDigitMethod = typeof(char).GetMethod("IsDigit", new Type[] { typeof(char) })!;
private static readonly MethodInfo s_charIsWhiteSpaceMethod = typeof(char).GetMethod("IsWhiteSpace", new Type[] { typeof(char) })!;
private static readonly MethodInfo s_charGetUnicodeInfo = typeof(char).GetMethod("GetUnicodeCategory", new Type[] { typeof(char) })!;
private static readonly MethodInfo s_charToLowerInvariantMethod = typeof(char).GetMethod("ToLowerInvariant", new Type[] { typeof(char) })!;
private static readonly MethodInfo s_cultureInfoGetCurrentCultureMethod = typeof(CultureInfo).GetMethod("get_CurrentCulture")!;
private static readonly MethodInfo s_cultureInfoGetTextInfoMethod = typeof(CultureInfo).GetMethod("get_TextInfo")!;
#if DEBUG
private static readonly MethodInfo s_debugWriteLine = typeof(Debug).GetMethod("WriteLine", new Type[] { typeof(string) })!;
#endif
private static readonly MethodInfo s_spanGetItemMethod = typeof(ReadOnlySpan<char>).GetMethod("get_Item", new Type[] { typeof(int) })!;
private static readonly MethodInfo s_spanGetLengthMethod = typeof(ReadOnlySpan<char>).GetMethod("get_Length")!;
private static readonly MethodInfo s_memoryMarshalGetReference = typeof(MemoryMarshal).GetMethod("GetReference", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char));
private static readonly MethodInfo s_spanIndexOfChar = typeof(MemoryExtensions).GetMethod("IndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char));
private static readonly MethodInfo s_spanIndexOfSpan = typeof(MemoryExtensions).GetMethod("IndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char));
private static readonly MethodInfo s_spanIndexOfAnyCharChar = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char));
private static readonly MethodInfo s_spanIndexOfAnyCharCharChar = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char));
private static readonly MethodInfo s_spanIndexOfAnySpan = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char));
private static readonly MethodInfo s_spanLastIndexOfChar = typeof(MemoryExtensions).GetMethod("LastIndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char));
private static readonly MethodInfo s_spanLastIndexOfSpan = typeof(MemoryExtensions).GetMethod("LastIndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char));
private static readonly MethodInfo s_spanSliceIntMethod = typeof(ReadOnlySpan<char>).GetMethod("Slice", new Type[] { typeof(int) })!;
private static readonly MethodInfo s_spanSliceIntIntMethod = typeof(ReadOnlySpan<char>).GetMethod("Slice", new Type[] { typeof(int), typeof(int) })!;
private static readonly MethodInfo s_spanStartsWith = typeof(MemoryExtensions).GetMethod("StartsWith", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char));
private static readonly MethodInfo s_stringAsSpanMethod = typeof(MemoryExtensions).GetMethod("AsSpan", new Type[] { typeof(string) })!;
private static readonly MethodInfo s_stringAsSpanIntIntMethod = typeof(MemoryExtensions).GetMethod("AsSpan", new Type[] { typeof(string), typeof(int), typeof(int) })!;
private static readonly MethodInfo s_stringGetCharsMethod = typeof(string).GetMethod("get_Chars", new Type[] { typeof(int) })!;
private static readonly MethodInfo s_stringIndexOfCharInt = typeof(string).GetMethod("IndexOf", new Type[] { typeof(char), typeof(int) })!;
private static readonly MethodInfo s_stringLastIndexOfCharIntInt = typeof(string).GetMethod("LastIndexOf", new Type[] { typeof(char), typeof(int), typeof(int) })!;
private static readonly MethodInfo s_textInfoToLowerMethod = typeof(TextInfo).GetMethod("ToLower", new Type[] { typeof(char) })!;
protected ILGenerator? _ilg;
// tokens representing local variables
private LocalBuilder? _runtextbegLocal;
private LocalBuilder? _runtextendLocal;
private LocalBuilder? _runtextposLocal;
private LocalBuilder? _runtextLocal;
private LocalBuilder? _runtrackposLocal;
private LocalBuilder? _runtrackLocal;
private LocalBuilder? _runstackposLocal;
private LocalBuilder? _runstackLocal;
private LocalBuilder? _textInfoLocal; // cached to avoid extraneous TLS hits from CurrentCulture and virtual calls to TextInfo
private LocalBuilder? _loopTimeoutCounterLocal; // timeout counter for setrep and setloop
protected RegexOptions _options; // options
protected RegexCode? _code; // the RegexCode object
protected int[]? _codes; // the RegexCodes being translated
protected string[]? _strings; // the stringtable associated with the RegexCodes
protected bool _hasTimeout; // whether the regex has a non-infinite timeout
private Label[]? _labels; // a label for every operation in _codes
private BacktrackNote[]? _notes; // a list of the backtracking states to be generated
private int _notecount; // true count of _notes (allocation grows exponentially)
protected int _trackcount; // count of backtracking states (used to reduce allocations)
private Label _backtrack; // label for backtracking
private Stack<LocalBuilder>? _int32LocalsPool; // pool of Int32 local variables
private Stack<LocalBuilder>? _readOnlySpanCharLocalsPool; // pool of ReadOnlySpan<char> local variables
private int _regexopcode; // the current opcode being processed
private int _codepos; // the current code being translated
private int _backpos; // the current backtrack-note being translated
// special code fragments
private int[]? _uniquenote; // _notes indices for code that should be emitted <= once
private int[]? _goto; // indices for forward-jumps-through-switch (for allocations)
// indices for unique code fragments
private const int Stackpop = 0; // pop one
private const int Stackpop2 = 1; // pop two
private const int Capback = 3; // uncapture
private const int Capback2 = 4; // uncapture 2
private const int Branchmarkback2 = 5; // back2 part of branchmark
private const int Lazybranchmarkback2 = 6; // back2 part of lazybranchmark
private const int Branchcountback2 = 7; // back2 part of branchcount
private const int Lazybranchcountback2 = 8; // back2 part of lazybranchcount
private const int Forejumpback = 9; // back part of forejump
private const int Uniquecount = 10;
private const int LoopTimeoutCheckCount = 2048; // A conservative value to guarantee the correct timeout handling.
private static FieldInfo RegexRunnerField(string fieldname) => typeof(RegexRunner).GetField(fieldname, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)!;
private static MethodInfo RegexRunnerMethod(string methname) => typeof(RegexRunner).GetMethod(methname, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)!;
/// <summary>
/// Entry point to dynamically compile a regular expression. The expression is compiled to
/// an in-memory assembly.
/// </summary>
internal static RegexRunnerFactory Compile(string pattern, RegexCode code, RegexOptions options, bool hasTimeout) =>
new RegexLWCGCompiler().FactoryInstanceFromCode(pattern, code, options, hasTimeout);
/// <summary>
/// Keeps track of an operation that needs to be referenced in the backtrack-jump
/// switch table, and that needs backtracking code to be emitted (if flags != 0)
/// </summary>
private sealed class BacktrackNote
{
internal int _codepos;
internal int _flags;
internal Label _label;
public BacktrackNote(int flags, Label label, int codepos)
{
_codepos = codepos;
_flags = flags;
_label = label;
}
}
/// <summary>
/// Adds a backtrack note to the list of them, and returns the index of the new
/// note (which is also the index for the jump used by the switch table)
/// </summary>
private int AddBacktrackNote(int flags, Label l, int codepos)
{
if (_notes == null || _notecount >= _notes.Length)
{
var newnotes = new BacktrackNote[_notes == null ? 16 : _notes.Length * 2];
if (_notes != null)
{
Array.Copy(_notes, newnotes, _notecount);
}
_notes = newnotes;
}
_notes[_notecount] = new BacktrackNote(flags, l, codepos);
return _notecount++;
}
/// <summary>
/// Adds a backtrack note for the current operation; creates a new label for
/// where the code will be, and returns the switch index.
/// </summary>
private int AddTrack() => AddTrack(RegexCode.Back);
/// <summary>
/// Adds a backtrack note for the current operation; creates a new label for
/// where the code will be, and returns the switch index.
/// </summary>
private int AddTrack(int flags) => AddBacktrackNote(flags, DefineLabel(), _codepos);
/// <summary>
/// Adds a switchtable entry for the specified position (for the forward
/// logic; does not cause backtracking logic to be generated)
/// </summary>
private int AddGoto(int destpos)
{
if (_goto![destpos] == -1)
{
_goto[destpos] = AddBacktrackNote(0, _labels![destpos], destpos);
}
return _goto[destpos];
}
/// <summary>
/// Adds a note for backtracking code that only needs to be generated once;
/// if it's already marked to be generated, returns the switch index
/// for the unique piece of code.
/// </summary>
private int AddUniqueTrack(int i) => AddUniqueTrack(i, RegexCode.Back);
/// <summary>
/// Adds a note for backtracking code that only needs to be generated once;
/// if it's already marked to be generated, returns the switch index
/// for the unique piece of code.
/// </summary>
private int AddUniqueTrack(int i, int flags)
{
if (_uniquenote![i] == -1)
{
_uniquenote[i] = AddTrack(flags);
}
return _uniquenote[i];
}
/// <summary>A macro for _ilg.DefineLabel</summary>
private Label DefineLabel() => _ilg!.DefineLabel();
/// <summary>A macro for _ilg.MarkLabel</summary>
private void MarkLabel(Label l) => _ilg!.MarkLabel(l);
/// <summary>Returns the ith operand of the current operation.</summary>
private int Operand(int i) => _codes![_codepos + i + 1];
/// <summary>True if the current operation is marked for the leftward direction.</summary>
private bool IsRightToLeft() => (_regexopcode & RegexCode.Rtl) != 0;
/// <summary>True if the current operation is marked for case insensitive operation.</summary>
private bool IsCaseInsensitive() => (_regexopcode & RegexCode.Ci) != 0;
/// <summary>Returns the raw regex opcode (masking out Back and Rtl).</summary>
private int Code() => _regexopcode & RegexCode.Mask;
/// <summary>A macro for _ilg.Emit(Opcodes.Ldstr, str)</summary>
protected void Ldstr(string str) => _ilg!.Emit(OpCodes.Ldstr, str);
/// <summary>A macro for the various forms of Ldc.</summary>
protected void Ldc(int i) => _ilg!.Emit(OpCodes.Ldc_I4, i);
/// <summary>A macro for _ilg.Emit(OpCodes.Ldc_I8).</summary>
protected void LdcI8(long i) => _ilg!.Emit(OpCodes.Ldc_I8, i);
/// <summary>A macro for _ilg.Emit(OpCodes.Ret).</summary>
protected void Ret() => _ilg!.Emit(OpCodes.Ret);
/// <summary>A macro for _ilg.Emit(OpCodes.Newobj, constructor).</summary>
protected void Newobj(ConstructorInfo constructor) => _ilg!.Emit(OpCodes.Newobj, constructor);
/// <summary>A macro for _ilg.Emit(OpCodes.Dup).</summary>
protected void Dup() => _ilg!.Emit(OpCodes.Dup);
/// <summary>A macro for _ilg.Emit(OpCodes.Rem_Un).</summary>
private void RemUn() => _ilg!.Emit(OpCodes.Rem_Un);
/// <summary>A macro for _ilg.Emit(OpCodes.Ceq).</summary>
private void Ceq() => _ilg!.Emit(OpCodes.Ceq);
/// <summary>A macro for _ilg.Emit(OpCodes.Cgt_Un).</summary>
private void CgtUn() => _ilg!.Emit(OpCodes.Cgt_Un);
/// <summary>A macro for _ilg.Emit(OpCodes.Clt_Un).</summary>
private void CltUn() => _ilg!.Emit(OpCodes.Clt_Un);
/// <summary>A macro for _ilg.Emit(OpCodes.Pop).</summary>
private void Pop() => _ilg!.Emit(OpCodes.Pop);
/// <summary>A macro for _ilg.Emit(OpCodes.Add).</summary>
private void Add() => _ilg!.Emit(OpCodes.Add);
/// <summary>A macro for _ilg.Emit(OpCodes.Add); a true flag can turn it into a Sub.</summary>
private void Add(bool negate) => _ilg!.Emit(negate ? OpCodes.Sub : OpCodes.Add);
/// <summary>A macro for _ilg.Emit(OpCodes.Sub).</summary>
private void Sub() => _ilg!.Emit(OpCodes.Sub);
/// <summary>A macro for _ilg.Emit(OpCodes.Sub) or _ilg.Emit(OpCodes.Add).</summary>
private void Sub(bool negate) => _ilg!.Emit(negate ? OpCodes.Add : OpCodes.Sub);
/// <summary>A macro for _ilg.Emit(OpCodes.Neg).</summary>
private void Neg() => _ilg!.Emit(OpCodes.Neg);
/// <summary>A macro for _ilg.Emit(OpCodes.Mul).</summary>
private void Mul() => _ilg!.Emit(OpCodes.Mul);
/// <summary>A macro for _ilg.Emit(OpCodes.And).</summary>
private void And() => _ilg!.Emit(OpCodes.And);
/// <summary>A macro for _ilg.Emit(OpCodes.Or).</summary>
private void Or() => _ilg!.Emit(OpCodes.Or);
/// <summary>A macro for _ilg.Emit(OpCodes.Shl).</summary>
private void Shl() => _ilg!.Emit(OpCodes.Shl);
/// <summary>A macro for _ilg.Emit(OpCodes.Shr).</summary>
private void Shr() => _ilg!.Emit(OpCodes.Shr);
/// <summary>A macro for _ilg.Emit(OpCodes.Ldloc).</summary>
/// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks>
private void Ldloc(LocalBuilder lt) => _ilg!.Emit(OpCodes.Ldloc, lt);
/// <summary>A macro for _ilg.Emit(OpCodes.Ldloca).</summary>
/// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks>
private void Ldloca(LocalBuilder lt) => _ilg!.Emit(OpCodes.Ldloca, lt);
/// <summary>A macro for _ilg.Emit(OpCodes.Ldind_U2).</summary>
private void LdindU2() => _ilg!.Emit(OpCodes.Ldind_U2);
/// <summary>A macro for _ilg.Emit(OpCodes.Ldind_I4).</summary>
private void LdindI4() => _ilg!.Emit(OpCodes.Ldind_I4);
/// <summary>A macro for _ilg.Emit(OpCodes.Ldind_I8).</summary>
private void LdindI8() => _ilg!.Emit(OpCodes.Ldind_I8);
/// <summary>A macro for _ilg.Emit(OpCodes.Unaligned).</summary>
private void Unaligned(byte alignment) => _ilg!.Emit(OpCodes.Unaligned, alignment);
/// <summary>A macro for _ilg.Emit(OpCodes.Stloc).</summary>
/// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks>
private void Stloc(LocalBuilder lt) => _ilg!.Emit(OpCodes.Stloc, lt);
/// <summary>A macro for _ilg.Emit(OpCodes.Ldarg_0).</summary>
protected void Ldthis() => _ilg!.Emit(OpCodes.Ldarg_0);
/// <summary>A macro for Ldthis(); Ldfld();</summary>
protected void Ldthisfld(FieldInfo ft)
{
Ldthis();
Ldfld(ft);
}
/// <summary>A macro for Ldthis(); Ldfld(); Stloc();</summary>
private void Mvfldloc(FieldInfo ft, LocalBuilder lt)
{
Ldthisfld(ft);
Stloc(lt);
}
/// <summary>A macro for Ldthis(); Ldloc(); Stfld();</summary>
private void Mvlocfld(LocalBuilder lt, FieldInfo ft)
{
Ldthis();
Ldloc(lt);
Stfld(ft);
}
/// <summary>A macro for _ilg.Emit(OpCodes.Ldfld).</summary>
private void Ldfld(FieldInfo ft) => _ilg!.Emit(OpCodes.Ldfld, ft);
/// <summary>A macro for _ilg.Emit(OpCodes.Stfld).</summary>
protected void Stfld(FieldInfo ft) => _ilg!.Emit(OpCodes.Stfld, ft);
/// <summary>A macro for _ilg.Emit(OpCodes.Callvirt, mt).</summary>
protected void Callvirt(MethodInfo mt) => _ilg!.Emit(OpCodes.Callvirt, mt);
/// <summary>A macro for _ilg.Emit(OpCodes.Call, mt).</summary>
protected void Call(MethodInfo mt) => _ilg!.Emit(OpCodes.Call, mt);
/// <summary>A macro for _ilg.Emit(OpCodes.Brfalse) (long form).</summary>
private void BrfalseFar(Label l) => _ilg!.Emit(OpCodes.Brfalse, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Brtrue) (long form).</summary>
private void BrtrueFar(Label l) => _ilg!.Emit(OpCodes.Brtrue, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Br) (long form).</summary>
private void BrFar(Label l) => _ilg!.Emit(OpCodes.Br, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Ble) (long form).</summary>
private void BleFar(Label l) => _ilg!.Emit(OpCodes.Ble, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Blt) (long form).</summary>
private void BltFar(Label l) => _ilg!.Emit(OpCodes.Blt, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Blt_Un) (long form).</summary>
private void BltUnFar(Label l) => _ilg!.Emit(OpCodes.Blt_Un, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Bge) (long form).</summary>
private void BgeFar(Label l) => _ilg!.Emit(OpCodes.Bge, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Bge_Un) (long form).</summary>
private void BgeUnFar(Label l) => _ilg!.Emit(OpCodes.Bge_Un, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Bgt) (long form).</summary>
private void BgtFar(Label l) => _ilg!.Emit(OpCodes.Bgt, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Bne) (long form).</summary>
private void BneFar(Label l) => _ilg!.Emit(OpCodes.Bne_Un, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Beq) (long form).</summary>
private void BeqFar(Label l) => _ilg!.Emit(OpCodes.Beq, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Brfalse_S) (short jump).</summary>
private void Brfalse(Label l) => _ilg!.Emit(OpCodes.Brfalse_S, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Brtrue_S) (short jump).</summary>
private void Brtrue(Label l) => _ilg!.Emit(OpCodes.Brtrue_S, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Br_S) (short jump).</summary>
private void Br(Label l) => _ilg!.Emit(OpCodes.Br_S, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Ble_S) (short jump).</summary>
private void Ble(Label l) => _ilg!.Emit(OpCodes.Ble_S, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Blt_S) (short jump).</summary>
private void Blt(Label l) => _ilg!.Emit(OpCodes.Blt_S, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Bge_S) (short jump).</summary>
private void Bge(Label l) => _ilg!.Emit(OpCodes.Bge_S, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Bge_Un_S) (short jump).</summary>
private void BgeUn(Label l) => _ilg!.Emit(OpCodes.Bge_Un_S, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Bgt_S) (short jump).</summary>
private void Bgt(Label l) => _ilg!.Emit(OpCodes.Bgt_S, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Bgt_Un_S) (short jump).</summary>
private void BgtUn(Label l) => _ilg!.Emit(OpCodes.Bgt_Un_S, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Bne_S) (short jump).</summary>
private void Bne(Label l) => _ilg!.Emit(OpCodes.Bne_Un_S, l);
/// <summary>A macro for _ilg.Emit(OpCodes.Beq_S) (short jump).</summary>
private void Beq(Label l) => _ilg!.Emit(OpCodes.Beq_S, l);
/// <summary>A macro for the Ldlen instruction.</summary>
private void Ldlen() => _ilg!.Emit(OpCodes.Ldlen);
/// <summary>A macro for the Ldelem_I4 instruction.</summary>
private void LdelemI4() => _ilg!.Emit(OpCodes.Ldelem_I4);
/// <summary>A macro for the Stelem_I4 instruction.</summary>
private void StelemI4() => _ilg!.Emit(OpCodes.Stelem_I4);
private void Switch(Label[] table) => _ilg!.Emit(OpCodes.Switch, table);
/// <summary>Declares a local int.</summary>
private LocalBuilder DeclareInt32() => _ilg!.DeclareLocal(typeof(int));
/// <summary>Declares a local CultureInfo.</summary>
private LocalBuilder? DeclareTextInfo() => _ilg!.DeclareLocal(typeof(TextInfo));
/// <summary>Declares a local int[].</summary>
private LocalBuilder DeclareInt32Array() => _ilg!.DeclareLocal(typeof(int[]));
/// <summary>Declares a local string.</summary>
private LocalBuilder DeclareString() => _ilg!.DeclareLocal(typeof(string));
private LocalBuilder DeclareReadOnlySpanChar() => _ilg!.DeclareLocal(typeof(ReadOnlySpan<char>));
/// <summary>Rents an Int32 local variable slot from the pool of locals.</summary>
/// <remarks>
/// Care must be taken to Dispose of the returned <see cref="RentedLocalBuilder"/> when it's no longer needed,
/// and also not to jump into the middle of a block involving a rented local from outside of that block.
/// </remarks>
private RentedLocalBuilder RentInt32Local() => new RentedLocalBuilder(
_int32LocalsPool ??= new Stack<LocalBuilder>(),
_int32LocalsPool.TryPop(out LocalBuilder? iterationLocal) ? iterationLocal : DeclareInt32());
/// <summary>Rents a ReadOnlySpan(char) local variable slot from the pool of locals.</summary>
/// <remarks>
/// Care must be taken to Dispose of the returned <see cref="RentedLocalBuilder"/> when it's no longer needed,
/// and also not to jump into the middle of a block involving a rented local from outside of that block.
/// </remarks>
private RentedLocalBuilder RentReadOnlySpanCharLocal() => new RentedLocalBuilder(
_readOnlySpanCharLocalsPool ??= new Stack<LocalBuilder>(1), // capacity == 1 as we currently don't expect overlapping instances
_readOnlySpanCharLocalsPool.TryPop(out LocalBuilder? iterationLocal) ? iterationLocal : DeclareReadOnlySpanChar());
/// <summary>Returned a rented local to the pool.</summary>
private struct RentedLocalBuilder : IDisposable
{
private Stack<LocalBuilder> _pool;
private LocalBuilder _local;
internal RentedLocalBuilder(Stack<LocalBuilder> pool, LocalBuilder local)
{
_local = local;
_pool = pool;
}
public static implicit operator LocalBuilder(RentedLocalBuilder local) => local._local;
public void Dispose()
{
Debug.Assert(_pool != null);
Debug.Assert(_local != null);
Debug.Assert(!_pool.Contains(_local));
_pool.Push(_local);
this = default;
}
}
/// <summary>Loads the char to the right of the current position.</summary>
private void Rightchar()
{
Ldloc(_runtextLocal!);
Ldloc(_runtextposLocal!);
Call(s_stringGetCharsMethod);
}
/// <summary>Loads the char to the right of the current position and advances the current position.</summary>
private void Rightcharnext()
{
Ldloc(_runtextLocal!);
Ldloc(_runtextposLocal!);
Call(s_stringGetCharsMethod);
Ldloc(_runtextposLocal!);
Ldc(1);
Add();
Stloc(_runtextposLocal!);
}
/// <summary>Loads the char to the left of the current position.</summary>
private void Leftchar()
{
Ldloc(_runtextLocal!);
Ldloc(_runtextposLocal!);
Ldc(1);
Sub();
Call(s_stringGetCharsMethod);
}
/// <summary>Loads the char to the left of the current position and advances (leftward).</summary>
private void Leftcharnext()
{
Ldloc(_runtextposLocal!);
Ldc(1);
Sub();
Stloc(_runtextposLocal!);
Ldloc(_runtextLocal!);
Ldloc(_runtextposLocal!);
Call(s_stringGetCharsMethod);
}
/// <summary>Creates a backtrack note and pushes the switch index it on the tracking stack.</summary>
private void Track()
{
ReadyPushTrack();
Ldc(AddTrack());
DoPush();
}
/// <summary>
/// Pushes the current switch index on the tracking stack so the backtracking
/// logic will be repeated again next time we backtrack here.
/// </summary>
private void Trackagain()
{
ReadyPushTrack();
Ldc(_backpos);
DoPush();
}
/// <summary>Saves the value of a local variable on the tracking stack.</summary>
private void PushTrack(LocalBuilder lt)
{
ReadyPushTrack();
Ldloc(lt);
DoPush();
}
/// <summary>
/// Creates a backtrack note for a piece of code that should only be generated once,
/// and emits code that pushes the switch index on the backtracking stack.
/// </summary>
private void TrackUnique(int i)
{
ReadyPushTrack();
Ldc(AddUniqueTrack(i));
DoPush();
}
/// <summary>
/// Creates a second-backtrack note for a piece of code that should only be
/// generated once, and emits code that pushes the switch index on the
/// backtracking stack.
/// </summary>
private void TrackUnique2(int i)
{
ReadyPushTrack();
Ldc(AddUniqueTrack(i, RegexCode.Back2));
DoPush();
}
/// <summary>Prologue to code that will push an element on the tracking stack.</summary>
private void ReadyPushTrack()
{
Ldloc(_runtrackposLocal!);
Ldc(1);
Sub();
Stloc(_runtrackposLocal!);
Ldloc(_runtrackLocal!);
Ldloc(_runtrackposLocal!);
}
/// <summary>Pops an element off the tracking stack (leave it on the operand stack).</summary>
private void PopTrack()
{
Ldloc(_runtrackLocal!);
Ldloc(_runtrackposLocal!);
LdelemI4();
using RentedLocalBuilder tmp = RentInt32Local();
Stloc(tmp);
Ldloc(_runtrackposLocal!);
Ldc(1);
Add();
Stloc(_runtrackposLocal!);
Ldloc(tmp);
}
/// <summary>Retrieves the top entry on the tracking stack without popping.</summary>
private void TopTrack()
{
Ldloc(_runtrackLocal!);
Ldloc(_runtrackposLocal!);
LdelemI4();
}
/// <summary>Saves the value of a local variable on the grouping stack.</summary>
private void PushStack(LocalBuilder lt)
{
ReadyPushStack();
Ldloc(lt);
DoPush();
}
/// <summary>Prologue to code that will replace the ith element on the grouping stack.</summary>
internal void ReadyReplaceStack(int i)
{
Ldloc(_runstackLocal!);
Ldloc(_runstackposLocal!);
if (i != 0)
{
Ldc(i);
Add();
}
}
/// <summary>Prologue to code that will push an element on the grouping stack.</summary>
private void ReadyPushStack()
{
Ldloc(_runstackposLocal!);
Ldc(1);
Sub();
Stloc(_runstackposLocal!);
Ldloc(_runstackLocal!);
Ldloc(_runstackposLocal!);
}
/// <summary>Retrieves the top entry on the stack without popping.</summary>
private void TopStack()
{
Ldloc(_runstackLocal!);
Ldloc(_runstackposLocal!);
LdelemI4();
}
/// <summary>Pops an element off the grouping stack (leave it on the operand stack).</summary>
private void PopStack()
{
using RentedLocalBuilder elementLocal = RentInt32Local();
Ldloc(_runstackLocal!);
Ldloc(_runstackposLocal!);
LdelemI4();
Stloc(elementLocal);
Ldloc(_runstackposLocal!);
Ldc(1);
Add();
Stloc(_runstackposLocal!);
Ldloc(elementLocal);
}
/// <summary>Pops 1 element off the grouping stack and discards it.</summary>
private void PopDiscardStack() => PopDiscardStack(1);
/// <summary>Pops i elements off the grouping stack and discards them.</summary>
private void PopDiscardStack(int i)
{
Ldloc(_runstackposLocal!);
Ldc(i);
Add();
Stloc(_runstackposLocal!);
}
/// <summary>Epilogue to code that will replace an element on a stack (use Ld* in between).</summary>
private void DoReplace() => StelemI4();
/// <summary>Epilogue to code that will push an element on a stack (use Ld* in between).</summary>
private void DoPush() => StelemI4();
/// <summary>Jump to the backtracking switch.</summary>
private void Back() => BrFar(_backtrack);
/// <summary>
/// Branch to the MSIL corresponding to the regex code at i
/// </summary>
/// <remarks>
/// A trick: since track and stack space is gobbled up unboundedly
/// only as a result of branching backwards, this is where we check
/// for sufficient space and trigger reallocations.
///
/// If the "goto" is backwards, we generate code that checks
/// available space against the amount of space that would be needed
/// in the worst case by code that will only go forward; if there's
/// not enough, we push the destination on the tracking stack, then
/// we jump to the place where we invoke the allocator.
///
/// Since forward gotos pose no threat, they just turn into a Br.
/// </remarks>
private void Goto(int i)
{
if (i < _codepos)
{
Label l1 = DefineLabel();
// When going backwards, ensure enough space.
Ldloc(_runtrackposLocal!);
Ldc(_trackcount * 4);
Ble(l1);
Ldloc(_runstackposLocal!);
Ldc(_trackcount * 3);
BgtFar(_labels![i]);
MarkLabel(l1);
ReadyPushTrack();
Ldc(AddGoto(i));
DoPush();
BrFar(_backtrack);
}
else
{
BrFar(_labels![i]);
}
}
/// <summary>
/// Returns the position of the next operation in the regex code, taking
/// into account the different numbers of arguments taken by operations
/// </summary>
private int NextCodepos() => _codepos + RegexCode.OpcodeSize(_codes![_codepos]);
/// <summary>The label for the next (forward) operation.</summary>
private Label AdvanceLabel() => _labels![NextCodepos()];
/// <summary>Goto the next (forward) operation.</summary>
private void Advance() => BrFar(AdvanceLabel());
/// <summary>Sets the culture local to CultureInfo.CurrentCulture.</summary>
private void InitLocalCultureInfo()
{
Debug.Assert(_textInfoLocal != null);
Call(s_cultureInfoGetCurrentCultureMethod);
Callvirt(s_cultureInfoGetTextInfoMethod);
Stloc(_textInfoLocal);
}
/// <summary>Whether ToLower operations should be performed with the invariant culture as opposed to the one in <see cref="_textInfoLocal"/>.</summary>
private bool UseToLowerInvariant => _textInfoLocal == null || (_options & RegexOptions.CultureInvariant) != 0;
/// <summary>Invokes either char.ToLowerInvariant(c) or _textInfo.ToLower(c).</summary>
private void CallToLower()
{
if (UseToLowerInvariant)
{
Call(s_charToLowerInvariantMethod);
}
else
{
using RentedLocalBuilder currentCharLocal = RentInt32Local();
Stloc(currentCharLocal);
Ldloc(_textInfoLocal!);
Ldloc(currentCharLocal);
Callvirt(s_textInfoToLowerMethod);
}
}
/// <summary>
/// Generates the first section of the MSIL. This section contains all
/// the forward logic, and corresponds directly to the regex codes.
/// In the absence of backtracking, this is all we would need.
/// </summary>
private void GenerateForwardSection()
{
_uniquenote = new int[Uniquecount];
_labels = new Label[_codes!.Length];
_goto = new int[_codes.Length];
// initialize
Array.Fill(_uniquenote, -1);
for (int codepos = 0; codepos < _codes.Length; codepos += RegexCode.OpcodeSize(_codes[codepos]))
{
_goto[codepos] = -1;
_labels[codepos] = DefineLabel();
}
// emit variable initializers
Mvfldloc(s_runtextField, _runtextLocal!);
Mvfldloc(s_runtextbegField, _runtextbegLocal!);
Mvfldloc(s_runtextendField, _runtextendLocal!);
Mvfldloc(s_runtextposField, _runtextposLocal!);
Mvfldloc(s_runtrackField, _runtrackLocal!);
Mvfldloc(s_runtrackposField, _runtrackposLocal!);
Mvfldloc(s_runstackField, _runstackLocal!);
Mvfldloc(s_runstackposField, _runstackposLocal!);
_backpos = -1;
for (int codepos = 0; codepos < _codes.Length; codepos += RegexCode.OpcodeSize(_codes[codepos]))
{
MarkLabel(_labels[codepos]);
_codepos = codepos;
_regexopcode = _codes[codepos];
GenerateOneCode();
}
}
/// <summary>
/// Generates the middle section of the MSIL. This section contains the
/// big switch jump that allows us to simulate a stack of addresses,
/// and it also contains the calls that expand the tracking and the
/// grouping stack when they get too full.
/// </summary>
private void GenerateMiddleSection()
{
using RentedLocalBuilder limitLocal = RentInt32Local();
Label afterDoubleStack = DefineLabel();
Label afterDoubleTrack = DefineLabel();
// Backtrack:
MarkLabel(_backtrack);
// (Equivalent of EnsureStorage, but written to avoid unnecessary local spilling.)
// int limitLocal = runtrackcount * 4;
Ldthisfld(s_runtrackcountField);
Ldc(4);
Mul();
Stloc(limitLocal);
// if (runstackpos < limit)
// {
// this.runstackpos = runstackpos;
// DoubleStack(); // might change runstackpos and runstack
// runstackpos = this.runstackpos;
// runstack = this.runstack;
// }
Ldloc(_runstackposLocal!);
Ldloc(limitLocal);
Bge(afterDoubleStack);
Mvlocfld(_runstackposLocal!, s_runstackposField);
Ldthis();
Call(s_doubleStackMethod);
Mvfldloc(s_runstackposField, _runstackposLocal!);
Mvfldloc(s_runstackField, _runstackLocal!);
MarkLabel(afterDoubleStack);
// if (runtrackpos < limit)
// {
// this.runtrackpos = runtrackpos;
// DoubleTrack(); // might change runtrackpos and runtrack
// runtrackpos = this.runtrackpos;
// runtrack = this.runtrack;
// }
Ldloc(_runtrackposLocal!);
Ldloc(limitLocal);
Bge(afterDoubleTrack);
Mvlocfld(_runtrackposLocal!, s_runtrackposField);
Ldthis();
Call(s_doubleTrackMethod);
Mvfldloc(s_runtrackposField, _runtrackposLocal!);
Mvfldloc(s_runtrackField, _runtrackLocal!);
MarkLabel(afterDoubleTrack);
// runtrack[runtrackpos++]
PopTrack();
// Backtracking jump table
var table = new Label[_notecount];
for (int i = 0; i < _notecount; i++)
{
table[i] = _notes![i]._label;
}
Switch(table);
}
/// <summary>
/// Generates the last section of the MSIL. This section contains all of
/// the backtracking logic.
/// </summary>
private void GenerateBacktrackSection()
{
for (int i = 0; i < _notecount; i++)
{
BacktrackNote n = _notes![i];
if (n._flags != 0)
{
MarkLabel(n._label);
_codepos = n._codepos;
_backpos = i;
_regexopcode = _codes![n._codepos] | n._flags;
GenerateOneCode();
}
}
}
/// <summary>
/// Generates FindFirstChar.
/// </summary>
protected void GenerateFindFirstChar()
{
Debug.Assert(_code != null);
_int32LocalsPool?.Clear();
_readOnlySpanCharLocalsPool?.Clear();
_runtextposLocal = DeclareInt32();
_runtextendLocal = DeclareInt32();
if (_code.RightToLeft)
{
_runtextbegLocal = DeclareInt32();
}
_runtextLocal = DeclareString();
_textInfoLocal = null;
if ((_options & RegexOptions.CultureInvariant) == 0)
{
bool needsCulture = _code.FindOptimizations.FindMode switch
{
FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive or
FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseInsensitive or
FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive or
FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive or
FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive => true,
_ when _code.FindOptimizations.FixedDistanceSets is List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets => sets.Exists(set => set.CaseInsensitive),
_ => false,
};
if (needsCulture)
{
_textInfoLocal = DeclareTextInfo();
InitLocalCultureInfo();
}
}
// Load necessary locals
// int runtextpos = this.runtextpos;
// int runtextend = this.runtextend;
Mvfldloc(s_runtextposField, _runtextposLocal);
Mvfldloc(s_runtextendField, _runtextendLocal);
if (_code.RightToLeft)
{
Mvfldloc(s_runtextbegField, _runtextbegLocal!);
}
// Generate length check. If the input isn't long enough to possibly match, fail quickly.
// It's rare for min required length to be 0, so we don't bother special-casing the check,
// especially since we want the "return false" code regardless.
int minRequiredLength = _code.Tree.MinRequiredLength;
Debug.Assert(minRequiredLength >= 0);
Label returnFalse = DefineLabel();
Label finishedLengthCheck = DefineLabel();
if (!_code.RightToLeft)
{
// if (runtextpos > runtextend - _code.Tree.MinRequiredLength)
// {
// this.runtextpos = runtextend;
// return false;
// }
Ldloc(_runtextposLocal);
Ldloc(_runtextendLocal);
if (minRequiredLength > 0)
{
Ldc(minRequiredLength);
Sub();
}
Ble(finishedLengthCheck);
MarkLabel(returnFalse);
Ldthis();
Ldloc(_runtextendLocal);
}
else
{
// if (runtextpos - _code.Tree.MinRequiredLength < runtextbeg)
// {
// this.runtextpos = runtextbeg;
// return false;
// }
Ldloc(_runtextposLocal);
if (minRequiredLength > 0)
{
Ldc(minRequiredLength);
Sub();
}
Ldloc(_runtextbegLocal!);
Bge(finishedLengthCheck);
MarkLabel(returnFalse);
Ldthis();
Ldloc(_runtextbegLocal!);
}
Stfld(s_runtextposField);
Ldc(0);
Ret();
MarkLabel(finishedLengthCheck);
// Emit any anchors.
if (GenerateAnchors())
{
return;
}
// Either anchors weren't specified, or they don't completely root all matches to a specific location.
switch (_code.FindOptimizations.FindMode)
{
case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive:
Debug.Assert(!string.IsNullOrEmpty(_code.FindOptimizations.LeadingCaseSensitivePrefix));
GenerateIndexOf_LeftToRight(_code.FindOptimizations.LeadingCaseSensitivePrefix);
break;
case FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive:
Debug.Assert(!string.IsNullOrEmpty(_code.FindOptimizations.LeadingCaseSensitivePrefix));
GenerateIndexOf_RightToLeft(_code.FindOptimizations.LeadingCaseSensitivePrefix);
break;
case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive:
case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive:
case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive:
case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive:
Debug.Assert(_code.FindOptimizations.FixedDistanceSets is { Count: > 0 });
GenerateFixedSet_LeftToRight();
break;
case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive:
case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive:
Debug.Assert(_code.FindOptimizations.FixedDistanceSets is { Count: > 0 });
GenerateFixedSet_RightToLeft();
break;
default:
Debug.Fail($"Unexpected mode: {_code.FindOptimizations.FindMode}");
goto case FindNextStartingPositionMode.NoSearch;
case FindNextStartingPositionMode.NoSearch:
// return true;
Ldc(1);
Ret();
break;
}
// Emits any anchors. Returns true if the anchor roots any match to a specific location and thus no further
// searching is required; otherwise, false.
bool GenerateAnchors()
{
// Generate anchor checks.
if ((_code.FindOptimizations.LeadingAnchor & (RegexPrefixAnalyzer.Beginning | RegexPrefixAnalyzer.Start | RegexPrefixAnalyzer.EndZ | RegexPrefixAnalyzer.End | RegexPrefixAnalyzer.Bol)) != 0)
{
switch (_code.FindOptimizations.LeadingAnchor)
{
case RegexPrefixAnalyzer.Beginning:
{
Label l1 = DefineLabel();
Ldloc(_runtextposLocal);
if (!_code.RightToLeft)
{
Ldthisfld(s_runtextbegField);
Ble(l1);
Br(returnFalse);
}
else
{
Ldloc(_runtextbegLocal!);
Ble(l1);
Ldthis();
Ldloc(_runtextbegLocal!);
Stfld(s_runtextposField);
}
MarkLabel(l1);
}
Ldc(1);
Ret();
return true;
case RegexPrefixAnalyzer.Start:
{
Label l1 = DefineLabel();
Ldloc(_runtextposLocal);
Ldthisfld(s_runtextstartField);
if (!_code.RightToLeft)
{
Ble(l1);
}
else
{
Bge(l1);
}
Br(returnFalse);
MarkLabel(l1);
}
Ldc(1);
Ret();
return true;
case RegexPrefixAnalyzer.EndZ:
{
Label l1 = DefineLabel();
if (!_code.RightToLeft)
{
Ldloc(_runtextposLocal);
Ldloc(_runtextendLocal);
Ldc(1);
Sub();
Bge(l1);
Ldthis();
Ldloc(_runtextendLocal);
Ldc(1);
Sub();
Stfld(s_runtextposField);
MarkLabel(l1);
}
else
{
Label l2 = DefineLabel();
Ldloc(_runtextposLocal);
Ldloc(_runtextendLocal);
Ldc(1);
Sub();
Blt(l1);
Ldloc(_runtextposLocal);
Ldloc(_runtextendLocal);
Beq(l2);
Ldthisfld(s_runtextField);
Ldloc(_runtextposLocal);
Call(s_stringGetCharsMethod);
Ldc('\n');
Beq(l2);
MarkLabel(l1);
BrFar(returnFalse);
MarkLabel(l2);
}
}
Ldc(1);
Ret();
return true;
case RegexPrefixAnalyzer.End:
{
Label l1 = DefineLabel();
Ldloc(_runtextposLocal);
Ldloc(_runtextendLocal);
if (!_code.RightToLeft)
{
Bge(l1);
Ldthis();
Ldloc(_runtextendLocal);
Stfld(s_runtextposField);
}
else
{
Bge(l1);
Br(returnFalse);
}
MarkLabel(l1);
}
Ldc(1);
Ret();
return true;
case RegexPrefixAnalyzer.Bol:
{
// Optimize the handling of a Beginning-Of-Line (BOL) anchor. BOL is special, in that unlike
// other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike
// the other anchors, which all skip all subsequent processing if found, with BOL we just use it
// to boost our position to the next line, and then continue normally with any prefix or char class searches.
Debug.Assert(!_code.RightToLeft, "RightToLeft isn't implemented and should have been filtered out previously");
Label atBeginningOfLine = DefineLabel();
// if (runtextpos > runtextbeg...
Ldloc(_runtextposLocal!);
Ldthisfld(s_runtextbegField);
Ble(atBeginningOfLine);
// ... && runtext[runtextpos - 1] != '\n') { ... }
Ldthisfld(s_runtextField);
Ldloc(_runtextposLocal);
Ldc(1);
Sub();
Call(s_stringGetCharsMethod);
Ldc('\n');
Beq(atBeginningOfLine);
// int tmp = runtext.IndexOf('\n', runtextpos);
Ldthisfld(s_runtextField);
Ldc('\n');
Ldloc(_runtextposLocal);
Call(s_stringIndexOfCharInt);
using (RentedLocalBuilder newlinePos = RentInt32Local())
{
Stloc(newlinePos);
// if (newlinePos == -1 || newlinePos + 1 > runtextend)
// {
// runtextpos = runtextend;
// return false;
// }
Ldloc(newlinePos);
Ldc(-1);
Beq(returnFalse);
Ldloc(newlinePos);
Ldc(1);
Add();
Ldloc(_runtextendLocal);
Bgt(returnFalse);
// runtextpos = newlinePos + 1;
Ldloc(newlinePos);
Ldc(1);
Add();
Stloc(_runtextposLocal);
}
MarkLabel(atBeginningOfLine);
}
break;
}
}
return false;
}
void GenerateIndexOf_LeftToRight(string prefix)
{
using RentedLocalBuilder i = RentInt32Local();
// int i = runtext.AsSpan(runtextpos, runtextend - runtextpos).IndexOf(prefix);
Ldthis();
Ldfld(s_runtextField);
Ldloc(_runtextposLocal);
Ldloc(_runtextendLocal);
Ldloc(_runtextposLocal);
Sub();
Call(s_stringAsSpanIntIntMethod);
Ldstr(prefix);
Call(s_stringAsSpanMethod);
Call(s_spanIndexOfSpan);
Stloc(i);
// if (i < 0) goto ReturnFalse;
Ldloc(i);
Ldc(0);
BltFar(returnFalse);
// base.runtextpos = runtextpos + i;
// return true;
Ldthis();
Ldloc(_runtextposLocal);
Ldloc(i);
Add();
Stfld(s_runtextposField);
Ldc(1);
Ret();
}
void GenerateIndexOf_RightToLeft(string prefix)
{
using RentedLocalBuilder i = RentInt32Local();
// int i = runtext.AsSpan(runtextpos, runtextbeg, runtextpos - runtextbeg).LastIndexOf(prefix);
Ldthis();
Ldfld(s_runtextField);
Ldloc(_runtextbegLocal!);
Ldloc(_runtextposLocal);
Ldloc(_runtextbegLocal!);
Sub();
Call(s_stringAsSpanIntIntMethod);
Ldstr(prefix);
Call(s_stringAsSpanMethod);
Call(s_spanLastIndexOfSpan);
Stloc(i);
// if (i < 0) goto ReturnFalse;
Ldloc(i);
Ldc(0);
BltFar(returnFalse);
// base.runtextpos = runtextbeg + i + LeadingCaseSensitivePrefix.Length;
// return true;
Ldthis();
Ldloc(_runtextbegLocal!);
Ldloc(i);
Add();
Ldc(prefix.Length);
Add();
Stfld(s_runtextposField);
Ldc(1);
Ret();
}
void GenerateFixedSet_RightToLeft()
{
(char[]? Chars, string Set, int Distance, bool CaseInsensitive) set = _code.FindOptimizations.FixedDistanceSets![0];
Debug.Assert(set.Distance == 0);
using RentedLocalBuilder i = RentInt32Local();
if (set.Chars is { Length: 1 } && !set.CaseInsensitive)
{
// int i = runtext.AsSpan(runtextpos, runtextbeg, runtextpos - runtextbeg).LastIndexOf(set.Chars[0]);
Ldthis();
Ldfld(s_runtextField);
Ldloc(_runtextbegLocal!);
Ldloc(_runtextposLocal);
Ldloc(_runtextbegLocal!);
Sub();
Call(s_stringAsSpanIntIntMethod);
Ldc(set.Chars[0]);
Call(s_spanLastIndexOfChar);
Stloc(i);
// if (i < 0) goto ReturnFalse;
Ldloc(i);
Ldc(0);
BltFar(returnFalse);
// base.runtextpos = runtextbeg + i + 1;
// return true;
Ldthis();
Ldloc(_runtextbegLocal!);
Ldloc(i);
Add();
Ldc(1);
Add();
Stfld(s_runtextposField);
Ldc(1);
Ret();
}
else
{
Label condition = DefineLabel();
Label increment = DefineLabel();
Label body = DefineLabel();
Mvfldloc(s_runtextField, _runtextLocal);
// for (int i = runtextpos - 1; ...
Ldloc(_runtextposLocal);
Ldc(1);
Sub();
Stloc(i);
BrFar(condition);
// if (MatchCharClass(runtext[i], set))
MarkLabel(body);
Ldloc(_runtextLocal);
Ldloc(i);
Call(s_stringGetCharsMethod);
EmitMatchCharacterClass(set.Set, set.CaseInsensitive);
Brfalse(increment);
// base.runtextpos = i + 1;
// return true;
Ldthis();
Ldloc(i);
Ldc(1);
Add();
Stfld(s_runtextposField);
Ldc(1);
Ret();
// for (...; ...; i--)
MarkLabel(increment);
Ldloc(i);
Ldc(1);
Sub();
Stloc(i);
// for (...; i >= runtextbeg; ...)
MarkLabel(condition);
Ldloc(i);
Ldloc(_runtextbegLocal!);
BgeFar(body);
BrFar(returnFalse);
}
}
void GenerateFixedSet_LeftToRight()
{
List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? sets = _code.FindOptimizations.FixedDistanceSets;
(char[]? Chars, string Set, int Distance, bool CaseInsensitive) primarySet = sets![0];
const int MaxSets = 4;
int setsToUse = Math.Min(sets.Count, MaxSets);
using RentedLocalBuilder iLocal = RentInt32Local();
using RentedLocalBuilder textSpanLocal = RentReadOnlySpanCharLocal();
// ReadOnlySpan<char> span = this.runtext.AsSpan(runtextpos, runtextend - runtextpos);
Ldthisfld(s_runtextField);
Ldloc(_runtextposLocal);
Ldloc(_runtextendLocal);
Ldloc(_runtextposLocal);
Sub();
Call(s_stringAsSpanIntIntMethod);
Stloc(textSpanLocal);
// If we can use IndexOf{Any}, try to accelerate the skip loop via vectorization to match the first prefix.
// We can use it if this is a case-sensitive class with a small number of characters in the class.
int setIndex = 0;
bool canUseIndexOf = !primarySet.CaseInsensitive && primarySet.Chars is not null;
bool needLoop = !canUseIndexOf || setsToUse > 1;
Label checkSpanLengthLabel = default;
Label charNotInClassLabel = default;
Label loopBody = default;
if (needLoop)
{
checkSpanLengthLabel = DefineLabel();
charNotInClassLabel = DefineLabel();
loopBody = DefineLabel();
// for (int i = 0;
Ldc(0);
Stloc(iLocal);
BrFar(checkSpanLengthLabel);
MarkLabel(loopBody);
}
if (canUseIndexOf)
{
setIndex = 1;
if (needLoop)
{
// textSpan.Slice(iLocal + primarySet.Distance);
Ldloca(textSpanLocal);
Ldloc(iLocal);
if (primarySet.Distance != 0)
{
Ldc(primarySet.Distance);
Add();
}
Call(s_spanSliceIntMethod);
}
else if (primarySet.Distance != 0)
{
// textSpan.Slice(primarySet.Distance)
Ldloca(textSpanLocal);
Ldc(primarySet.Distance);
Call(s_spanSliceIntMethod);
}
else
{
// textSpan
Ldloc(textSpanLocal);
}
switch (primarySet.Chars!.Length)
{
case 1:
// tmp = ...IndexOf(setChars[0]);
Ldc(primarySet.Chars[0]);
Call(s_spanIndexOfChar);
break;
case 2:
// tmp = ...IndexOfAny(setChars[0], setChars[1]);
Ldc(primarySet.Chars[0]);
Ldc(primarySet.Chars[1]);
Call(s_spanIndexOfAnyCharChar);
break;
case 3:
// tmp = ...IndexOfAny(setChars[0], setChars[1], setChars[2]});
Ldc(primarySet.Chars[0]);
Ldc(primarySet.Chars[1]);
Ldc(primarySet.Chars[2]);
Call(s_spanIndexOfAnyCharCharChar);
break;
default:
Ldstr(new string(primarySet.Chars));
Call(s_stringAsSpanMethod);
Call(s_spanIndexOfAnySpan);
break;
}
if (needLoop)
{
// i += tmp;
// if (tmp < 0) goto returnFalse;
using (RentedLocalBuilder tmp = RentInt32Local())
{
Stloc(tmp);
Ldloc(iLocal);
Ldloc(tmp);
Add();
Stloc(iLocal);
Ldloc(tmp);
Ldc(0);
BltFar(returnFalse);
}
}
else
{
// i = tmp;
// if (i < 0) goto returnFalse;
Stloc(iLocal);
Ldloc(iLocal);
Ldc(0);
BltFar(returnFalse);
}
// if (i >= textSpan.Length - (minRequiredLength - 1)) goto returnFalse;
if (sets.Count > 1)
{
Debug.Assert(needLoop);
Ldloca(textSpanLocal);
Call(s_spanGetLengthMethod);
Ldc(minRequiredLength - 1);
Sub();
Ldloc(iLocal);
BleFar(returnFalse);
}
}
// if (!CharInClass(textSpan[i], prefix[0], "...")) continue;
// if (!CharInClass(textSpan[i + 1], prefix[1], "...")) continue;
// if (!CharInClass(textSpan[i + 2], prefix[2], "...")) continue;
// ...
Debug.Assert(setIndex == 0 || setIndex == 1);
for ( ; setIndex < sets.Count; setIndex++)
{
Debug.Assert(needLoop);
Ldloca(textSpanLocal);
Ldloc(iLocal);
if (sets[setIndex].Distance != 0)
{
Ldc(sets[setIndex].Distance);
Add();
}
Call(s_spanGetItemMethod);
LdindU2();
EmitMatchCharacterClass(sets[setIndex].Set, sets[setIndex].CaseInsensitive);
BrfalseFar(charNotInClassLabel);
}
// this.runtextpos = runtextpos + i;
// return true;
Ldthis();
Ldloc(_runtextposLocal);
Ldloc(iLocal);
Add();
Stfld(s_runtextposField);
Ldc(1);
Ret();
if (needLoop)
{
MarkLabel(charNotInClassLabel);
// for (...; ...; i++)
Ldloc(iLocal);
Ldc(1);
Add();
Stloc(iLocal);
// for (...; i < span.Length - (minRequiredLength - 1); ...);
MarkLabel(checkSpanLengthLabel);
Ldloc(iLocal);
Ldloca(textSpanLocal);
Call(s_spanGetLengthMethod);
if (setsToUse > 1 || primarySet.Distance != 0)
{
Ldc(minRequiredLength - 1);
Sub();
}
BltFar(loopBody);
// runtextpos = runtextend;
// return false;
BrFar(returnFalse);
}
}
}
private bool TryGenerateSimplifiedGo(RegexNode node)
{
Debug.Assert(node.Type == RegexNode.Capture, "Every generated tree should begin with a capture node");
Debug.Assert(node.ChildCount() == 1, "Capture nodes should have one child");
// RightToLeft is rare and not worth adding a lot of custom code to handle in this path.
if ((node.Options & RegexOptions.RightToLeft) != 0)
{
return false;
}
// Skip the Capture node. We handle the implicit root capture specially.
node = node.Child(0);
if (!node.SupportsSimplifiedCodeGenerationImplementation())
{
return false;
}
// We've determined that the RegexNode can be handled with this optimized path. Generate the code.
#if DEBUG
if ((_options & RegexOptions.Debug) != 0)
{
Debug.WriteLine("Using optimized non-backtracking code gen.");
}
#endif
// In some limited cases, FindFirstChar will only return true if it successfully matched the whole thing.
// This is the case, in particular, for strings. We can special case these to do essentially nothing
// in Go other than emit the capture.
if (!IsCaseInsensitive(node)) // FindFirstChar may not be 100% accurate on casing in all cultures
{
switch (node.Type)
{
case RegexNode.Multi:
case RegexNode.Notone:
case RegexNode.One:
case RegexNode.Set:
// base.Capture(0, base.runtextpos, base.runtextpos + node.Str.Length);
// base.runtextpos = base.runtextpos + node.Str.Length;
// return;
Ldthis();
Dup();
Ldc(0);
Ldthisfld(s_runtextposField);
Dup();
Ldc(node.Type == RegexNode.Multi ? node.Str!.Length : 1);
Add();
Call(s_captureMethod);
Ldthisfld(s_runtextposField);
Ldc(node.Type == RegexNode.Multi ? node.Str!.Length : 1);
Add();
Stfld(s_runtextposField);
Ret();
return true;
}
}
// Declare some locals.
LocalBuilder runtextLocal = DeclareString();
LocalBuilder originalruntextposLocal = DeclareInt32();
LocalBuilder runtextposLocal = DeclareInt32();
LocalBuilder textSpanLocal = DeclareReadOnlySpanChar();
LocalBuilder runtextendLocal = DeclareInt32();
Label stopSuccessLabel = DefineLabel();
Label doneLabel = DefineLabel();
Label originalDoneLabel = doneLabel;
if (_hasTimeout)
{
_loopTimeoutCounterLocal = DeclareInt32();
}
// CultureInfo culture = CultureInfo.CurrentCulture; // only if the whole expression or any subportion is ignoring case, and we're not using invariant
InitializeCultureForGoIfNecessary();
// string runtext = this.runtext;
// int runtextend = this.runtextend;
Mvfldloc(s_runtextField, runtextLocal);
Mvfldloc(s_runtextendField, runtextendLocal);
// int runtextpos = this.runtextpos;
// int originalruntextpos = this.runtextpos;
Ldthisfld(s_runtextposField);
Stloc(runtextposLocal);
Ldloc(runtextposLocal);
Stloc(originalruntextposLocal);
// The implementation tries to use const indexes into the span wherever possible, which we can do
// in all places except for variable-length loops. For everything else, we know at any point in
// the regex exactly how far into it we are, and we can use that to index into the span created
// at the beginning of the routine to begin at exactly where we're starting in the input. For
// variable-length loops, we index at this textSpanPos + i, and then after the loop we slice the input
// by i so that this position is still accurate for everything after it.
int textSpanPos = 0;
LoadTextSpanLocal();
// Emit the code for all nodes in the tree.
bool expressionHasCaptures = (node.Options & RegexNode.HasCapturesFlag) != 0;
EmitNode(node);
// Success:
// runtextpos += textSpanPos;
// this.runtextpos = runtextpos;
// Capture(0, originalruntextpos, runtextpos);
MarkLabel(stopSuccessLabel);
Ldthis();
Ldloc(runtextposLocal);
if (textSpanPos > 0)
{
Ldc(textSpanPos);
Add();
Stloc(runtextposLocal);
Ldloc(runtextposLocal);
}
Stfld(s_runtextposField);
Ldthis();
Ldc(0);
Ldloc(originalruntextposLocal);
Ldloc(runtextposLocal);
Call(s_captureMethod);
// If the graph contained captures, undo any remaining to handle failed matches.
if (expressionHasCaptures)
{
// while (Crawlpos() != 0) Uncapture();
Label finalReturnLabel = DefineLabel();
Br(finalReturnLabel);
MarkLabel(originalDoneLabel);
Label condition = DefineLabel();
Label body = DefineLabel();
Br(condition);
MarkLabel(body);
Ldthis();
Call(s_uncaptureMethod);
MarkLabel(condition);
Ldthis();
Call(s_crawlposMethod);
Brtrue(body);
// Done:
MarkLabel(finalReturnLabel);
}
else
{
// Done:
MarkLabel(originalDoneLabel);
}
// return;
Ret();
// Generated code successfully with non-backtracking implementation.
return true;
static bool IsCaseInsensitive(RegexNode node) => (node.Options & RegexOptions.IgnoreCase) != 0;
// Creates a span for runtext starting at runtextpos until this.runtextend.
void LoadTextSpanLocal()
{
// textSpan = runtext.AsSpan(runtextpos, this.runtextend - runtextpos);
Ldloc(runtextLocal);
Ldloc(runtextposLocal);
Ldloc(runtextendLocal);
Ldloc(runtextposLocal);
Sub();
Call(s_stringAsSpanIntIntMethod);
Stloc(textSpanLocal);
}
// Emits the sum of a constant and a value from a local.
void EmitSum(int constant, LocalBuilder? local)
{
if (local == null)
{
Ldc(constant);
}
else if (constant == 0)
{
Ldloc(local);
}
else
{
Ldloc(local);
Ldc(constant);
Add();
}
}
// Emits a check that the span is large enough at the currently known static position to handle the required additional length.
void EmitSpanLengthCheck(int requiredLength, LocalBuilder? dynamicRequiredLength = null)
{
// if ((uint)(textSpanPos + requiredLength + dynamicRequiredLength - 1) >= (uint)textSpan.Length) goto Done;
Debug.Assert(requiredLength > 0);
EmitSum(textSpanPos + requiredLength - 1, dynamicRequiredLength);
Ldloca(textSpanLocal);
Call(s_spanGetLengthMethod);
BgeUnFar(doneLabel);
}
// Emits code to get ref textSpan[textSpanPos]
void EmitTextSpanOffset()
{
Ldloc(textSpanLocal);
Call(s_memoryMarshalGetReference);
if (textSpanPos > 0)
{
Ldc(textSpanPos * sizeof(char));
Add();
}
}
// Adds the value of textSpanPos into the runtextpos local, slices textspan by the corresponding amount,
// and zeros out textSpanPos.
void TransferTextSpanPosToRunTextPos()
{
if (textSpanPos > 0)
{
// runtextpos += textSpanPos;
Ldloc(runtextposLocal);
Ldc(textSpanPos);
Add();
Stloc(runtextposLocal);
// textSpan = textSpan.Slice(textSpanPos);
Ldloca(textSpanLocal);
Ldc(textSpanPos);
Call(s_spanSliceIntMethod);
Stloc(textSpanLocal);
// textSpanPos = 0;
textSpanPos = 0;
}
}
// Emits the code for an atomic alternate, one that once a branch successfully matches is non-backtracking into it.
// This amounts to generating the code for each branch, with failures in a branch resetting state to what it was initially
// and then jumping to the next branch. We don't need to worry about uncapturing, because capturing is only allowed for the
// implicit capture that happens for the whole match at the end.
void EmitAtomicAlternate(RegexNode node)
{
// int startingTextSpanPos = textSpanPos;
// int startingRunTextPos = runtextpos;
//
// Branch0(); // jumps to NextBranch1 on failure
// goto Success;
//
// NextBranch1:
// runtextpos = originalruntextpos;
// textSpan = originalTextSpan;
// Branch1(); // jumps to NextBranch2 on failure
// goto Success;
//
// ...
//
// NextBranchN:
// runtextpos = startingRunTextPos;
// textSpan = this.runtext.AsSpan(runtextpos, this.runtextend - runtextpos);
// textSpanPos = startingTextSpanPos;
// BranchN(); // jumps to Done on failure
// Save off runtextpos. We'll need to reset this each time a branch fails.
LocalBuilder startingRunTextPos = DeclareInt32();
Ldloc(runtextposLocal);
Stloc(startingRunTextPos);
int startingTextSpanPos = textSpanPos;
// If the alternation's branches contain captures, save off the relevant
// state. Note that this is only about subexpressions within the alternation,
// as the alternation is atomic, so we're not concerned about captures after
// the alternation.
LocalBuilder? startingCrawlpos = null;
if ((node.Options & RegexNode.HasCapturesFlag) != 0)
{
startingCrawlpos = DeclareInt32();
Ldthis();
Call(s_crawlposMethod);
Stloc(startingCrawlpos);
}
// Label to jump to when any branch completes successfully.
Label doneAlternate = DefineLabel();
// A failure in a branch other than the last should jump to the next
// branch, not to the final done.
Label originalDoneLabel = doneLabel;
int childCount = node.ChildCount();
for (int i = 0; i < childCount - 1; i++)
{
Label nextBranch = DefineLabel();
doneLabel = nextBranch;
// Emit the code for each branch.
EmitNode(node.Child(i));
// If we get here in the generated code, the branch completed successfully.
// Before jumping to the end, we need to zero out textSpanPos, so that no
// matter what the value is after the branch, whatever follows the alternate
// will see the same textSpanPos.
TransferTextSpanPosToRunTextPos();
BrFar(doneAlternate);
// Reset state for next branch and loop around to generate it. This includes
// setting runtextpos back to what it was at the beginning of the alternation,
// updating textSpan to be the full length it was, and if there's a capture that
// needs to be reset, uncapturing it.
MarkLabel(nextBranch);
Ldloc(startingRunTextPos);
Stloc(runtextposLocal);
LoadTextSpanLocal();
textSpanPos = startingTextSpanPos;
if (startingCrawlpos != null)
{
EmitUncaptureUntil(startingCrawlpos);
}
}
// If the final branch fails, that's like any other failure, and we jump to
// done (unless we have captures we need to unwind first, in which case we uncapture
// them and then jump to done).
if (startingCrawlpos != null)
{
Label uncapture = DefineLabel();
doneLabel = uncapture;
EmitNode(node.Child(childCount - 1));
doneLabel = originalDoneLabel;
TransferTextSpanPosToRunTextPos();
Br(doneAlternate);
MarkLabel(uncapture);
EmitUncaptureUntil(startingCrawlpos);
BrFar(doneLabel);
}
else
{
doneLabel = originalDoneLabel;
EmitNode(node.Child(childCount - 1));
TransferTextSpanPosToRunTextPos();
}
// Successfully completed the alternate.
MarkLabel(doneAlternate);
Debug.Assert(textSpanPos == 0);
}
// Emits the code for a Capture node.
void EmitCapture(RegexNode node, RegexNode? subsequent = null)
{
Debug.Assert(node.N == -1);
LocalBuilder startingRunTextPos = DeclareInt32();
// Get the capture number. This needs to be kept
// in sync with MapCapNum in RegexWriter.
Debug.Assert(node.Type == RegexNode.Capture);
Debug.Assert(node.N == -1, "Currently only support capnum, not uncapnum");
int capnum = node.M;
if (capnum != -1 && _code!.Caps != null)
{
capnum = (int)_code.Caps[capnum]!;
}
// runtextpos += textSpanPos;
// textSpan = textSpan.Slice(textSpanPos);
// startingRunTextPos = runtextpos;
TransferTextSpanPosToRunTextPos();
Ldloc(runtextposLocal);
Stloc(startingRunTextPos);
// Emit child node.
EmitNode(node.Child(0), subsequent);
// runtextpos += textSpanPos;
// textSpan = textSpan.Slice(textSpanPos);
// Capture(capnum, startingRunTextPos, runtextpos);
TransferTextSpanPosToRunTextPos();
Ldthis();
Ldc(capnum);
Ldloc(startingRunTextPos);
Ldloc(runtextposLocal);
Call(s_captureMethod);
}
// Emits code to unwind the capture stack until the crawl position specified in the provided local.
void EmitUncaptureUntil(LocalBuilder startingCrawlpos)
{
Debug.Assert(startingCrawlpos != null);
// while (Crawlpos() != startingCrawlpos) Uncapture();
Label condition = DefineLabel();
Label body = DefineLabel();
Br(condition);
MarkLabel(body);
Ldthis();
Call(s_uncaptureMethod);
MarkLabel(condition);
Ldthis();
Call(s_crawlposMethod);
Ldloc(startingCrawlpos);
Bne(body);
}
// Emits the code to handle a positive lookahead assertion.
void EmitPositiveLookaheadAssertion(RegexNode node)
{
// Save off runtextpos. We'll need to reset this upon successful completion of the lookahead.
LocalBuilder startingRunTextPos = DeclareInt32();
Ldloc(runtextposLocal);
Stloc(startingRunTextPos);
int startingTextSpanPos = textSpanPos;
// Emit the child.
EmitNode(node.Child(0));
// After the child completes successfully, reset the text positions.
// Do not reset captures, which persist beyond the lookahead.
Ldloc(startingRunTextPos);
Stloc(runtextposLocal);
LoadTextSpanLocal();
textSpanPos = startingTextSpanPos;
}
// Emits the code to handle a negative lookahead assertion.
void EmitNegativeLookaheadAssertion(RegexNode node)
{
// Save off runtextpos. We'll need to reset this upon successful completion of the lookahead.
LocalBuilder startingRunTextPos = DeclareInt32();
Ldloc(runtextposLocal);
Stloc(startingRunTextPos);
int startingTextSpanPos = textSpanPos;
Label originalDoneLabel = doneLabel;
Label negativeLookaheadDoneLabel = DefineLabel();
doneLabel = negativeLookaheadDoneLabel;
// Emit the child.
EmitNode(node.Child(0));
// If the generated code ends up here, it matched the lookahead, which actually
// means failure for a _negative_ lookahead, so we need to jump to the original done.
BrFar(originalDoneLabel);
// Failures (success for a negative lookahead) jump here.
MarkLabel(negativeLookaheadDoneLabel);
Debug.Assert(doneLabel == negativeLookaheadDoneLabel);
doneLabel = originalDoneLabel;
// After the child completes in failure (success for negative lookahead), reset the text positions.
Ldloc(startingRunTextPos);
Stloc(runtextposLocal);
LoadTextSpanLocal();
textSpanPos = startingTextSpanPos;
}
// Emits the code for the node.
void EmitNode(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true)
{
if (!StackHelper.TryEnsureSufficientExecutionStack())
{
StackHelper.CallOnEmptyStack(EmitNode, node, subsequent, emitLengthChecksIfRequired);
return;
}
switch (node.Type)
{
case RegexNode.One:
case RegexNode.Notone:
case RegexNode.Set:
EmitSingleChar(node, emitLengthChecksIfRequired);
break;
case RegexNode.Boundary:
case RegexNode.NonBoundary:
case RegexNode.ECMABoundary:
case RegexNode.NonECMABoundary:
EmitBoundary(node);
break;
case RegexNode.Beginning:
case RegexNode.Start:
case RegexNode.Bol:
case RegexNode.Eol:
case RegexNode.End:
case RegexNode.EndZ:
EmitAnchors(node);
break;
case RegexNode.Multi:
EmitMultiChar(node, emitLengthChecksIfRequired);
break;
case RegexNode.Oneloopatomic:
case RegexNode.Notoneloopatomic:
case RegexNode.Setloopatomic:
EmitSingleCharAtomicLoop(node);
break;
case RegexNode.Loop:
EmitAtomicNodeLoop(node);
break;
case RegexNode.Lazyloop:
// An atomic lazy loop amounts to doing the minimum amount of work possible.
// That means iterating as little as is required, which means a repeater
// for the min, and if min is 0, doing nothing.
Debug.Assert(node.M == node.N || (node.Next != null && node.Next.Type == RegexNode.Atomic));
if (node.M > 0)
{
EmitNodeRepeater(node);
}
break;
case RegexNode.Atomic:
EmitNode(node.Child(0), subsequent);
break;
case RegexNode.Alternate:
EmitAtomicAlternate(node);
break;
case RegexNode.Oneloop:
case RegexNode.Notoneloop:
case RegexNode.Setloop:
EmitSingleCharLoop(node, subsequent, emitLengthChecksIfRequired);
break;
case RegexNode.Onelazy:
case RegexNode.Notonelazy:
case RegexNode.Setlazy:
EmitSingleCharFixedRepeater(node, emitLengthChecksIfRequired);
break;
case RegexNode.Concatenate:
EmitConcatenation(node, subsequent, emitLengthChecksIfRequired);
break;
case RegexNode.Capture:
EmitCapture(node, subsequent);
break;
case RegexNode.Require:
EmitPositiveLookaheadAssertion(node);
break;
case RegexNode.Prevent:
EmitNegativeLookaheadAssertion(node);
break;
case RegexNode.Nothing:
BrFar(doneLabel);
break;
case RegexNode.Empty:
// Emit nothing.
break;
case RegexNode.UpdateBumpalong:
EmitUpdateBumpalong();
break;
default:
Debug.Fail($"Unexpected node type: {node.Type}");
break;
}
}
// Emits the code to handle updating base.runtextpos to runtextpos in response to
// an UpdateBumpalong node. This is used when we want to inform the scan loop that
// it should bump from this location rather than from the original location.
void EmitUpdateBumpalong()
{
// base.runtextpos = runtextpos;
TransferTextSpanPosToRunTextPos();
Ldthis();
Ldloc(runtextposLocal);
Stfld(s_runtextposField);
}
// Emits code for a concatenation
void EmitConcatenation(RegexNode node, RegexNode? subsequent, bool emitLengthChecksIfRequired)
{
int childCount = node.ChildCount();
for (int i = 0; i < childCount; i++)
{
if (emitLengthChecksIfRequired && node.TryGetJoinableLengthCheckChildRange(i, out int requiredLength, out int exclusiveEnd))
{
EmitSpanLengthCheck(requiredLength);
for (; i < exclusiveEnd; i++)
{
EmitNode(node.Child(i), i + 1 < childCount ? node.Child(i + 1) : subsequent, emitLengthChecksIfRequired: false);
}
i--;
continue;
}
EmitNode(node.Child(i), i + 1 < childCount ? node.Child(i + 1) : subsequent);
}
}
// Emits the code to handle a single-character match.
void EmitSingleChar(RegexNode node, bool emitLengthCheck = true, LocalBuilder? offset = null)
{
// This only emits a single check, but it's called from the looping constructs in a loop
// to generate the code for a single check, so we check for each "family" (one, notone, set)
// rather than only for the specific single character nodes.
// if ((uint)(textSpanPos + offset) >= textSpan.Length || textSpan[textSpanPos + offset] != ch) goto Done;
if (emitLengthCheck)
{
EmitSpanLengthCheck(1, offset);
}
Ldloca(textSpanLocal);
EmitSum(textSpanPos, offset);
Call(s_spanGetItemMethod);
LdindU2();
if (node.IsSetFamily)
{
EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node));
BrfalseFar(doneLabel);
}
else
{
if (IsCaseInsensitive(node))
{
CallToLower();
}
Ldc(node.Ch);
if (node.IsOneFamily)
{
BneFar(doneLabel);
}
else // IsNotoneFamily
{
BeqFar(doneLabel);
}
}
textSpanPos++;
}
// Emits the code to handle a boundary check on a character.
void EmitBoundary(RegexNode node)
{
// if (!IsBoundary(runtextpos + textSpanPos, this.runtextbeg, this.runtextend)) goto doneLabel;
Ldthis();
Ldloc(runtextposLocal);
if (textSpanPos > 0)
{
Ldc(textSpanPos);
Add();
}
Ldthisfld(s_runtextbegField);
Ldloc(runtextendLocal);
switch (node.Type)
{
case RegexNode.Boundary:
Call(s_isBoundaryMethod);
BrfalseFar(doneLabel);
break;
case RegexNode.NonBoundary:
Call(s_isBoundaryMethod);
BrtrueFar(doneLabel);
break;
case RegexNode.ECMABoundary:
Call(s_isECMABoundaryMethod);
BrfalseFar(doneLabel);
break;
default:
Debug.Assert(node.Type == RegexNode.NonECMABoundary);
Call(s_isECMABoundaryMethod);
BrtrueFar(doneLabel);
break;
}
}
// Emits the code to handle various anchors.
void EmitAnchors(RegexNode node)
{
Debug.Assert(textSpanPos >= 0);
switch (node.Type)
{
case RegexNode.Beginning:
case RegexNode.Start:
if (textSpanPos > 0)
{
// If we statically know we've already matched part of the regex, there's no way we're at the
// beginning or start, as we've already progressed past it.
BrFar(doneLabel);
}
else
{
// if (runtextpos > this.runtextbeg/start) goto doneLabel;
Ldloc(runtextposLocal);
Ldthisfld(node.Type == RegexNode.Beginning ? s_runtextbegField : s_runtextstartField);
BneFar(doneLabel);
}
break;
case RegexNode.Bol:
if (textSpanPos > 0)
{
// if (textSpan[textSpanPos - 1] != '\n') goto doneLabel;
Ldloca(textSpanLocal);
Ldc(textSpanPos - 1);
Call(s_spanGetItemMethod);
LdindU2();
Ldc('\n');
BneFar(doneLabel);
}
else
{
// We can't use our textSpan in this case, because we'd need to access textSpan[-1], so we access the runtext field directly:
// if (runtextpos > this.runtextbeg && this.runtext[runtextpos - 1] != '\n') goto doneLabel;
Label success = DefineLabel();
Ldloc(runtextposLocal);
Ldthisfld(s_runtextbegField);
Ble(success);
Ldthisfld(s_runtextField);
Ldloc(runtextposLocal);
Ldc(1);
Sub();
Call(s_stringGetCharsMethod);
Ldc('\n');
BneFar(doneLabel);
MarkLabel(success);
}
break;
case RegexNode.End:
// if (textSpanPos < textSpan.Length) goto doneLabel;
Ldc(textSpanPos);
Ldloca(textSpanLocal);
Call(s_spanGetLengthMethod);
BltUnFar(doneLabel);
break;
case RegexNode.EndZ:
// if (textSpanPos < textSpan.Length - 1) goto doneLabel;
Ldc(textSpanPos);
Ldloca(textSpanLocal);
Call(s_spanGetLengthMethod);
Ldc(1);
Sub();
BltFar(doneLabel);
goto case RegexNode.Eol;
case RegexNode.Eol:
// if (textSpanPos < textSpan.Length && textSpan[textSpanPos] != '\n') goto doneLabel;
{
Label success = DefineLabel();
Ldc(textSpanPos);
Ldloca(textSpanLocal);
Call(s_spanGetLengthMethod);
BgeUn(success);
Ldloca(textSpanLocal);
Ldc(textSpanPos);
Call(s_spanGetItemMethod);
LdindU2();
Ldc('\n');
BneFar(doneLabel);
MarkLabel(success);
}
break;
}
}
// Emits the code to handle a multiple-character match.
void EmitMultiChar(RegexNode node, bool emitLengthCheck = true)
{
bool caseInsensitive = IsCaseInsensitive(node);
// If the multi string's length exceeds the maximum length we want to unroll, instead generate a call to StartsWith.
// Each character that we unroll results in code generation that increases the size of both the IL and the resulting asm,
// and with a large enough string, that can cause significant overhead as well as even risk stack overflow due to
// having an obscenely long method. Such long string lengths in a pattern are generally quite rare. However, we also
// want to unroll for shorter strings, because the overhead of invoking StartsWith instead of doing a few simple
// inline comparisons is very measurable, especially if we're doing a culture-sensitive comparison and StartsWith
// accesses CultureInfo.CurrentCulture on each call. We need to be cognizant not only of the cost if the whole
// string matches, but also the cost when the comparison fails early on, and thus we pay for the call overhead
// but don't reap the benefits of all the vectorization StartsWith can do.
const int MaxUnrollLength = 64;
if (!caseInsensitive && // StartsWith(..., XxIgnoreCase) won't necessarily be the same as char-by-char comparison
node.Str!.Length > MaxUnrollLength)
{
// if (!textSpan.Slice(textSpanPos).StartsWith("...") goto doneLabel;
Ldloca(textSpanLocal);
Ldc(textSpanPos);
Call(s_spanSliceIntMethod);
Ldstr(node.Str);
Call(s_stringAsSpanMethod);
Call(s_spanStartsWith);
BrfalseFar(doneLabel);
textSpanPos += node.Str.Length;
return;
}
// Emit the length check for the whole string. If the generated code gets past this point,
// we know the span is at least textSpanPos + s.Length long.
ReadOnlySpan<char> s = node.Str;
if (emitLengthCheck)
{
EmitSpanLengthCheck(s.Length);
}
// If we're doing a case-insensitive comparison, we need to lower case each character,
// so we just go character-by-character. But if we're not, we try to process multiple
// characters at a time; this is helpful not only for throughput but also in reducing
// the amount of IL and asm that results from this unrolling. This optimization
// is subject to endianness issues if the generated code is used on a machine with a
// different endianness, but that's not a concern when the code is emitted by the
// same process that then uses it.
if (!caseInsensitive)
{
// On 64-bit, process 4 characters at a time until the string isn't at least 4 characters long.
if (IntPtr.Size == 8)
{
const int CharsPerInt64 = 4;
while (s.Length >= CharsPerInt64)
{
// if (Unsafe.ReadUnaligned<long>(ref Unsafe.Add(ref MemoryMarshal.GetReference(textSpan), textSpanPos)) != value) goto doneLabel;
EmitTextSpanOffset();
Unaligned(1);
LdindI8();
LdcI8(MemoryMarshal.Read<long>(MemoryMarshal.AsBytes(s)));
BneFar(doneLabel);
textSpanPos += CharsPerInt64;
s = s.Slice(CharsPerInt64);
}
}
// Of what remains, process 2 characters at a time until the string isn't at least 2 characters long.
const int CharsPerInt32 = 2;
while (s.Length >= CharsPerInt32)
{
// if (Unsafe.ReadUnaligned<int>(ref Unsafe.Add(ref MemoryMarshal.GetReference(textSpan), textSpanPos)) != value) goto doneLabel;
EmitTextSpanOffset();
Unaligned(1);
LdindI4();
Ldc(MemoryMarshal.Read<int>(MemoryMarshal.AsBytes(s)));
BneFar(doneLabel);
textSpanPos += CharsPerInt32;
s = s.Slice(CharsPerInt32);
}
}
// Finally, process all of the remaining characters one by one.
for (int i = 0; i < s.Length; i++)
{
// if (s[i] != textSpan[textSpanPos++]) goto doneLabel;
EmitTextSpanOffset();
textSpanPos++;
LdindU2();
if (caseInsensitive)
{
CallToLower();
}
Ldc(s[i]);
BneFar(doneLabel);
}
}
// Emits the code to handle a backtracking, single-character loop.
void EmitSingleCharLoop(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true)
{
// If this is actually a repeater, emit that instead; no backtracking necessary.
if (node.M == node.N)
{
EmitSingleCharFixedRepeater(node, emitLengthChecksIfRequired);
return;
}
Debug.Assert(node.M < node.N);
Label backtrackingLabel = DefineLabel();
Label endLoop = DefineLabel();
LocalBuilder startingPos = DeclareInt32();
LocalBuilder endingPos = DeclareInt32();
LocalBuilder crawlPos = DeclareInt32();
// We're about to enter a loop, so ensure our text position is 0.
TransferTextSpanPosToRunTextPos();
// int startingPos = runtextpos;
// Single char atomic loop
// int endingPos = runtextpos;
// int crawlPos = base.Crawlpos();
// startingPos += node.M;
// goto endLoop;
Ldloc(runtextposLocal);
Stloc(startingPos);
EmitSingleCharAtomicLoop(node);
TransferTextSpanPosToRunTextPos();
Ldloc(runtextposLocal);
Stloc(endingPos);
Ldthis();
Call(s_crawlposMethod);
Stloc(crawlPos);
if (node.M > 0)
{
Ldloc(startingPos);
Ldc(node.M);
Add();
Stloc(startingPos);
}
Br(endLoop);
// Backtracking:
// if (startingPos >= endingPos) goto doneLabel;
MarkLabel(backtrackingLabel);
Ldloc(startingPos);
Ldloc(endingPos);
BgeFar(doneLabel);
doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes
// while (base.Crawlpos() != crawlPos) Uncapture();
if (expressionHasCaptures)
{
// Uncapture any captures if the expression has any. It's possible the captures it has
// are before this node, in which case this is wasted effort, but still functionally correct.
EmitUncaptureUntil(crawlPos);
}
if (subsequent?.FindStartingCharacter() is char subsequentCharacter)
{
// endingPos = runtext.LastIndexOf(subsequentCharacter, endingPos - 1, endingPos - startingPos);
// if (endingPos < 0)
// {
// goto doneLabel;
// }
Ldloc(runtextLocal);
Ldc(subsequentCharacter);
Ldloc(endingPos);
Ldc(1);
Sub();
Ldloc(endingPos);
Ldloc(startingPos);
Sub();
Call(s_stringLastIndexOfCharIntInt);
Stloc(endingPos);
Ldloc(endingPos);
Ldc(0);
BltFar(doneLabel);
}
else
{
// endingPos--;
Ldloc(endingPos);
Ldc(1);
Sub();
Stloc(endingPos);
}
// runtextpos = endingPos;
Ldloc(endingPos);
Stloc(runtextposLocal);
// textspan = runtext.AsSpan(runtextpos, runtextend - runtextpos);
LoadTextSpanLocal();
MarkLabel(endLoop);
}
// Emits the code to handle a loop (repeater) with a fixed number of iterations.
// RegexNode.M is used for the number of iterations; RegexNode.N is ignored.
void EmitSingleCharFixedRepeater(RegexNode node, bool emitLengthChecksIfRequired = true)
{
int iterations = node.M;
if (iterations == 0)
{
// No iterations, nothing to do.
return;
}
// if ((uint)(textSpanPos + iterations - 1) >= (uint)textSpan.Length) goto doneLabel;
if (emitLengthChecksIfRequired)
{
EmitSpanLengthCheck(iterations);
}
// Arbitrary limit for unrolling vs creating a loop. We want to balance size in the generated
// code with other costs, like the (small) overhead of slicing to create the temp span to iterate.
const int MaxUnrollSize = 16;
if (iterations <= MaxUnrollSize)
{
// if (textSpan[textSpanPos] != c1 ||
// textSpan[textSpanPos + 1] != c2 ||
// ...)
// goto doneLabel;
for (int i = 0; i < iterations; i++)
{
EmitSingleChar(node, emitLengthCheck: false);
}
}
else
{
// ReadOnlySpan<char> tmp = textSpan.Slice(textSpanPos, iterations);
// for (int i = 0; i < tmp.Length; i++)
// {
// TimeoutCheck();
// if (tmp[i] != ch) goto Done;
// }
// textSpanPos += iterations;
Label conditionLabel = DefineLabel();
Label bodyLabel = DefineLabel();
using RentedLocalBuilder spanLocal = RentReadOnlySpanCharLocal();
Ldloca(textSpanLocal);
Ldc(textSpanPos);
Ldc(iterations);
Call(s_spanSliceIntIntMethod);
Stloc(spanLocal);
using RentedLocalBuilder iterationLocal = RentInt32Local();
Ldc(0);
Stloc(iterationLocal);
BrFar(conditionLabel);
MarkLabel(bodyLabel);
EmitTimeoutCheck();
LocalBuilder tmpTextSpanLocal = textSpanLocal; // we want EmitSingleChar to refer to this temporary
int tmpTextSpanPos = textSpanPos;
textSpanLocal = spanLocal;
textSpanPos = 0;
EmitSingleChar(node, emitLengthCheck: false, offset: iterationLocal);
textSpanLocal = tmpTextSpanLocal;
textSpanPos = tmpTextSpanPos;
Ldloc(iterationLocal);
Ldc(1);
Add();
Stloc(iterationLocal);
MarkLabel(conditionLabel);
Ldloc(iterationLocal);
Ldloca(spanLocal);
Call(s_spanGetLengthMethod);
BltFar(bodyLabel);
textSpanPos += iterations;
}
}
// Emits the code to handle a loop (repeater) with a fixed number of iterations.
// This is used both to handle the case of A{5, 5} where the min and max are equal,
// and also to handle part of the case of A{3, 5}, where this method is called to
// handle the A{3, 3} portion, and then remaining A{0, 2} is handled separately.
void EmitNodeRepeater(RegexNode node)
{
int iterations = node.M;
Debug.Assert(iterations > 0);
if (iterations == 1)
{
Debug.Assert(node.ChildCount() == 1);
EmitNode(node.Child(0));
return;
}
// Ensure textSpanPos is 0 prior to emitting the child.
TransferTextSpanPosToRunTextPos();
// for (int i = 0; i < iterations; i++)
// {
// TimeoutCheck();
// if (textSpan[textSpanPos] != ch) goto Done;
// }
Label conditionLabel = DefineLabel();
Label bodyLabel = DefineLabel();
LocalBuilder iterationLocal = DeclareInt32();
Ldc(0);
Stloc(iterationLocal);
BrFar(conditionLabel);
MarkLabel(bodyLabel);
EmitTimeoutCheck();
Debug.Assert(node.ChildCount() == 1);
Debug.Assert(textSpanPos == 0);
EmitNode(node.Child(0));
TransferTextSpanPosToRunTextPos();
Ldloc(iterationLocal);
Ldc(1);
Add();
Stloc(iterationLocal);
MarkLabel(conditionLabel);
Ldloc(iterationLocal);
Ldc(iterations);
BltFar(bodyLabel);
}
// Emits the code to handle a non-backtracking, variable-length loop around a single character comparison.
void EmitSingleCharAtomicLoop(RegexNode node)
{
// If this is actually a repeater, emit that instead.
if (node.M == node.N)
{
EmitSingleCharFixedRepeater(node);
return;
}
// If this is actually an optional single char, emit that instead.
if (node.M == 0 && node.N == 1)
{
EmitAtomicSingleCharZeroOrOne(node);
return;
}
Debug.Assert(node.N > node.M);
int minIterations = node.M;
int maxIterations = node.N;
using RentedLocalBuilder iterationLocal = RentInt32Local();
Label atomicLoopDoneLabel = DefineLabel();
Span<char> setChars = stackalloc char[5]; // max optimized by IndexOfAny today
int numSetChars = 0;
if (node.IsNotoneFamily &&
maxIterations == int.MaxValue &&
(!IsCaseInsensitive(node)))
{
// For Notone, we're looking for a specific character, as everything until we find
// it is consumed by the loop. If we're unbounded, such as with ".*" and if we're case-sensitive,
// we can use the vectorized IndexOf to do the search, rather than open-coding it. The unbounded
// restriction is purely for simplicity; it could be removed in the future with additional code to
// handle the unbounded case.
// int i = textSpan.Slice(textSpanPos).IndexOf(char);
if (textSpanPos > 0)
{
Ldloca(textSpanLocal);
Ldc(textSpanPos);
Call(s_spanSliceIntMethod);
}
else
{
Ldloc(textSpanLocal);
}
Ldc(node.Ch);
Call(s_spanIndexOfChar);
Stloc(iterationLocal);
// if (i >= 0) goto atomicLoopDoneLabel;
Ldloc(iterationLocal);
Ldc(0);
BgeFar(atomicLoopDoneLabel);
// i = textSpan.Length - textSpanPos;
Ldloca(textSpanLocal);
Call(s_spanGetLengthMethod);
if (textSpanPos > 0)
{
Ldc(textSpanPos);
Sub();
}
Stloc(iterationLocal);
}
else if (node.IsSetFamily &&
maxIterations == int.MaxValue &&
!IsCaseInsensitive(node) &&
(numSetChars = RegexCharClass.GetSetChars(node.Str!, setChars)) != 0 &&
RegexCharClass.IsNegated(node.Str!))
{
// If the set is negated and contains only a few characters (if it contained 1 and was negated, it would
// have been reduced to a Notone), we can use an IndexOfAny to find any of the target characters.
// As with the notoneloopatomic above, the unbounded constraint is purely for simplicity.
Debug.Assert(numSetChars > 1);
// int i = textSpan.Slice(textSpanPos).IndexOfAny(ch1, ch2, ...);
if (textSpanPos > 0)
{
Ldloca(textSpanLocal);
Ldc(textSpanPos);
Call(s_spanSliceIntMethod);
}
else
{
Ldloc(textSpanLocal);
}
switch (numSetChars)
{
case 2:
Ldc(setChars[0]);
Ldc(setChars[1]);
Call(s_spanIndexOfAnyCharChar);
break;
case 3:
Ldc(setChars[0]);
Ldc(setChars[1]);
Ldc(setChars[2]);
Call(s_spanIndexOfAnyCharCharChar);
break;
default:
Ldstr(setChars.Slice(0, numSetChars).ToString());
Call(s_stringAsSpanMethod);
Call(s_spanIndexOfSpan);
break;
}
Stloc(iterationLocal);
// if (i >= 0) goto atomicLoopDoneLabel;
Ldloc(iterationLocal);
Ldc(0);
BgeFar(atomicLoopDoneLabel);
// i = textSpan.Length - textSpanPos;
Ldloca(textSpanLocal);
Call(s_spanGetLengthMethod);
if (textSpanPos > 0)
{
Ldc(textSpanPos);
Sub();
}
Stloc(iterationLocal);
}
else if (node.IsSetFamily && maxIterations == int.MaxValue && node.Str == RegexCharClass.AnyClass)
{
// .* was used with RegexOptions.Singleline, which means it'll consume everything. Just jump to the end.
// The unbounded constraint is the same as in the Notone case above, done purely for simplicity.
// int i = runtextend - runtextpos;
TransferTextSpanPosToRunTextPos();
Ldloc(runtextendLocal);
Ldloc(runtextposLocal);
Sub();
Stloc(iterationLocal);
}
else
{
// For everything else, do a normal loop.
// Transfer text pos to runtextpos to help with bounds check elimination on the loop.
TransferTextSpanPosToRunTextPos();
Label conditionLabel = DefineLabel();
Label bodyLabel = DefineLabel();
// int i = 0;
Ldc(0);
Stloc(iterationLocal);
BrFar(conditionLabel);
// Body:
// TimeoutCheck();
MarkLabel(bodyLabel);
EmitTimeoutCheck();
// if ((uint)i >= (uint)textSpan.Length) goto atomicLoopDoneLabel;
Ldloc(iterationLocal);
Ldloca(textSpanLocal);
Call(s_spanGetLengthMethod);
BgeUnFar(atomicLoopDoneLabel);
// if (textSpan[i] != ch) goto atomicLoopDoneLabel;
Ldloca(textSpanLocal);
Ldloc(iterationLocal);
Call(s_spanGetItemMethod);
LdindU2();
if (node.IsSetFamily)
{
EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node));
BrfalseFar(atomicLoopDoneLabel);
}
else
{
if (IsCaseInsensitive(node))
{
CallToLower();
}
Ldc(node.Ch);
if (node.IsOneFamily)
{
BneFar(atomicLoopDoneLabel);
}
else // IsNotoneFamily
{
BeqFar(atomicLoopDoneLabel);
}
}
// i++;
Ldloc(iterationLocal);
Ldc(1);
Add();
Stloc(iterationLocal);
// if (i >= maxIterations) goto atomicLoopDoneLabel;
MarkLabel(conditionLabel);
if (maxIterations != int.MaxValue)
{
Ldloc(iterationLocal);
Ldc(maxIterations);
BltFar(bodyLabel);
}
else
{
BrFar(bodyLabel);
}
}
// Done:
MarkLabel(atomicLoopDoneLabel);
// Check to ensure we've found at least min iterations.
if (minIterations > 0)
{
Ldloc(iterationLocal);
Ldc(minIterations);
BltFar(doneLabel);
}
// Now that we've completed our optional iterations, advance the text span
// and runtextpos by the number of iterations completed.
// textSpan = textSpan.Slice(i);
Ldloca(textSpanLocal);
Ldloc(iterationLocal);
Call(s_spanSliceIntMethod);
Stloc(textSpanLocal);
// runtextpos += i;
Ldloc(runtextposLocal);
Ldloc(iterationLocal);
Add();
Stloc(runtextposLocal);
}
// Emits the code to handle a non-backtracking optional zero-or-one loop.
void EmitAtomicSingleCharZeroOrOne(RegexNode node)
{
Debug.Assert(node.M == 0 && node.N == 1);
Label skipUpdatesLabel = DefineLabel();
// if ((uint)textSpanPos >= (uint)textSpan.Length) goto skipUpdatesLabel;
Ldc(textSpanPos);
Ldloca(textSpanLocal);
Call(s_spanGetLengthMethod);
BgeUnFar(skipUpdatesLabel);
// if (textSpan[textSpanPos] != ch) goto skipUpdatesLabel;
Ldloca(textSpanLocal);
Ldc(textSpanPos);
Call(s_spanGetItemMethod);
LdindU2();
if (node.IsSetFamily)
{
EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node));
BrfalseFar(skipUpdatesLabel);
}
else
{
if (IsCaseInsensitive(node))
{
CallToLower();
}
Ldc(node.Ch);
if (node.IsOneFamily)
{
BneFar(skipUpdatesLabel);
}
else // IsNotoneFamily
{
BeqFar(skipUpdatesLabel);
}
}
// textSpan = textSpan.Slice(1);
Ldloca(textSpanLocal);
Ldc(1);
Call(s_spanSliceIntMethod);
Stloc(textSpanLocal);
// runtextpos++;
Ldloc(runtextposLocal);
Ldc(1);
Add();
Stloc(runtextposLocal);
MarkLabel(skipUpdatesLabel);
}
// Emits the code to handle a non-backtracking, variable-length loop around another node.
void EmitAtomicNodeLoop(RegexNode node)
{
Debug.Assert(node.Type == RegexNode.Loop);
Debug.Assert(node.M == node.N || (node.Next != null && (node.Next.Type is RegexNode.Atomic or RegexNode.Capture)));
Debug.Assert(node.M < int.MaxValue);
// If this is actually a repeater, emit that instead.
if (node.M == node.N)
{
EmitNodeRepeater(node);
return;
}
LocalBuilder iterationLocal = DeclareInt32();
LocalBuilder startingRunTextPosLocal = DeclareInt32();
Label originalDoneLabel = doneLabel;
Label atomicNodeLabel = DefineLabel();
doneLabel = atomicNodeLabel;
// We might loop any number of times. In order to ensure this loop
// and subsequent code sees textSpanPos the same regardless, we always need it to contain
// the same value, and the easiest such value is 0. So, we transfer
// textSpanPos to runtextpos, and ensure that any path out of here has
// textSpanPos as 0.
TransferTextSpanPosToRunTextPos();
Label conditionLabel = DefineLabel();
Label bodyLabel = DefineLabel();
Debug.Assert(node.N > node.M);
int minIterations = node.M;
int maxIterations = node.N;
// int i = 0;
Ldc(0);
Stloc(iterationLocal);
BrFar(conditionLabel);
// Body:
// TimeoutCheck();
// if (!match) goto Done;
MarkLabel(bodyLabel);
EmitTimeoutCheck();
// Iteration body
Label successfulIterationLabel = DefineLabel();
Label prevDone = doneLabel;
Label iterationDone = DefineLabel();
doneLabel = iterationDone;
// Save off runtextpos.
Ldloc(runtextposLocal);
Stloc(startingRunTextPosLocal);
// Emit the child.
Debug.Assert(textSpanPos == 0);
EmitNode(node.Child(0));
TransferTextSpanPosToRunTextPos(); // ensure textSpanPos remains 0
Br(successfulIterationLabel); // iteration succeeded
// If the generated code gets here, the iteration failed.
// Reset state, branch to done.
MarkLabel(iterationDone);
Debug.Assert(doneLabel == iterationDone);
doneLabel = prevDone;
Ldloc(startingRunTextPosLocal);
Stloc(runtextposLocal);
BrFar(doneLabel);
// Successful iteration.
MarkLabel(successfulIterationLabel);
// i++;
Ldloc(iterationLocal);
Ldc(1);
Add();
Stloc(iterationLocal);
// if (i >= maxIterations) goto doneLabel;
MarkLabel(conditionLabel);
if (maxIterations != int.MaxValue)
{
Ldloc(iterationLocal);
Ldc(maxIterations);
BltFar(bodyLabel);
}
else
{
BrFar(bodyLabel);
}
// Done:
MarkLabel(atomicNodeLabel);
Debug.Assert(doneLabel == atomicNodeLabel);
doneLabel = originalDoneLabel;
// Check to ensure we've found at least min iterations.
if (minIterations > 0)
{
Ldloc(iterationLocal);
Ldc(minIterations);
BltFar(doneLabel);
}
}
}
/// <summary>Generates the code for "RegexRunner.Go".</summary>
protected void GenerateGo()
{
Debug.Assert(_code != null);
_int32LocalsPool?.Clear();
_readOnlySpanCharLocalsPool?.Clear();
// Generate simpler code when we're dealing with simpler regexes.
if (TryGenerateSimplifiedGo(_code.Tree.Root))
{
return;
}
// We're dealing with a regex more complicated that the fast-path non-backtracking
// implementation can handle. Do the full-fledged thing.
// declare some locals
_runtextposLocal = DeclareInt32();
_runtextLocal = DeclareString();
_runtrackposLocal = DeclareInt32();
_runtrackLocal = DeclareInt32Array();
_runstackposLocal = DeclareInt32();
_runstackLocal = DeclareInt32Array();
if (_hasTimeout)
{
_loopTimeoutCounterLocal = DeclareInt32();
}
_runtextbegLocal = DeclareInt32();
_runtextendLocal = DeclareInt32();
InitializeCultureForGoIfNecessary();
// clear some tables
_labels = null;
_notes = null;
_notecount = 0;
// globally used labels
_backtrack = DefineLabel();
// emit the code!
GenerateForwardSection();
GenerateMiddleSection();
GenerateBacktrackSection();
}
private void InitializeCultureForGoIfNecessary()
{
_textInfoLocal = null;
if ((_options & RegexOptions.CultureInvariant) == 0)
{
bool needsCulture = (_options & RegexOptions.IgnoreCase) != 0;
if (!needsCulture)
{
for (int codepos = 0; codepos < _codes!.Length; codepos += RegexCode.OpcodeSize(_codes[codepos]))
{
if ((_codes[codepos] & RegexCode.Ci) == RegexCode.Ci)
{
needsCulture = true;
break;
}
}
}
if (needsCulture)
{
// cache CultureInfo in local variable which saves excessive thread local storage accesses
_textInfoLocal = DeclareTextInfo();
InitLocalCultureInfo();
}
}
}
/// <summary>
/// The main translation function. It translates the logic for a single opcode at
/// the current position. The structure of this function exactly mirrors
/// the structure of the inner loop of RegexInterpreter.Go().
/// </summary>
/// <remarks>
/// The C# code from RegexInterpreter.Go() that corresponds to each case is
/// included as a comment.
///
/// Note that since we're generating code, we can collapse many cases that are
/// dealt with one-at-a-time in RegexIntepreter. We can also unroll loops that
/// iterate over constant strings or sets.
/// </remarks>
private void GenerateOneCode()
{
#if DEBUG
if ((_options & RegexOptions.Debug) != 0)
DumpBacktracking();
#endif
// Before executing any RegEx code in the unrolled loop,
// we try checking for the match timeout:
if (_hasTimeout)
{
Ldthis();
Call(s_checkTimeoutMethod);
}
// Now generate the IL for the RegEx code saved in _regexopcode.
// We unroll the loop done by the RegexCompiler creating as very long method
// that is longer if the pattern is longer:
switch (_regexopcode)
{
case RegexCode.Stop:
//: return;
Mvlocfld(_runtextposLocal!, s_runtextposField); // update _textpos
Ret();
break;
case RegexCode.Nothing:
//: break Backward;
Back();
break;
case RegexCode.UpdateBumpalong:
// UpdateBumpalong should only exist in the code stream at such a point where the root
// of the backtracking stack contains the runtextpos from the start of this Go call. Replace
// that tracking value with the current runtextpos value.
//: base.runtrack[base.runtrack.Length - 1] = runtextpos;
Ldloc(_runtrackLocal!);
Dup();
Ldlen();
Ldc(1);
Sub();
Ldloc(_runtextposLocal!);
StelemI4();
break;
case RegexCode.Goto:
//: Goto(Operand(0));
Goto(Operand(0));
break;
case RegexCode.Testref:
//: if (!_match.IsMatched(Operand(0)))
//: break Backward;
Ldthis();
Ldc(Operand(0));
Call(s_isMatchedMethod);
BrfalseFar(_backtrack);
break;
case RegexCode.Lazybranch:
//: Track(Textpos());
PushTrack(_runtextposLocal!);
Track();
break;
case RegexCode.Lazybranch | RegexCode.Back:
//: Trackframe(1);
//: Textto(Tracked(0));
//: Goto(Operand(0));
PopTrack();
Stloc(_runtextposLocal!);
Goto(Operand(0));
break;
case RegexCode.Nullmark:
//: Stack(-1);
//: Track();
ReadyPushStack();
Ldc(-1);
DoPush();
TrackUnique(Stackpop);
break;
case RegexCode.Setmark:
//: Stack(Textpos());
//: Track();
PushStack(_runtextposLocal!);
TrackUnique(Stackpop);
break;
case RegexCode.Nullmark | RegexCode.Back:
case RegexCode.Setmark | RegexCode.Back:
//: Stackframe(1);
//: break Backward;
PopDiscardStack();
Back();
break;
case RegexCode.Getmark:
//: Stackframe(1);
//: Track(Stacked(0));
//: Textto(Stacked(0));
ReadyPushTrack();
PopStack();
Stloc(_runtextposLocal!);
Ldloc(_runtextposLocal!);
DoPush();
Track();
break;
case RegexCode.Getmark | RegexCode.Back:
//: Trackframe(1);
//: Stack(Tracked(0));
//: break Backward;
ReadyPushStack();
PopTrack();
DoPush();
Back();
break;
case RegexCode.Capturemark:
//: if (!IsMatched(Operand(1)))
//: break Backward;
//: Stackframe(1);
//: if (Operand(1) != -1)
//: TransferCapture(Operand(0), Operand(1), Stacked(0), Textpos());
//: else
//: Capture(Operand(0), Stacked(0), Textpos());
//: Track(Stacked(0));
//: Stackframe(1);
//: Capture(Operand(0), Stacked(0), Textpos());
//: Track(Stacked(0));
if (Operand(1) != -1)
{
Ldthis();
Ldc(Operand(1));
Call(s_isMatchedMethod);
BrfalseFar(_backtrack);
}
using (RentedLocalBuilder stackedLocal = RentInt32Local())
{
PopStack();
Stloc(stackedLocal);
if (Operand(1) != -1)
{
Ldthis();
Ldc(Operand(0));
Ldc(Operand(1));
Ldloc(stackedLocal);
Ldloc(_runtextposLocal!);
Call(s_transferCaptureMethod);
}
else
{
Ldthis();
Ldc(Operand(0));
Ldloc(stackedLocal);
Ldloc(_runtextposLocal!);
Call(s_captureMethod);
}
PushTrack(stackedLocal);
}
TrackUnique(Operand(0) != -1 && Operand(1) != -1 ? Capback2 : Capback);
break;
case RegexCode.Capturemark | RegexCode.Back:
//: Trackframe(1);
//: Stack(Tracked(0));
//: Uncapture();
//: if (Operand(0) != -1 && Operand(1) != -1)
//: Uncapture();
//: break Backward;
ReadyPushStack();
PopTrack();
DoPush();
Ldthis();
Call(s_uncaptureMethod);
if (Operand(0) != -1 && Operand(1) != -1)
{
Ldthis();
Call(s_uncaptureMethod);
}
Back();
break;
case RegexCode.Branchmark:
//: Stackframe(1);
//:
//: if (Textpos() != Stacked(0))
//: { // Nonempty match -> loop now
//: Track(Stacked(0), Textpos()); // Save old mark, textpos
//: Stack(Textpos()); // Make new mark
//: Goto(Operand(0)); // Loop
//: }
//: else
//: { // Empty match -> straight now
//: Track2(Stacked(0)); // Save old mark
//: Advance(1); // Straight
//: }
//: continue Forward;
{
Label l1 = DefineLabel();
PopStack();
using (RentedLocalBuilder mark = RentInt32Local())
{
Stloc(mark); // Stacked(0) -> temp
PushTrack(mark);
Ldloc(mark);
}
Ldloc(_runtextposLocal!);
Beq(l1); // mark == textpos -> branch
// (matched != 0)
PushTrack(_runtextposLocal!);
PushStack(_runtextposLocal!);
Track();
Goto(Operand(0)); // Goto(Operand(0))
// else
MarkLabel(l1);
TrackUnique2(Branchmarkback2);
break;
}
case RegexCode.Branchmark | RegexCode.Back:
//: Trackframe(2);
//: Stackframe(1);
//: Textto(Tracked(1)); // Recall position
//: Track2(Tracked(0)); // Save old mark
//: Advance(1);
PopTrack();
Stloc(_runtextposLocal!);
PopStack();
Pop();
// track spot 0 is already in place
TrackUnique2(Branchmarkback2);
Advance();
break;
case RegexCode.Branchmark | RegexCode.Back2:
//: Trackframe(1);
//: Stack(Tracked(0)); // Recall old mark
//: break Backward; // Backtrack
ReadyPushStack();
PopTrack();
DoPush();
Back();
break;
case RegexCode.Lazybranchmark:
//: StackPop();
//: int oldMarkPos = StackPeek();
//:
//: if (Textpos() != oldMarkPos) { // Nonempty match -> next loop
//: { // Nonempty match -> next loop
//: if (oldMarkPos != -1)
//: Track(Stacked(0), Textpos()); // Save old mark, textpos
//: else
//: TrackPush(Textpos(), Textpos());
//: }
//: else
//: { // Empty match -> no loop
//: Track2(Stacked(0)); // Save old mark
//: }
//: Advance(1);
//: continue Forward;
{
using (RentedLocalBuilder mark = RentInt32Local())
{
PopStack();
Stloc(mark); // Stacked(0) -> temp
// if (oldMarkPos != -1)
Label l2 = DefineLabel();
Label l3 = DefineLabel();
Ldloc(mark);
Ldc(-1);
Beq(l2); // mark == -1 -> branch
PushTrack(mark);
Br(l3);
// else
MarkLabel(l2);
PushTrack(_runtextposLocal!);
MarkLabel(l3);
// if (Textpos() != mark)
Label l1 = DefineLabel();
Ldloc(_runtextposLocal!);
Ldloc(mark);
Beq(l1); // mark == textpos -> branch
PushTrack(_runtextposLocal!);
Track();
Br(AdvanceLabel()); // Advance (near)
// else
MarkLabel(l1);
ReadyPushStack(); // push the current textPos on the stack.
// May be ignored by 'back2' or used by a true empty match.
Ldloc(mark);
}
DoPush();
TrackUnique2(Lazybranchmarkback2);
break;
}
case RegexCode.Lazybranchmark | RegexCode.Back:
//: Trackframe(2);
//: Track2(Tracked(0)); // Save old mark
//: Stack(Textpos()); // Make new mark
//: Textto(Tracked(1)); // Recall position
//: Goto(Operand(0)); // Loop
PopTrack();
Stloc(_runtextposLocal!);
PushStack(_runtextposLocal!);
TrackUnique2(Lazybranchmarkback2);
Goto(Operand(0));
break;
case RegexCode.Lazybranchmark | RegexCode.Back2:
//: Stackframe(1);
//: Trackframe(1);
//: Stack(Tracked(0)); // Recall old mark
//: break Backward;
ReadyReplaceStack(0);
PopTrack();
DoReplace();
Back();
break;
case RegexCode.Nullcount:
//: Stack(-1, Operand(0));
//: Track();
ReadyPushStack();
Ldc(-1);
DoPush();
ReadyPushStack();
Ldc(Operand(0));
DoPush();
TrackUnique(Stackpop2);
break;
case RegexCode.Setcount:
//: Stack(Textpos(), Operand(0));
//: Track();
PushStack(_runtextposLocal!);
ReadyPushStack();
Ldc(Operand(0));
DoPush();
TrackUnique(Stackpop2);
break;
case RegexCode.Nullcount | RegexCode.Back:
case RegexCode.Setcount | RegexCode.Back:
//: Stackframe(2);
//: break Backward;
PopDiscardStack(2);
Back();
break;
case RegexCode.Branchcount:
//: Stackframe(2);
//: int mark = Stacked(0);
//: int count = Stacked(1);
//:
//: if (count >= Operand(1) || Textpos() == mark && count >= 0)
//: { // Max loops or empty match -> straight now
//: Track2(mark, count); // Save old mark, count
//: Advance(2); // Straight
//: }
//: else
//: { // Nonempty match -> count+loop now
//: Track(mark); // remember mark
//: Stack(Textpos(), count + 1); // Make new mark, incr count
//: Goto(Operand(0)); // Loop
//: }
//: continue Forward;
{
using (RentedLocalBuilder count = RentInt32Local())
{
PopStack();
Stloc(count); // count -> temp
PopStack();
using (RentedLocalBuilder mark = RentInt32Local())
{
Stloc(mark); // mark -> temp2
PushTrack(mark);
Ldloc(mark);
}
Label l1 = DefineLabel();
Label l2 = DefineLabel();
Ldloc(_runtextposLocal!);
Bne(l1); // mark != textpos -> l1
Ldloc(count);
Ldc(0);
Bge(l2); // count >= 0 && mark == textpos -> l2
MarkLabel(l1);
Ldloc(count);
Ldc(Operand(1));
Bge(l2); // count >= Operand(1) -> l2
// else
PushStack(_runtextposLocal!);
ReadyPushStack();
Ldloc(count); // mark already on track
Ldc(1);
Add();
DoPush();
Track();
Goto(Operand(0));
// if (count >= Operand(1) || Textpos() == mark)
MarkLabel(l2);
PushTrack(count); // mark already on track
}
TrackUnique2(Branchcountback2);
break;
}
case RegexCode.Branchcount | RegexCode.Back:
//: Trackframe(1);
//: Stackframe(2);
//: if (Stacked(1) > 0) // Positive -> can go straight
//: {
//: Textto(Stacked(0)); // Zap to mark
//: Track2(Tracked(0), Stacked(1) - 1); // Save old mark, old count
//: Advance(2); // Straight
//: continue Forward;
//: }
//: Stack(Tracked(0), Stacked(1) - 1); // recall old mark, old count
//: break Backward;
{
using (RentedLocalBuilder count = RentInt32Local())
{
Label l1 = DefineLabel();
PopStack();
Ldc(1);
Sub();
Stloc(count);
Ldloc(count);
Ldc(0);
Blt(l1);
// if (count >= 0)
PopStack();
Stloc(_runtextposLocal!);
PushTrack(count); // Tracked(0) is already on the track
TrackUnique2(Branchcountback2);
Advance();
// else
MarkLabel(l1);
ReadyReplaceStack(0);
PopTrack();
DoReplace();
PushStack(count);
}
Back();
break;
}
case RegexCode.Branchcount | RegexCode.Back2:
//: Trackframe(2);
//: Stack(Tracked(0), Tracked(1)); // Recall old mark, old count
//: break Backward; // Backtrack
PopTrack();
using (RentedLocalBuilder tmp = RentInt32Local())
{
Stloc(tmp);
ReadyPushStack();
PopTrack();
DoPush();
PushStack(tmp);
}
Back();
break;
case RegexCode.Lazybranchcount:
//: Stackframe(2);
//: int mark = Stacked(0);
//: int count = Stacked(1);
//:
//: if (count < 0)
//: { // Negative count -> loop now
//: Track2(mark); // Save old mark
//: Stack(Textpos(), count + 1); // Make new mark, incr count
//: Goto(Operand(0)); // Loop
//: }
//: else
//: { // Nonneg count or empty match -> straight now
//: Track(mark, count, Textpos()); // Save mark, count, position
//: }
{
PopStack();
using (RentedLocalBuilder count = RentInt32Local())
{
Stloc(count); // count -> temp
PopStack();
using (RentedLocalBuilder mark = RentInt32Local())
{
Stloc(mark); // mark -> temp2
Label l1 = DefineLabel();
Ldloc(count);
Ldc(0);
Bge(l1); // count >= 0 -> l1
// if (count < 0)
PushTrack(mark);
PushStack(_runtextposLocal!);
ReadyPushStack();
Ldloc(count);
Ldc(1);
Add();
DoPush();
TrackUnique2(Lazybranchcountback2);
Goto(Operand(0));
// else
MarkLabel(l1);
PushTrack(mark);
}
PushTrack(count);
}
PushTrack(_runtextposLocal!);
Track();
break;
}
case RegexCode.Lazybranchcount | RegexCode.Back:
//: Trackframe(3);
//: int mark = Tracked(0);
//: int textpos = Tracked(2);
//: if (Tracked(1) < Operand(1) && textpos != mark)
//: { // Under limit and not empty match -> loop
//: Textto(Tracked(2)); // Recall position
//: Stack(Textpos(), Tracked(1) + 1); // Make new mark, incr count
//: Track2(Tracked(0)); // Save old mark
//: Goto(Operand(0)); // Loop
//: continue Forward;
//: }
//: else
//: {
//: Stack(Tracked(0), Tracked(1)); // Recall old mark, count
//: break Backward; // backtrack
//: }
{
using (RentedLocalBuilder cLocal = RentInt32Local())
{
Label l1 = DefineLabel();
PopTrack();
Stloc(_runtextposLocal!);
PopTrack();
Stloc(cLocal);
Ldloc(cLocal);
Ldc(Operand(1));
Bge(l1); // Tracked(1) >= Operand(1) -> l1
Ldloc(_runtextposLocal!);
TopTrack();
Beq(l1); // textpos == mark -> l1
PushStack(_runtextposLocal!);
ReadyPushStack();
Ldloc(cLocal);
Ldc(1);
Add();
DoPush();
TrackUnique2(Lazybranchcountback2);
Goto(Operand(0));
MarkLabel(l1);
ReadyPushStack();
PopTrack();
DoPush();
PushStack(cLocal);
}
Back();
break;
}
case RegexCode.Lazybranchcount | RegexCode.Back2:
// <
ReadyReplaceStack(1);
PopTrack();
DoReplace();
ReadyReplaceStack(0);
TopStack();
Ldc(1);
Sub();
DoReplace();
Back();
break;
case RegexCode.Setjump:
//: Stack(Trackpos(), Crawlpos());
//: Track();
ReadyPushStack();
Ldthisfld(s_runtrackField);
Ldlen();
Ldloc(_runtrackposLocal!);
Sub();
DoPush();
ReadyPushStack();
Ldthis();
Call(s_crawlposMethod);
DoPush();
TrackUnique(Stackpop2);
break;
case RegexCode.Setjump | RegexCode.Back:
//: Stackframe(2);
PopDiscardStack(2);
Back();
break;
case RegexCode.Backjump:
//: Stackframe(2);
//: Trackto(Stacked(0));
//: while (Crawlpos() != Stacked(1))
//: Uncapture();
//: break Backward;
{
Label l1 = DefineLabel();
Label l2 = DefineLabel();
using (RentedLocalBuilder stackedLocal = RentInt32Local())
{
PopStack();
Stloc(stackedLocal);
Ldthisfld(s_runtrackField);
Ldlen();
PopStack();
Sub();
Stloc(_runtrackposLocal!);
MarkLabel(l1);
Ldthis();
Call(s_crawlposMethod);
Ldloc(stackedLocal);
Beq(l2);
Ldthis();
Call(s_uncaptureMethod);
Br(l1);
}
MarkLabel(l2);
Back();
break;
}
case RegexCode.Forejump:
//: Stackframe(2);
//: Trackto(Stacked(0));
//: Track(Stacked(1));
PopStack();
using (RentedLocalBuilder tmp = RentInt32Local())
{
Stloc(tmp);
Ldthisfld(s_runtrackField);
Ldlen();
PopStack();
Sub();
Stloc(_runtrackposLocal!);
PushTrack(tmp);
}
TrackUnique(Forejumpback);
break;
case RegexCode.Forejump | RegexCode.Back:
//: Trackframe(1);
//: while (Crawlpos() != Tracked(0))
//: Uncapture();
//: break Backward;
{
Label l1 = DefineLabel();
Label l2 = DefineLabel();
using (RentedLocalBuilder trackedLocal = RentInt32Local())
{
PopTrack();
Stloc(trackedLocal);
MarkLabel(l1);
Ldthis();
Call(s_crawlposMethod);
Ldloc(trackedLocal);
Beq(l2);
Ldthis();
Call(s_uncaptureMethod);
Br(l1);
}
MarkLabel(l2);
Back();
break;
}
case RegexCode.Bol:
//: if (Leftchars() > 0 && CharAt(Textpos() - 1) != '\n')
//: break Backward;
{
Label l1 = _labels![NextCodepos()];
Ldloc(_runtextposLocal!);
Ldloc(_runtextbegLocal!);
Ble(l1);
Leftchar();
Ldc('\n');
BneFar(_backtrack);
break;
}
case RegexCode.Eol:
//: if (Rightchars() > 0 && CharAt(Textpos()) != '\n')
//: break Backward;
{
Label l1 = _labels![NextCodepos()];
Ldloc(_runtextposLocal!);
Ldloc(_runtextendLocal!);
Bge(l1);
Rightchar();
Ldc('\n');
BneFar(_backtrack);
break;
}
case RegexCode.Boundary:
case RegexCode.NonBoundary:
//: if (!IsBoundary(Textpos(), _textbeg, _textend))
//: break Backward;
Ldthis();
Ldloc(_runtextposLocal!);
Ldloc(_runtextbegLocal!);
Ldloc(_runtextendLocal!);
Call(s_isBoundaryMethod);
if (Code() == RegexCode.Boundary)
{
BrfalseFar(_backtrack);
}
else
{
BrtrueFar(_backtrack);
}
break;
case RegexCode.ECMABoundary:
case RegexCode.NonECMABoundary:
//: if (!IsECMABoundary(Textpos(), _textbeg, _textend))
//: break Backward;
Ldthis();
Ldloc(_runtextposLocal!);
Ldloc(_runtextbegLocal!);
Ldloc(_runtextendLocal!);
Call(s_isECMABoundaryMethod);
if (Code() == RegexCode.ECMABoundary)
{
BrfalseFar(_backtrack);
}
else
{
BrtrueFar(_backtrack);
}
break;
case RegexCode.Beginning:
//: if (Leftchars() > 0)
//: break Backward;
Ldloc(_runtextposLocal!);
Ldloc(_runtextbegLocal!);
BgtFar(_backtrack);
break;
case RegexCode.Start:
//: if (Textpos() != Textstart())
//: break Backward;
Ldloc(_runtextposLocal!);
Ldthisfld(s_runtextstartField);
BneFar(_backtrack);
break;
case RegexCode.EndZ:
//: if (Rightchars() > 1 || Rightchars() == 1 && CharAt(Textpos()) != '\n')
//: break Backward;
Ldloc(_runtextposLocal!);
Ldloc(_runtextendLocal!);
Ldc(1);
Sub();
BltFar(_backtrack);
Ldloc(_runtextposLocal!);
Ldloc(_runtextendLocal!);
Bge(_labels![NextCodepos()]);
Rightchar();
Ldc('\n');
BneFar(_backtrack);
break;
case RegexCode.End:
//: if (Rightchars() > 0)
//: break Backward;
Ldloc(_runtextposLocal!);
Ldloc(_runtextendLocal!);
BltFar(_backtrack);
break;
case RegexCode.One:
case RegexCode.Notone:
case RegexCode.Set:
case RegexCode.One | RegexCode.Rtl:
case RegexCode.Notone | RegexCode.Rtl:
case RegexCode.Set | RegexCode.Rtl:
case RegexCode.One | RegexCode.Ci:
case RegexCode.Notone | RegexCode.Ci:
case RegexCode.Set | RegexCode.Ci:
case RegexCode.One | RegexCode.Ci | RegexCode.Rtl:
case RegexCode.Notone | RegexCode.Ci | RegexCode.Rtl:
case RegexCode.Set | RegexCode.Ci | RegexCode.Rtl:
//: if (Rightchars() < 1 || Rightcharnext() != (char)Operand(0))
//: break Backward;
Ldloc(_runtextposLocal!);
if (!IsRightToLeft())
{
Ldloc(_runtextendLocal!);
BgeFar(_backtrack);
Rightcharnext();
}
else
{
Ldloc(_runtextbegLocal!);
BleFar(_backtrack);
Leftcharnext();
}
if (Code() == RegexCode.Set)
{
EmitMatchCharacterClass(_strings![Operand(0)], IsCaseInsensitive());
BrfalseFar(_backtrack);
}
else
{
if (IsCaseInsensitive())
{
CallToLower();
}
Ldc(Operand(0));
if (Code() == RegexCode.One)
{
BneFar(_backtrack);
}
else
{
BeqFar(_backtrack);
}
}
break;
case RegexCode.Multi:
case RegexCode.Multi | RegexCode.Ci:
//: String Str = _strings[Operand(0)];
//: int i, c;
//: if (Rightchars() < (c = Str.Length))
//: break Backward;
//: for (i = 0; c > 0; i++, c--)
//: if (Str[i] != Rightcharnext())
//: break Backward;
{
string str = _strings![Operand(0)];
Ldc(str.Length);
Ldloc(_runtextendLocal!);
Ldloc(_runtextposLocal!);
Sub();
BgtFar(_backtrack);
// unroll the string
for (int i = 0; i < str.Length; i++)
{
Ldloc(_runtextLocal!);
Ldloc(_runtextposLocal!);
if (i != 0)
{
Ldc(i);
Add();
}
Call(s_stringGetCharsMethod);
if (IsCaseInsensitive())
{
CallToLower();
}
Ldc(str[i]);
BneFar(_backtrack);
}
Ldloc(_runtextposLocal!);
Ldc(str.Length);
Add();
Stloc(_runtextposLocal!);
break;
}
case RegexCode.Multi | RegexCode.Rtl:
case RegexCode.Multi | RegexCode.Ci | RegexCode.Rtl:
//: String Str = _strings[Operand(0)];
//: int c;
//: if (Leftchars() < (c = Str.Length))
//: break Backward;
//: while (c > 0)
//: if (Str[--c] != Leftcharnext())
//: break Backward;
{
string str = _strings![Operand(0)];
Ldc(str.Length);
Ldloc(_runtextposLocal!);
Ldloc(_runtextbegLocal!);
Sub();
BgtFar(_backtrack);
// unroll the string
for (int i = str.Length; i > 0;)
{
i--;
Ldloc(_runtextLocal!);
Ldloc(_runtextposLocal!);
Ldc(str.Length - i);
Sub();
Call(s_stringGetCharsMethod);
if (IsCaseInsensitive())
{
CallToLower();
}
Ldc(str[i]);
BneFar(_backtrack);
}
Ldloc(_runtextposLocal!);
Ldc(str.Length);
Sub();
Stloc(_runtextposLocal!);
break;
}
case RegexCode.Ref:
case RegexCode.Ref | RegexCode.Rtl:
case RegexCode.Ref | RegexCode.Ci:
case RegexCode.Ref | RegexCode.Ci | RegexCode.Rtl:
//: int capnum = Operand(0);
//: int j, c;
//: if (!_match.IsMatched(capnum)) {
//: if (!RegexOptions.ECMAScript)
//: break Backward;
//: } else {
//: if (Rightchars() < (c = _match.MatchLength(capnum)))
//: break Backward;
//: for (j = _match.MatchIndex(capnum); c > 0; j++, c--)
//: if (CharAt(j) != Rightcharnext())
//: break Backward;
//: }
{
using RentedLocalBuilder lenLocal = RentInt32Local();
using RentedLocalBuilder indexLocal = RentInt32Local();
Label l1 = DefineLabel();
Ldthis();
Ldc(Operand(0));
Call(s_isMatchedMethod);
if ((_options & RegexOptions.ECMAScript) != 0)
{
Brfalse(AdvanceLabel());
}
else
{
BrfalseFar(_backtrack); // !IsMatched() -> back
}
Ldthis();
Ldc(Operand(0));
Call(s_matchLengthMethod);
Stloc(lenLocal);
Ldloc(lenLocal);
if (!IsRightToLeft())
{
Ldloc(_runtextendLocal!);
Ldloc(_runtextposLocal!);
}
else
{
Ldloc(_runtextposLocal!);
Ldloc(_runtextbegLocal!);
}
Sub();
BgtFar(_backtrack); // Matchlength() > Rightchars() -> back
Ldthis();
Ldc(Operand(0));
Call(s_matchIndexMethod);
if (!IsRightToLeft())
{
Ldloc(lenLocal);
Add(IsRightToLeft());
}
Stloc(indexLocal); // index += len
Ldloc(_runtextposLocal!);
Ldloc(lenLocal);
Add(IsRightToLeft());
Stloc(_runtextposLocal!); // texpos += len
MarkLabel(l1);
Ldloc(lenLocal);
Ldc(0);
Ble(AdvanceLabel());
Ldloc(_runtextLocal!);
Ldloc(indexLocal);
Ldloc(lenLocal);
if (IsRightToLeft())
{
Ldc(1);
Sub();
Stloc(lenLocal);
Ldloc(lenLocal);
}
Sub(IsRightToLeft());
Call(s_stringGetCharsMethod);
if (IsCaseInsensitive())
{
CallToLower();
}
Ldloc(_runtextLocal!);
Ldloc(_runtextposLocal!);
Ldloc(lenLocal);
if (!IsRightToLeft())
{
Ldloc(lenLocal);
Ldc(1);
Sub();
Stloc(lenLocal);
}
Sub(IsRightToLeft());
Call(s_stringGetCharsMethod);
if (IsCaseInsensitive())
{
CallToLower();
}
Beq(l1);
Back();
break;
}
case RegexCode.Onerep:
case RegexCode.Notonerep:
case RegexCode.Setrep:
case RegexCode.Onerep | RegexCode.Rtl:
case RegexCode.Notonerep | RegexCode.Rtl:
case RegexCode.Setrep | RegexCode.Rtl:
case RegexCode.Onerep | RegexCode.Ci:
case RegexCode.Notonerep | RegexCode.Ci:
case RegexCode.Setrep | RegexCode.Ci:
case RegexCode.Onerep | RegexCode.Ci | RegexCode.Rtl:
case RegexCode.Notonerep | RegexCode.Ci | RegexCode.Rtl:
case RegexCode.Setrep | RegexCode.Ci | RegexCode.Rtl:
//: int c = Operand(1);
//: if (Rightchars() < c)
//: break Backward;
//: char ch = (char)Operand(0);
//: while (c-- > 0)
//: if (Rightcharnext() != ch)
//: break Backward;
{
int c = Operand(1);
if (c == 0)
break;
Ldc(c);
if (!IsRightToLeft())
{
Ldloc(_runtextendLocal!);
Ldloc(_runtextposLocal!);
}
else
{
Ldloc(_runtextposLocal!);
Ldloc(_runtextbegLocal!);
}
Sub();
BgtFar(_backtrack); // Matchlength() > Rightchars() -> back
Ldloc(_runtextposLocal!);
Ldc(c);
Add(IsRightToLeft());
Stloc(_runtextposLocal!); // texpos += len
using RentedLocalBuilder lenLocal = RentInt32Local();
Label l1 = DefineLabel();
Ldc(c);
Stloc(lenLocal);
MarkLabel(l1);
Ldloc(_runtextLocal!);
Ldloc(_runtextposLocal!);
Ldloc(lenLocal);
if (IsRightToLeft())
{
Ldc(1);
Sub();
Stloc(lenLocal);
Ldloc(lenLocal);
Add();
}
else
{
Ldloc(lenLocal);
Ldc(1);
Sub();
Stloc(lenLocal);
Sub();
}
Call(s_stringGetCharsMethod);
if (Code() == RegexCode.Setrep)
{
EmitTimeoutCheck();
EmitMatchCharacterClass(_strings![Operand(0)], IsCaseInsensitive());
BrfalseFar(_backtrack);
}
else
{
if (IsCaseInsensitive())
{
CallToLower();
}
Ldc(Operand(0));
if (Code() == RegexCode.Onerep)
{
BneFar(_backtrack);
}
else
{
BeqFar(_backtrack);
}
}
Ldloc(lenLocal);
Ldc(0);
if (Code() == RegexCode.Setrep)
{
BgtFar(l1);
}
else
{
Bgt(l1);
}
break;
}
case RegexCode.Oneloop:
case RegexCode.Notoneloop:
case RegexCode.Setloop:
case RegexCode.Oneloop | RegexCode.Rtl:
case RegexCode.Notoneloop | RegexCode.Rtl:
case RegexCode.Setloop | RegexCode.Rtl:
case RegexCode.Oneloop | RegexCode.Ci:
case RegexCode.Notoneloop | RegexCode.Ci:
case RegexCode.Setloop | RegexCode.Ci:
case RegexCode.Oneloop | RegexCode.Ci | RegexCode.Rtl:
case RegexCode.Notoneloop | RegexCode.Ci | RegexCode.Rtl:
case RegexCode.Setloop | RegexCode.Ci | RegexCode.Rtl:
case RegexCode.Oneloopatomic:
case RegexCode.Notoneloopatomic:
case RegexCode.Setloopatomic:
case RegexCode.Oneloopatomic | RegexCode.Rtl:
case RegexCode.Notoneloopatomic | RegexCode.Rtl:
case RegexCode.Setloopatomic | RegexCode.Rtl:
case RegexCode.Oneloopatomic | RegexCode.Ci:
case RegexCode.Notoneloopatomic | RegexCode.Ci:
case RegexCode.Setloopatomic | RegexCode.Ci:
case RegexCode.Oneloopatomic | RegexCode.Ci | RegexCode.Rtl:
case RegexCode.Notoneloopatomic | RegexCode.Ci | RegexCode.Rtl:
case RegexCode.Setloopatomic | RegexCode.Ci | RegexCode.Rtl:
//: int len = Operand(1);
//: if (len > Rightchars())
//: len = Rightchars();
//: char ch = (char)Operand(0);
//: int i;
//: for (i = len; i > 0; i--)
//: {
//: if (Rightcharnext() != ch)
//: {
//: Leftnext();
//: break;
//: }
//: }
//: if (len > i)
//: Track(len - i - 1, Textpos() - 1);
{
int c = Operand(1);
if (c == 0)
{
break;
}
using RentedLocalBuilder lenLocal = RentInt32Local();
using RentedLocalBuilder iLocal = RentInt32Local();
if (!IsRightToLeft())
{
Ldloc(_runtextendLocal!);
Ldloc(_runtextposLocal!);
}
else
{
Ldloc(_runtextposLocal!);
Ldloc(_runtextbegLocal!);
}
Sub();
Stloc(lenLocal);
if (c != int.MaxValue)
{
Label l4 = DefineLabel();
Ldloc(lenLocal);
Ldc(c);
Blt(l4);
Ldc(c);
Stloc(lenLocal);
MarkLabel(l4);
}
Label loopEnd = DefineLabel();
string? set = Code() == RegexCode.Setloop || Code() == RegexCode.Setloopatomic ? _strings![Operand(0)] : null;
Span<char> setChars = stackalloc char[5]; // max optimized by IndexOfAny today
int numSetChars;
// If this is a notoneloop{atomic} and we're left-to-right and case-sensitive,
// we can use the vectorized IndexOf to search for the target character.
if ((Code() == RegexCode.Notoneloop || Code() == RegexCode.Notoneloopatomic) &&
!IsRightToLeft() &&
(!IsCaseInsensitive()))
{
// i = runtext.AsSpan(runtextpos, len).IndexOf(ch);
Ldloc(_runtextLocal!);
Ldloc(_runtextposLocal!);
Ldloc(lenLocal);
Call(s_stringAsSpanIntIntMethod);
Ldc(Operand(0));
Call(s_spanIndexOfChar);
Stloc(iLocal);
Label charFound = DefineLabel();
// if (i != -1) goto charFound;
Ldloc(iLocal);
Ldc(-1);
Bne(charFound);
// runtextpos += len;
// i = 0;
// goto loopEnd;
Ldloc(_runtextposLocal!);
Ldloc(lenLocal);
Add();
Stloc(_runtextposLocal!);
Ldc(0);
Stloc(iLocal);
BrFar(loopEnd);
// charFound:
// runtextpos += i;
// i = len - i;
// goto loopEnd;
MarkLabel(charFound);
Ldloc(_runtextposLocal!);
Ldloc(iLocal);
Add();
Stloc(_runtextposLocal!);
Ldloc(lenLocal);
Ldloc(iLocal);
Sub();
Stloc(iLocal);
BrFar(loopEnd);
}
else if ((Code() == RegexCode.Setloop || Code() == RegexCode.Setloopatomic) &&
!IsRightToLeft() &&
!IsCaseInsensitive() &&
(numSetChars = RegexCharClass.GetSetChars(set!, setChars)) != 0 &&
RegexCharClass.IsNegated(set!))
{
// Similarly, if this is a setloop{atomic} and we're left-to-right and case-sensitive,
// and if the set contains only a few negated chars, we can use the vectorized IndexOfAny
// to search for those chars.
Debug.Assert(numSetChars > 1);
// i = runtext.AsSpan(runtextpos, len).IndexOfAny(ch1, ch2{, ch3});
Ldloc(_runtextLocal!);
Ldloc(_runtextposLocal!);
Ldloc(lenLocal);
Call(s_stringAsSpanIntIntMethod);
switch (numSetChars)
{
case 2:
Ldc(setChars[0]);
Ldc(setChars[1]);
Call(s_spanIndexOfAnyCharChar);
break;
case 3:
Ldc(setChars[0]);
Ldc(setChars[1]);
Ldc(setChars[2]);
Call(s_spanIndexOfAnyCharCharChar);
break;
default:
Ldstr(setChars.Slice(0, numSetChars).ToString());
Call(s_stringAsSpanMethod);
Call(s_spanIndexOfSpan);
break;
}
Stloc(iLocal);
Label charFound = DefineLabel();
// if (i != -1) goto charFound;
Ldloc(iLocal);
Ldc(-1);
Bne(charFound);
// runtextpos += len;
// i = 0;
// goto loopEnd;
Ldloc(_runtextposLocal!);
Ldloc(lenLocal);
Add();
Stloc(_runtextposLocal!);
Ldc(0);
Stloc(iLocal);
BrFar(loopEnd);
// charFound:
// runtextpos += i;
// i = len - i;
// goto loopEnd;
MarkLabel(charFound);
Ldloc(_runtextposLocal!);
Ldloc(iLocal);
Add();
Stloc(_runtextposLocal!);
Ldloc(lenLocal);
Ldloc(iLocal);
Sub();
Stloc(iLocal);
BrFar(loopEnd);
}
else if ((Code() == RegexCode.Setloop || Code() == RegexCode.Setloopatomic) &&
!IsRightToLeft() &&
set == RegexCharClass.AnyClass)
{
// If someone uses .* along with RegexOptions.Singleline, that becomes [anycharacter]*, which means it'll
// consume everything. As such, we can simply update our position to be the last allowed, without
// actually checking anything.
// runtextpos += len;
// i = 0;
// goto loopEnd;
Ldloc(_runtextposLocal!);
Ldloc(lenLocal);
Add();
Stloc(_runtextposLocal!);
Ldc(0);
Stloc(iLocal);
BrFar(loopEnd);
}
else
{
// Otherwise, we emit the open-coded loop.
Ldloc(lenLocal);
Ldc(1);
Add();
Stloc(iLocal);
Label loopCondition = DefineLabel();
MarkLabel(loopCondition);
Ldloc(iLocal);
Ldc(1);
Sub();
Stloc(iLocal);
Ldloc(iLocal);
Ldc(0);
if (Code() == RegexCode.Setloop || Code() == RegexCode.Setloopatomic)
{
BleFar(loopEnd);
}
else
{
Ble(loopEnd);
}
if (IsRightToLeft())
{
Leftcharnext();
}
else
{
Rightcharnext();
}
if (Code() == RegexCode.Setloop || Code() == RegexCode.Setloopatomic)
{
EmitTimeoutCheck();
EmitMatchCharacterClass(_strings![Operand(0)], IsCaseInsensitive());
BrtrueFar(loopCondition);
}
else
{
if (IsCaseInsensitive())
{
CallToLower();
}
Ldc(Operand(0));
if (Code() == RegexCode.Oneloop || Code() == RegexCode.Oneloopatomic)
{
Beq(loopCondition);
}
else
{
Debug.Assert(Code() == RegexCode.Notoneloop || Code() == RegexCode.Notoneloopatomic);
Bne(loopCondition);
}
}
Ldloc(_runtextposLocal!);
Ldc(1);
Sub(IsRightToLeft());
Stloc(_runtextposLocal!);
}
// loopEnd:
MarkLabel(loopEnd);
if (Code() != RegexCode.Oneloopatomic && Code() != RegexCode.Notoneloopatomic && Code() != RegexCode.Setloopatomic)
{
// if (len <= i) goto advance;
Ldloc(lenLocal);
Ldloc(iLocal);
Ble(AdvanceLabel());
// TrackPush(len - i - 1, runtextpos - Bump())
ReadyPushTrack();
Ldloc(lenLocal);
Ldloc(iLocal);
Sub();
Ldc(1);
Sub();
DoPush();
ReadyPushTrack();
Ldloc(_runtextposLocal!);
Ldc(1);
Sub(IsRightToLeft());
DoPush();
Track();
}
break;
}
case RegexCode.Oneloop | RegexCode.Back:
case RegexCode.Notoneloop | RegexCode.Back:
case RegexCode.Setloop | RegexCode.Back:
case RegexCode.Oneloop | RegexCode.Rtl | RegexCode.Back:
case RegexCode.Notoneloop | RegexCode.Rtl | RegexCode.Back:
case RegexCode.Setloop | RegexCode.Rtl | RegexCode.Back:
case RegexCode.Oneloop | RegexCode.Ci | RegexCode.Back:
case RegexCode.Notoneloop | RegexCode.Ci | RegexCode.Back:
case RegexCode.Setloop | RegexCode.Ci | RegexCode.Back:
case RegexCode.Oneloop | RegexCode.Ci | RegexCode.Rtl | RegexCode.Back:
case RegexCode.Notoneloop | RegexCode.Ci | RegexCode.Rtl | RegexCode.Back:
case RegexCode.Setloop | RegexCode.Ci | RegexCode.Rtl | RegexCode.Back:
//: Trackframe(2);
//: int i = Tracked(0);
//: int pos = Tracked(1);
//: Textto(pos);
//: if (i > 0)
//: Track(i - 1, pos - 1);
//: Advance(2);
PopTrack();
Stloc(_runtextposLocal!);
PopTrack();
using (RentedLocalBuilder posLocal = RentInt32Local())
{
Stloc(posLocal);
Ldloc(posLocal);
Ldc(0);
BleFar(AdvanceLabel());
ReadyPushTrack();
Ldloc(posLocal);
}
Ldc(1);
Sub();
DoPush();
ReadyPushTrack();
Ldloc(_runtextposLocal!);
Ldc(1);
Sub(IsRightToLeft());
DoPush();
Trackagain();
Advance();
break;
case RegexCode.Onelazy:
case RegexCode.Notonelazy:
case RegexCode.Setlazy:
case RegexCode.Onelazy | RegexCode.Rtl:
case RegexCode.Notonelazy | RegexCode.Rtl:
case RegexCode.Setlazy | RegexCode.Rtl:
case RegexCode.Onelazy | RegexCode.Ci:
case RegexCode.Notonelazy | RegexCode.Ci:
case RegexCode.Setlazy | RegexCode.Ci:
case RegexCode.Onelazy | RegexCode.Ci | RegexCode.Rtl:
case RegexCode.Notonelazy | RegexCode.Ci | RegexCode.Rtl:
case RegexCode.Setlazy | RegexCode.Ci | RegexCode.Rtl:
//: int c = Operand(1);
//: if (c > Rightchars())
//: c = Rightchars();
//: if (c > 0)
//: Track(c - 1, Textpos());
{
int c = Operand(1);
if (c == 0)
{
break;
}
if (!IsRightToLeft())
{
Ldloc(_runtextendLocal!);
Ldloc(_runtextposLocal!);
}
else
{
Ldloc(_runtextposLocal!);
Ldloc(_runtextbegLocal!);
}
Sub();
using (RentedLocalBuilder cLocal = RentInt32Local())
{
Stloc(cLocal);
if (c != int.MaxValue)
{
Label l4 = DefineLabel();
Ldloc(cLocal);
Ldc(c);
Blt(l4);
Ldc(c);
Stloc(cLocal);
MarkLabel(l4);
}
Ldloc(cLocal);
Ldc(0);
Ble(AdvanceLabel());
ReadyPushTrack();
Ldloc(cLocal);
}
Ldc(1);
Sub();
DoPush();
PushTrack(_runtextposLocal!);
Track();
break;
}
case RegexCode.Onelazy | RegexCode.Back:
case RegexCode.Notonelazy | RegexCode.Back:
case RegexCode.Setlazy | RegexCode.Back:
case RegexCode.Onelazy | RegexCode.Rtl | RegexCode.Back:
case RegexCode.Notonelazy | RegexCode.Rtl | RegexCode.Back:
case RegexCode.Setlazy | RegexCode.Rtl | RegexCode.Back:
case RegexCode.Onelazy | RegexCode.Ci | RegexCode.Back:
case RegexCode.Notonelazy | RegexCode.Ci | RegexCode.Back:
case RegexCode.Setlazy | RegexCode.Ci | RegexCode.Back:
case RegexCode.Onelazy | RegexCode.Ci | RegexCode.Rtl | RegexCode.Back:
case RegexCode.Notonelazy | RegexCode.Ci | RegexCode.Rtl | RegexCode.Back:
case RegexCode.Setlazy | RegexCode.Ci | RegexCode.Rtl | RegexCode.Back:
//: Trackframe(2);
//: int pos = Tracked(1);
//: Textto(pos);
//: if (Rightcharnext() != (char)Operand(0))
//: break Backward;
//: int i = Tracked(0);
//: if (i > 0)
//: Track(i - 1, pos + 1);
PopTrack();
Stloc(_runtextposLocal!);
PopTrack();
using (RentedLocalBuilder iLocal = RentInt32Local())
{
Stloc(iLocal);
if (!IsRightToLeft())
{
Rightcharnext();
}
else
{
Leftcharnext();
}
if (Code() == RegexCode.Setlazy)
{
EmitMatchCharacterClass(_strings![Operand(0)], IsCaseInsensitive());
BrfalseFar(_backtrack);
}
else
{
if (IsCaseInsensitive())
{
CallToLower();
}
Ldc(Operand(0));
if (Code() == RegexCode.Onelazy)
{
BneFar(_backtrack);
}
else
{
BeqFar(_backtrack);
}
}
Ldloc(iLocal);
Ldc(0);
BleFar(AdvanceLabel());
ReadyPushTrack();
Ldloc(iLocal);
}
Ldc(1);
Sub();
DoPush();
PushTrack(_runtextposLocal!);
Trackagain();
Advance();
break;
default:
Debug.Fail($"Unimplemented state: {_regexopcode:X8}");
break;
}
}
/// <summary>Emits a a check for whether the character is in the specified character class.</summary>
/// <remarks>The character to be checked has already been loaded onto the stack.</remarks>
private void EmitMatchCharacterClass(string charClass, bool caseInsensitive)
{
// We need to perform the equivalent of calling RegexRunner.CharInClass(ch, charClass),
// but that call is relatively expensive. Before we fall back to it, we try to optimize
// some common cases for which we can do much better, such as known character classes
// for which we can call a dedicated method, or a fast-path for ASCII using a lookup table.
// First, see if the char class is a built-in one for which there's a better function
// we can just call directly. Everything in this section must work correctly for both
// case-sensitive and case-insensitive modes, regardless of culture.
switch (charClass)
{
case RegexCharClass.AnyClass:
// true
Pop();
Ldc(1);
return;
case RegexCharClass.DigitClass:
// char.IsDigit(ch)
Call(s_charIsDigitMethod);
return;
case RegexCharClass.NotDigitClass:
// !char.IsDigit(ch)
Call(s_charIsDigitMethod);
Ldc(0);
Ceq();
return;
case RegexCharClass.SpaceClass:
// char.IsWhiteSpace(ch)
Call(s_charIsWhiteSpaceMethod);
return;
case RegexCharClass.NotSpaceClass:
// !char.IsWhiteSpace(ch)
Call(s_charIsWhiteSpaceMethod);
Ldc(0);
Ceq();
return;
}
// If we're meant to be doing a case-insensitive lookup, and if we're not using the invariant culture,
// lowercase the input. If we're using the invariant culture, we may still end up calling ToLower later
// on, but we may also be able to avoid it, in particular in the case of our lookup table, where we can
// generate the lookup table already factoring in the invariant case sensitivity. There are multiple
// special-code paths between here and the lookup table, but we only take those if invariant is false;
// if it were true, they'd need to use CallToLower().
bool invariant = false;
if (caseInsensitive)
{
invariant = UseToLowerInvariant;
if (!invariant)
{
CallToLower();
}
}
// Next, handle simple sets of one range, e.g. [A-Z], [0-9], etc. This includes some built-in classes, like ECMADigitClass.
if (!invariant && RegexCharClass.TryGetSingleRange(charClass, out char lowInclusive, out char highInclusive))
{
if (lowInclusive == highInclusive)
{
// ch == charClass[3]
Ldc(lowInclusive);
Ceq();
}
else
{
// (uint)ch - lowInclusive < highInclusive - lowInclusive + 1
Ldc(lowInclusive);
Sub();
Ldc(highInclusive - lowInclusive + 1);
CltUn();
}
// Negate the answer if the negation flag was set
if (RegexCharClass.IsNegated(charClass))
{
Ldc(0);
Ceq();
}
return;
}
// Next if the character class contains nothing but a single Unicode category, we can calle char.GetUnicodeCategory and
// compare against it. It has a fast-lookup path for ASCII, so is as good or better than any lookup we'd generate (plus
// we get smaller code), and it's what we'd do for the fallback (which we get to avoid generating) as part of CharInClass.
if (!invariant && RegexCharClass.TryGetSingleUnicodeCategory(charClass, out UnicodeCategory category, out bool negated))
{
// char.GetUnicodeCategory(ch) == category
Call(s_charGetUnicodeInfo);
Ldc((int)category);
Ceq();
if (negated)
{
Ldc(0);
Ceq();
}
return;
}
// All checks after this point require reading the input character multiple times,
// so we store it into a temporary local.
using RentedLocalBuilder tempLocal = RentInt32Local();
Stloc(tempLocal);
// Next, if there's only 2 or 3 chars in the set (fairly common due to the sets we create for prefixes),
// it's cheaper and smaller to compare against each than it is to use a lookup table.
if (!invariant && !RegexCharClass.IsNegated(charClass))
{
Span<char> setChars = stackalloc char[4];
int numChars = RegexCharClass.GetSetChars(charClass, setChars);
if (numChars is 2 or 3)
{
if ((setChars[0] | 0x20) == setChars[1]) // special-case common case of an upper and lowercase ASCII letter combination
{
// ((ch | 0x20) == setChars[1])
Ldloc(tempLocal);
Ldc(0x20);
Or();
Ldc(setChars[1]);
Ceq();
}
else
{
// (ch == setChars[0]) | (ch == setChars[1])
Ldloc(tempLocal);
Ldc(setChars[0]);
Ceq();
Ldloc(tempLocal);
Ldc(setChars[1]);
Ceq();
Or();
}
// | (ch == setChars[2])
if (numChars == 3)
{
Ldloc(tempLocal);
Ldc(setChars[2]);
Ceq();
Or();
}
return;
}
else if (numChars == 4 &&
(setChars[0] | 0x20) == setChars[1] &&
(setChars[2] | 0x20) == setChars[3])
{
// ((ch | 0x20) == setChars[1])
Ldloc(tempLocal);
Ldc(0x20);
Or();
Ldc(setChars[1]);
Ceq();
// ((ch | 0x20) == setChars[3])
Ldloc(tempLocal);
Ldc(0x20);
Or();
Ldc(setChars[3]);
Ceq();
Or();
return;
}
}
using RentedLocalBuilder resultLocal = RentInt32Local();
// Analyze the character set more to determine what code to generate.
RegexCharClass.CharClassAnalysisResults analysis = RegexCharClass.Analyze(charClass);
// Helper method that emits a call to RegexRunner.CharInClass(ch{.ToLowerInvariant()}, charClass)
void EmitCharInClass()
{
Ldloc(tempLocal);
if (invariant)
{
CallToLower();
}
Ldstr(charClass);
Call(s_charInClassMethod);
Stloc(resultLocal);
}
Label doneLabel = DefineLabel();
Label comparisonLabel = DefineLabel();
if (!invariant) // if we're being asked to do a case insensitive, invariant comparison, use the lookup table
{
if (analysis.ContainsNoAscii)
{
// We determined that the character class contains only non-ASCII,
// for example if the class were [\p{IsGreek}\p{IsGreekExtended}], which is
// the same as [\u0370-\u03FF\u1F00-1FFF]. (In the future, we could possibly
// extend the analysis to produce a known lower-bound and compare against
// that rather than always using 128 as the pivot point.)
// ch >= 128 && RegexRunner.CharInClass(ch, "...")
Ldloc(tempLocal);
Ldc(128);
Blt(comparisonLabel);
EmitCharInClass();
Br(doneLabel);
MarkLabel(comparisonLabel);
Ldc(0);
Stloc(resultLocal);
MarkLabel(doneLabel);
Ldloc(resultLocal);
return;
}
if (analysis.AllAsciiContained)
{
// We determined that every ASCII character is in the class, for example
// if the class were the negated example from case 1 above:
// [^\p{IsGreek}\p{IsGreekExtended}].
// ch < 128 || RegexRunner.CharInClass(ch, "...")
Ldloc(tempLocal);
Ldc(128);
Blt(comparisonLabel);
EmitCharInClass();
Br(doneLabel);
MarkLabel(comparisonLabel);
Ldc(1);
Stloc(resultLocal);
MarkLabel(doneLabel);
Ldloc(resultLocal);
return;
}
}
// Now, our big hammer is to generate a lookup table that lets us quickly index by character into a yes/no
// answer as to whether the character is in the target character class. However, we don't want to store
// a lookup table for every possible character for every character class in the regular expression; at one
// bit for each of 65K characters, that would be an 8K bitmap per character class. Instead, we handle the
// common case of ASCII input via such a lookup table, which at one bit for each of 128 characters is only
// 16 bytes per character class. We of course still need to be able to handle inputs that aren't ASCII, so
// we check the input against 128, and have a fallback if the input is >= to it. Determining the right
// fallback could itself be expensive. For example, if it's possible that a value >= 128 could match the
// character class, we output a call to RegexRunner.CharInClass, but we don't want to have to enumerate the
// entire character class evaluating every character against it, just to determine whether it's a match.
// Instead, we employ some quick heuristics that will always ensure we provide a correct answer even if
// we could have sometimes generated better code to give that answer.
// Generate the lookup table to store 128 answers as bits. We use a const string instead of a byte[] / static
// data property because it lets IL emit handle all the details for us.
string bitVectorString = string.Create(8, (charClass, invariant), static (dest, state) => // String length is 8 chars == 16 bytes == 128 bits.
{
for (int i = 0; i < 128; i++)
{
char c = (char)i;
bool isSet = state.invariant ?
RegexCharClass.CharInClass(char.ToLowerInvariant(c), state.charClass) :
RegexCharClass.CharInClass(c, state.charClass);
if (isSet)
{
dest[i >> 4] |= (char)(1 << (i & 0xF));
}
}
});
// We determined that the character class may contain ASCII, so we
// output the lookup against the lookup table.
// ch < 128 ? (bitVectorString[ch >> 4] & (1 << (ch & 0xF))) != 0 :
Ldloc(tempLocal);
Ldc(128);
Bge(comparisonLabel);
Ldstr(bitVectorString);
Ldloc(tempLocal);
Ldc(4);
Shr();
Call(s_stringGetCharsMethod);
Ldc(1);
Ldloc(tempLocal);
Ldc(15);
And();
Ldc(31);
And();
Shl();
And();
Ldc(0);
CgtUn();
Stloc(resultLocal);
Br(doneLabel);
MarkLabel(comparisonLabel);
if (analysis.ContainsOnlyAscii)
{
// We know that all inputs that could match are ASCII, for example if the
// character class were [A-Za-z0-9], so since the ch is now known to be >= 128, we
// can just fail the comparison.
Ldc(0);
Stloc(resultLocal);
}
else if (analysis.AllNonAsciiContained)
{
// We know that all non-ASCII inputs match, for example if the character
// class were [^\r\n], so since we just determined the ch to be >= 128, we can just
// give back success.
Ldc(1);
Stloc(resultLocal);
}
else
{
// We know that the whole class wasn't ASCII, and we don't know anything about the non-ASCII
// characters other than that some might be included, for example if the character class
// were [\w\d], so since ch >= 128, we need to fall back to calling CharInClass.
EmitCharInClass();
}
MarkLabel(doneLabel);
Ldloc(resultLocal);
}
/// <summary>Emits a timeout check.</summary>
private void EmitTimeoutCheck()
{
if (!_hasTimeout)
{
return;
}
Debug.Assert(_loopTimeoutCounterLocal != null);
// Increment counter for each loop iteration.
Ldloc(_loopTimeoutCounterLocal);
Ldc(1);
Add();
Stloc(_loopTimeoutCounterLocal);
// Emit code to check the timeout every 2048th iteration.
Label label = DefineLabel();
Ldloc(_loopTimeoutCounterLocal);
Ldc(LoopTimeoutCheckCount);
RemUn();
Brtrue(label);
Ldthis();
Call(s_checkTimeoutMethod);
MarkLabel(label);
}
#if DEBUG
/// <summary>Emit code to print out the current state of the runner.</summary>
[ExcludeFromCodeCoverage(Justification = "Debug only")]
private void DumpBacktracking()
{
Mvlocfld(_runtextposLocal!, s_runtextposField);
Mvlocfld(_runtrackposLocal!, s_runtrackposField);
Mvlocfld(_runstackposLocal!, s_runstackposField);
Ldthis();
Call(s_dumpStateM);
var sb = new StringBuilder();
if (_backpos > 0)
{
sb.Append($"{_backpos:D6} ");
}
else
{
sb.Append(" ");
}
sb.Append(_code!.OpcodeDescription(_codepos));
if ((_regexopcode & RegexCode.Back) != 0)
{
sb.Append(" Back");
}
if ((_regexopcode & RegexCode.Back2) != 0)
{
sb.Append(" Back2");
}
Ldstr(sb.ToString());
Call(s_debugWriteLine!);
}
#endif
}
}
| 42.394522 | 355 | 0.444151 | [
"MIT"
] | kasperk81/runtime | src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs | 222,868 | C# |
// Copyright (c) 2020, Phoenix Contact GmbH & Co. KG
// Licensed under the Apache License, Version 2.0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Moryx.AbstractionLayer.Capabilities;
using Moryx.AbstractionLayer.Resources;
using Moryx.Container;
using Moryx.Logging;
using Moryx.Model;
using Moryx.Model.Repositories;
using Moryx.Modules;
using Moryx.Resources.Model;
using Moryx.Tools;
namespace Moryx.Resources.Management
{
[Plugin(LifeCycle.Singleton, typeof(IResourceManager))]
internal class ResourceManager : IResourceManager
{
#region Dependency Injection
/// <summary>
/// Reference to the resource graph
/// </summary>
public IManagedResourceGraph Graph { get; set; }
/// <summary>
/// Type controller managing the type tree and proxy creation
/// </summary>
public IResourceTypeController TypeController { get; set; }
/// <summary>
/// Component responsible for linking of the object graph
/// </summary>
public IResourceLinker ResourceLinker { get; set; }
/// <summary>
/// Access to the database
/// </summary>
public IUnitOfWorkFactory<ResourcesContext> UowFactory { get; set; }
/// <summary>
/// Logger for the ResourceManager
/// </summary>
[UseChild(nameof(ResourceManager))]
public IModuleLogger Logger { get; set; }
#endregion
#region Fields
/// <summary>
/// Enum of the different startup phases of the resources
/// </summary>
private enum ResourceStartupPhase
{
/// <summary>
/// Loading the existing resources or creating a root resource
/// </summary>
LoadResources,
/// <summary>
/// Calling Initialize() foreach loaded resource
/// </summary>
Initializing,
/// <summary>
/// Every loaded resource is initialized
/// </summary>
Initialized,
/// <summary>
/// Calling Start() foreach loaded resource
/// </summary>
Starting,
/// <summary>
/// Every loaded resource is started.
/// </summary>
Started,
/// <summary>
/// Calling Stop() foreach resource
/// </summary>
Stopping,
/// <summary>
/// All resources are stopped
/// </summary>
Stopped
}
/// <summary>
/// Current phase of the Resource-Startup-Phase
/// </summary>
private ResourceStartupPhase _startup;
/// <summary>
/// Fallback lock object if a new instance is saved BEFORE having the wrapper as a lock object
/// </summary>
private readonly object _fallbackLock = new object();
#endregion
#region LifeCycle
public void Initialize()
{
// Set delegates on graph
Graph.SaveDelegate = Save;
Graph.DestroyDelegate = Destroy;
_startup = ResourceStartupPhase.LoadResources;
using (var uow = UowFactory.Create(ContextMode.AllOff))
{
// Create all objects
var allResources = ResourceEntityAccessor.FetchResourceTemplates(uow);
if (allResources.Count > 0)
{
LoadResources(allResources);
}
else
{
Logger.Log(LogLevel.Warning, "The ResourceManager initialized without a resource." +
"Execute a resource initializer to add resources with \"exec ResourceManager initialize\"");
}
}
_startup = ResourceStartupPhase.Initializing;
// Boot resources
Parallel.ForEach(Graph.GetAll(), resourceWrapper =>
{
try
{
resourceWrapper.Initialize();
}
catch (Exception e)
{
resourceWrapper.ErrorOccured();
Logger.LogException(LogLevel.Warning, e, "Failed to initialize resource {0}-{1}", resourceWrapper.Target.Id, resourceWrapper.Target.Name);
}
});
_startup = ResourceStartupPhase.Initialized;
}
/// <summary>
/// Load and link all resources from the database
/// </summary>
private void LoadResources(ICollection<ResourceEntityAccessor> allResources)
{
// Create resource objects on multiple threads
var query = from template in allResources.AsParallel()
select template.Instantiate(TypeController, Graph);
foreach (var resource in query)
AddResource(resource, false);
// Link them to each other
Parallel.ForEach(allResources, LinkReferences);
// Register events after all links were set
foreach (var resourceWrapper in Graph.GetAll())
RegisterEvents(resourceWrapper.Target);
}
/// <summary>
/// Add resource to all collections and register to the <see cref="Resource.Changed"/> event
/// </summary>
private void AddResource(Resource instance, bool registerEvents)
{
// Add instance to the graph
var wrapped = Graph.Add(instance);
// Register to events
if (registerEvents)
RegisterEvents(instance);
switch (_startup)
{
case ResourceStartupPhase.LoadResources:
// do nothing
break;
case ResourceStartupPhase.Initializing:
case ResourceStartupPhase.Initialized:
// Resources those are created during the initialize of a resource are automatically initialized also.
wrapped.Initialize();
break;
case ResourceStartupPhase.Starting:
case ResourceStartupPhase.Started:
// Resources those are created during the start of a resource are automatically initialized and started also.
wrapped.Initialize();
wrapped.Start();
break;
case ResourceStartupPhase.Stopping:
case ResourceStartupPhase.Stopped:
// do nothing
break;
default:
throw new ArgumentOutOfRangeException();
}
// Inform listeners about the new resource
if (instance is IPublicResource publicResource)
RaiseResourceAdded(publicResource);
}
/// <summary>
/// Register a resources events
/// </summary>
private void RegisterEvents(Resource instance)
{
instance.Changed += OnResourceChanged;
if (instance is IPublicResource asPublic)
asPublic.CapabilitiesChanged += RaiseCapabilitiesChanged;
foreach (var autoSaveCollection in ResourceReferenceTools.GetAutoSaveCollections(instance))
autoSaveCollection.CollectionChanged += OnAutoSaveCollectionChanged;
}
/// <summary>
/// Register a resources events
/// </summary>
private void UnregisterEvents(Resource instance)
{
instance.Changed -= OnResourceChanged;
var asPublic = instance as IPublicResource;
if (asPublic != null)
asPublic.CapabilitiesChanged -= RaiseCapabilitiesChanged;
foreach (var autoSaveCollection in ResourceReferenceTools.GetAutoSaveCollections(instance))
autoSaveCollection.CollectionChanged -= OnAutoSaveCollectionChanged;
}
/// <summary>
/// Event handler when a resource was modified and the changes need to
/// written to storage
/// </summary>
private void OnResourceChanged(object sender, EventArgs eventArgs)
{
Save((Resource)sender);
}
/// <summary>
/// Build object graph from simplified <see cref="ResourceEntityAccessor"/> and flat resource list
/// </summary>
private void LinkReferences(ResourceEntityAccessor entityAccessor)
{
ResourceLinker.LinkReferences(entityAccessor.Instance, entityAccessor.Relations);
}
public void Start()
{
_startup = ResourceStartupPhase.Starting;
Parallel.ForEach(Graph.GetAll(), resourceWrapper =>
{
try
{
resourceWrapper.Start();
}
catch (Exception e)
{
resourceWrapper.ErrorOccured();
Logger.LogException(LogLevel.Warning, e, "Failed to start resource {0}-{1}", resourceWrapper.Target.Id, resourceWrapper.Target.Name);
}
});
_startup = ResourceStartupPhase.Started;
}
public void Stop()
{
_startup = ResourceStartupPhase.Stopping;
Parallel.ForEach(Graph.GetAll(), resourceWrapper =>
{
try
{
resourceWrapper.Stop();
UnregisterEvents(resourceWrapper.Target);
}
catch (Exception e)
{
Logger.LogException(LogLevel.Warning, e, "Failed to stop resource {0}-{1}", resourceWrapper.Target.Id, resourceWrapper.Target.Name);
}
});
_startup = ResourceStartupPhase.Stopped;
}
#endregion
public void Save(Resource resource)
{
lock (Graph.GetWrapper(resource.Id) ?? _fallbackLock)
{
using (var uow = UowFactory.Create())
{
var newResources = new HashSet<Resource>();
var entity = ResourceEntityAccessor.SaveToEntity(uow, resource);
if (entity.Id == 0)
newResources.Add(resource);
var newInstances = ResourceLinker.SaveReferences(uow, resource, entity);
newResources.AddRange(newInstances);
try
{
uow.SaveChanges();
}
catch (Exception ex)
{
Logger.LogException(LogLevel.Error, ex, "Error saving resource {0}-{1}!", resource.Id, resource.Name);
throw;
}
foreach (var instance in newResources)
AddResource(instance, true);
}
}
}
/// <summary>
/// A collection with "AutoSave = true" was modified. Write current state to the database
/// </summary>
private void OnAutoSaveCollectionChanged(object sender, ReferenceCollectionChangedEventArgs args)
{
var instance = args.Parent;
var property = args.CollectionProperty;
lock (Graph.GetWrapper(instance.Id)) // Unlike Save AutoSave collections are ALWAYS part of the Graph
{
using (var uow = UowFactory.Create())
{
var newResources = ResourceLinker.SaveSingleCollection(uow, instance, property);
try
{
uow.SaveChanges();
}
catch (Exception ex)
{
Logger.LogException(LogLevel.Error, ex, "Error saving collection {2} on resource {0}-{1}!", instance.Id, instance.Name, property.Name);
throw;
}
foreach (var newResource in newResources)
AddResource(newResource, true);
}
}
}
public void ExecuteInitializer(IResourceInitializer initializer)
{
var roots = initializer.Execute(Graph);
if (roots.Count == 0)
throw new InvalidOperationException("ResourceInitializer must return at least one resource");
using (var uow = UowFactory.Create())
{
ResourceLinker.SaveRoots(uow, roots);
uow.SaveChanges();
}
}
#region IResourceCreator
public bool Destroy(IResource resource, bool permanent)
{
var instance = (Resource)resource;
((IPlugin)resource).Stop();
// Load entity and relations to disconnect resource and remove from database
using (var uow = UowFactory.Create())
{
var resourceRepository = uow.GetRepository<IResourceEntityRepository>();
var relationRepository = uow.GetRepository<IResourceRelationRepository>();
// Fetch entity and relations
// Update properties on the references and get rid of relation entities
var entity = resourceRepository.GetByKey(instance.Id);
var relations = ResourceRelationAccessor.FromEntity(uow, entity);
foreach (var relation in relations)
{
var reference = Graph.Get(relation.ReferenceId);
ResourceLinker.RemoveLinking(resource, reference);
if (permanent)
relationRepository.Remove(relation.Entity);
}
resourceRepository.Remove(entity, permanent);
uow.SaveChanges();
}
// Unregister from all events to avoid memory leaks
UnregisterEvents(instance);
// Remove from internal collections
var removed = Graph.Remove(instance);
// Notify listeners about the removal of the resource
if (removed && instance is IPublicResource publicResource)
RaiseResourceRemoved(publicResource);
// Destroy the object
TypeController.Destroy(instance);
return removed;
}
#endregion
#region IResourceManagement
private void RaiseResourceAdded(IPublicResource newResource)
{
ResourceAdded?.Invoke(this, newResource);
}
public event EventHandler<IPublicResource> ResourceAdded;
private void RaiseResourceRemoved(IPublicResource newResource)
{
ResourceRemoved?.Invoke(this, newResource);
}
public event EventHandler<IPublicResource> ResourceRemoved;
///
public event EventHandler<ICapabilities> CapabilitiesChanged;
private void RaiseCapabilitiesChanged(object originalSender, ICapabilities capabilities)
{
// Only forward events for available resources
if (Graph.GetWrapper(((IResource)originalSender).Id).State.IsAvailable)
CapabilitiesChanged?.Invoke(originalSender, capabilities);
}
#endregion
}
}
| 35.20362 | 159 | 0.548008 | [
"Apache-2.0"
] | 1nf0rmagician/MORYX-AbstractionLayer | src/Moryx.Resources.Management/Resources/ResourceManager.cs | 15,560 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace Evolution.Samples.TravelingSalesmanProblem
{
public partial class FrmTsp : Form
{
private const int CITY_RECTANGLE_SIZE = 3;
private Graphics graphics;
public FrmTsp()
{
InitializeComponent();
graphics = pctMap.CreateGraphics();
}
private Tsp Tsp { get; set; }
private void btnGenerateMap_Click(object sender, EventArgs e)
{
GenerateEngine();
}
private void GenerateEngine()
{
Tsp = new Tsp((int) nbrNumberOfCities.Value,
chkCircular.Checked ? Tsp.PositionSelection.Circular : Tsp.PositionSelection.Random);
DrawMap();
}
private void DrawCities()
{
Size size = pctMap.Size;
foreach (City city in Tsp.Cities)
{
Point position = new Point((int) (city.Position.X*size.Width - CITY_RECTANGLE_SIZE/2),
(int) (city.Position.Y*size.Height - CITY_RECTANGLE_SIZE/2));
graphics.DrawRectangle(Pens.Red, position.X, position.Y, CITY_RECTANGLE_SIZE, CITY_RECTANGLE_SIZE);
}
}
private void DrawPath()
{
List<City> cities = Tsp.GetPath();
for (int i = 1; i < cities.Count; i++)
{
City city = cities[i];
City previousCity = cities[i - 1];
Size size = pctMap.Size;
Point cityPos = new Point((int) (city.Position.X*size.Width), (int) (city.Position.Y*size.Height));
Point previousCityPos = new Point((int) (previousCity.Position.X*size.Width),
(int) (previousCity.Position.Y*size.Height));
graphics.DrawLine(Pens.GreenYellow, cityPos, previousCityPos);
}
}
private void FrmTsp_Resize(object sender, EventArgs e)
{
graphics = pctMap.CreateGraphics();
DrawMap();
}
private void FrmTsp_Load(object sender, EventArgs e)
{
}
private void btnStepForward_Click(object sender, EventArgs e)
{
if (Tsp == null)
GenerateEngine();
Tsp.Evolve();
DrawMap();
}
private void DrawMap()
{
graphics.Clear(Color.White);
DrawPath();
DrawCities();
lblGeneration.Text = "Generation: " + (Tsp?.Generation ?? 0);
lblBestGeneration.Text = "Best Generation: " + (Tsp?.BestFitnessGeneration ?? 0);
lblBestFitness.Text = "Best Fitness: " + (Tsp?.BestFitness ?? 0).ToString("00.00");
}
private void btnRun_Click(object sender, EventArgs e)
{
if (Tsp == null)
GenerateEngine();
int x = 0;
while (Tsp.Evolve())
{
x++;
if (x%100 == 0)
{
DrawMap();
Application.DoEvents();
}
}
DrawMap();
}
private void lblGeneration_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
}
} | 29.025641 | 115 | 0.517668 | [
"Apache-2.0"
] | bgarate/Evolution | Evolution/Evolution.Samples.TravellingSalesmanProblem/frmTsp.cs | 3,398 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.ContractsLight;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using BuildXL.Cache.ContentStore.Exceptions;
using BuildXL.Cache.ContentStore.Extensions;
using BuildXL.Cache.ContentStore.FileSystem;
using BuildXL.Cache.ContentStore.Hashing;
using BuildXL.Cache.ContentStore.Interfaces.Extensions;
using BuildXL.Cache.ContentStore.Interfaces.FileSystem;
using BuildXL.Cache.ContentStore.Interfaces.Results;
using BuildXL.Cache.ContentStore.Interfaces.Sessions;
using BuildXL.Cache.ContentStore.Interfaces.Stores;
using BuildXL.Cache.ContentStore.Interfaces.Time;
using BuildXL.Cache.ContentStore.Interfaces.Tracing;
using BuildXL.Cache.ContentStore.Interfaces.Utils;
using BuildXL.Cache.ContentStore.Synchronization;
using BuildXL.Cache.ContentStore.Tracing;
using BuildXL.Cache.ContentStore.Tracing.Internal;
using BuildXL.Cache.ContentStore.UtilitiesCore;
using BuildXL.Cache.ContentStore.UtilitiesCore.Internal;
using BuildXL.Cache.ContentStore.Utils;
using BuildXL.Utilities;
using AbsolutePath = BuildXL.Cache.ContentStore.Interfaces.FileSystem.AbsolutePath;
using ContractUtilities = BuildXL.Cache.ContentStore.Utils.ContractUtilities;
using FileInfo = BuildXL.Cache.ContentStore.Interfaces.FileSystem.FileInfo;
using RelativePath = BuildXL.Cache.ContentStore.Interfaces.FileSystem.RelativePath;
namespace BuildXL.Cache.ContentStore.Stores
{
/// <summary>
/// Callback to update last access time based on external access times.
/// </summary>
public delegate Task UpdateContentWithLastAccessTimeAsync(ContentHash contentHash, DateTime dateTime);
/// <summary>
/// Checks if content is pinned locally and returns its content size.
/// </summary>
public delegate long PinnedSizeChecker(Context context, ContentHash contentHash);
/// <summary>
/// Content addressable store where content is stored on disk
/// </summary>
/// <remarks>
/// CacheRoot C:\blah\Cache
/// CacheShareRoot C:\blah\Cache\Shared \\machine\CAS
/// CacheContentRoot C:\blah\Cache\Shared\SHA1
/// ContentHashRoot C:\blah\Cache\Shared\SHA1\abc
/// </remarks>
public class FileSystemContentStoreInternal : StartupShutdownBase, IContentStoreInternal, IContentDirectoryHost
{
/// <nodoc />
public const bool DefaultApplyDenyWriteAttributesOnContent = false;
/// <summary>
/// Public name for monitoring use.
/// </summary>
public const string Component = "FileSystemContentStore";
/// <summary>
/// Name of counter for current size.
/// </summary>
public const string CurrentByteCountName = Component + ".CurrentByteCount";
/// <summary>
/// Name of counter for current number of blobs.
/// </summary>
public const string CurrentFileCountName = Component + ".CurrentFileCount";
/// <summary>
/// A history of the schema versions with comments describing the changes
/// </summary>
protected enum VersionHistory
{
/// <summary>
/// Content in CAS was marked read-only
/// </summary>
Version0 = 0,
/// <summary>
/// Content in C:\blah\Cache\SHA1
/// </summary>
Version1 = 1,
/// <summary>
/// Content in C:\blah\Cache\Shared\SHA1
/// </summary>
Version2 = 2,
/// <summary>
/// Content with attribute normalization and Deny WriteAttributes set
/// </summary>
CurrentVersion = 3
}
// TODO: Adjust defaults (bug 1365340)
private const int ParallelPlaceFilesLimit = 8;
/// <summary>
/// Format string for blob files
/// </summary>
private const string BlobNameExtension = "blob";
private static readonly int BlobNameExtensionLength = BlobNameExtension.Length;
/// <summary>
/// Directory to write temp files in.
/// </summary>
private const string TempFileSubdirectory = "temp";
/// <summary>
/// Length of subdirectory names used for storing files. For example with length 3,
/// content with hash "abcdefg" will be stored in $root\abc\abcdefg.blob.
/// </summary>
private const int HashDirectoryNameLength = 3;
/// <summary>
/// Name of the file in the cache directory that keeps track of the local CAS version.
/// </summary>
private const string VersionFileName = "LocalCAS.version";
/// <nodoc />
protected IAbsFileSystem FileSystem { get; }
/// <nodoc />
protected IClock Clock { get; }
/// <nodoc />
public AbsolutePath RootPath { get; }
/// <inheritdoc />
protected override Tracer Tracer => _tracer;
/// <nodoc />
public ContentStoreConfiguration Configuration { get; private set; }
/// <summary>
/// Gets helper to read/write version numbers
/// </summary>
protected SerializedDataValue SerializedDataVersion { get; }
private readonly ContentStoreInternalTracer _tracer = new ContentStoreInternalTracer();
private readonly ConfigurationModel _configurationModel;
private readonly AbsolutePath _contentRootDirectory;
private readonly AbsolutePath _tempFolder;
private readonly Dictionary<HashType, IContentHasher> _hashers;
/// <summary>
/// LockSet used to ensure thread safety on write operations.
/// </summary>
private readonly LockSet<ContentHash> _lockSet = new LockSet<ContentHash>();
private readonly NagleQueue<ContentHash> _nagleQueue;
private bool _applyDenyWriteAttributesOnContent;
private IContentChangeAnnouncer _announcer;
/// <summary>
/// Path to the file in the cache directory that keeps track of the local CAS version.
/// </summary>
protected readonly AbsolutePath VersionFilePath;
/// <summary>
/// List of cached files and their metadata.
/// </summary>
protected readonly IContentDirectory ContentDirectory;
/// <summary>
/// Tracker for the number of times each content has been pinned.
/// </summary>
protected readonly ConcurrentDictionary<ContentHash, Pin> PinMap = new ConcurrentDictionary<ContentHash, Pin>();
/// <summary>
/// Tracker for the index of the most recent successful hardlinked replica for each hash.
/// </summary>
private readonly ConcurrentDictionary<ContentHash, int> _replicaCursors = new ConcurrentDictionary<ContentHash, int>();
/// <summary>
/// Hook for performing some action immediately prior to evicting a file from the cache.
/// </summary>
/// <remarks>
/// For example, used in some tests to artificially slow the purger in order to simulate slower I/O for some scenarios.
/// </remarks>
private readonly Action _preEvictFileAction = null;
/// <summary>
/// Configuration for Distributed Eviction.
/// </summary>
private readonly DistributedEvictionSettings _distributedEvictionSettings;
/// <summary>
/// Stream containing the empty file.
/// </summary>
private readonly Stream _emptyFileStream = new MemoryStream(CollectionUtilities.EmptyArray<byte>(), false);
/// <summary>
/// Cumulative count of instances of the content directory being discovered as out of sync with the disk.
/// </summary>
private long _contentDirectoryMismatchCount;
private BackgroundTaskTracker _taskTracker;
private QuotaKeeper _quotaKeeper;
private PinSizeHistory _pinSizeHistory;
private int _pinContextCount;
private long _maxPinSize;
private readonly ContentStoreSettings _settings;
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemContentStoreInternal" /> class.
/// </summary>
public FileSystemContentStoreInternal(
IAbsFileSystem fileSystem,
IClock clock,
AbsolutePath rootPath,
ConfigurationModel configurationModel = null,
NagleQueue<ContentHash> nagleQueue = null,
DistributedEvictionSettings distributedEvictionSettings = null,
ContentStoreSettings settings = null)
{
Contract.Requires(fileSystem != null);
Contract.Requires(clock != null);
_hashers = HashInfoLookup.CreateAll();
int maxContentPathLengthRelativeToCacheRoot = GetMaxContentPathLengthRelativeToCacheRoot();
RootPath = rootPath;
if ((RootPath.Path.Length + 1 + maxContentPathLengthRelativeToCacheRoot) >= FileSystemConstants.MaxPath)
{
throw new CacheException("Root path does not provide enough room for cache paths to fit MAX_PATH");
}
_nagleQueue = nagleQueue;
Clock = clock;
FileSystem = fileSystem;
_configurationModel = configurationModel ?? new ConfigurationModel();
_contentRootDirectory = RootPath / Constants.SharedDirectoryName;
_tempFolder = _contentRootDirectory / TempFileSubdirectory;
VersionFilePath = RootPath / VersionFileName;
SerializedDataVersion = new SerializedDataValue(FileSystem, VersionFilePath, (int)VersionHistory.CurrentVersion);
ContentDirectory = new MemoryContentDirectory(FileSystem, RootPath, this);
_pinContextCount = 0;
_maxPinSize = -1;
_distributedEvictionSettings = distributedEvictionSettings;
_settings = settings ?? ContentStoreSettings.DefaultSettings;
}
private async Task PerformUpgradeToNextVersionAsync(Context context, VersionHistory currentVersion)
{
Contract.Requires(currentVersion < VersionHistory.CurrentVersion);
foreach (var hashName in HashInfoLookup.All().Select(hashInfo => hashInfo.Name))
{
AbsolutePath v0ContentFolder = RootPath / hashName;
Func<IEnumerable<AbsolutePath>> enumerateVersion0Blobs = () => FileSystem
.EnumerateFiles(v0ContentFolder, EnumerateOptions.Recurse)
.Where(fileInfo => fileInfo.FullPath.Path.EndsWith(BlobNameExtension, StringComparison.OrdinalIgnoreCase))
.Select(fileInfo => fileInfo.FullPath);
switch (currentVersion)
{
case VersionHistory.Version0:
Upgrade0To1(enumerateVersion0Blobs, v0ContentFolder);
break;
case VersionHistory.Version1:
Upgrade1To2(enumerateVersion0Blobs, v0ContentFolder);
break;
case VersionHistory.Version2:
await Upgrade2To3(context);
break;
default:
throw ContractUtilities.AssertFailure("Version migration code must be added.");
}
}
SerializedDataVersion.WriteValueFile((int)currentVersion + 1);
_tracer.Debug(context, $"version is now {(int)currentVersion + 1}");
}
private void Upgrade0To1(Func<IEnumerable<AbsolutePath>> enumerateVersion0Blobs, AbsolutePath v0ContentFolder)
{
if (FileSystem.DirectoryExists(v0ContentFolder))
{
Parallel.ForEach(
enumerateVersion0Blobs(),
path =>
{
FileAttributes attributes = FileSystem.GetFileAttributes(path);
if ((attributes & FileAttributes.ReadOnly) != 0)
{
FileSystem.SetFileAttributes(path, attributes & ~FileAttributes.ReadOnly);
}
});
}
}
private void Upgrade1To2(Func<IEnumerable<AbsolutePath>> enumerateVersion0Blobs, AbsolutePath v0ContentFolder)
{
if (FileSystem.DirectoryExists(v0ContentFolder))
{
Parallel.ForEach(
enumerateVersion0Blobs(),
oldPath =>
{
if (TryGetHashFromPath(oldPath, out var hash))
{
AbsolutePath newPath = GetPrimaryPathFor(hash);
FileSystem.CreateDirectory(newPath.Parent);
FileSystem.MoveFile(oldPath, newPath, true);
}
});
FileSystem.DeleteDirectory(v0ContentFolder, DeleteOptions.All);
}
}
private Task Upgrade2To3(Context context)
{
var upgradeCacheBlobAction = new ActionBlock<FileInfo>(
blobPath => ApplyPermissions(context, blobPath.FullPath, FileAccessMode.ReadOnly),
new ExecutionDataflowBlockOptions {MaxDegreeOfParallelism = Environment.ProcessorCount});
return upgradeCacheBlobAction.PostAllAndComplete(EnumerateBlobPathsFromDisk());
}
/// <summary>
/// Unit testing hook.
/// </summary>
protected virtual void UpgradeLegacyVsoContentRenameFile(AbsolutePath sourcePath, AbsolutePath destinationPath)
{
FileSystem.MoveFile(sourcePath, destinationPath, replaceExisting: false);
}
/// <summary>
/// Unit testing hook.
/// </summary>
protected virtual void UpgradeLegacyVsoContentRenameDirectory(AbsolutePath sourcePath, AbsolutePath destinationPath)
{
FileSystem.MoveDirectory(sourcePath, destinationPath);
}
/// <summary>
/// Unit testing hook.
/// </summary>
protected virtual void UpgradeLegacyVsoContentDeleteDirectory(AbsolutePath directory)
{
FileSystem.DeleteDirectory(directory, DeleteOptions.All);
}
private async Task UpgradeLegacyVsoContentAsync(Context context)
{
var legacyVsoContentRootPath = _contentRootDirectory / ((int)HashType.DeprecatedVso0).ToString();
if (FileSystem.DirectoryExists(legacyVsoContentRootPath))
{
var vsoContentRootPath = _contentRootDirectory / HashType.Vso0.ToString();
try
{
UpgradeLegacyVsoContentRenameDirectory(legacyVsoContentRootPath, vsoContentRootPath);
}
catch (Exception renameDirException)
{
context.Warning(
$"Could not rename [{legacyVsoContentRootPath}] to [{vsoContentRootPath}]. Falling back to hard-linking individual files. {renameDirException}");
if (!FileSystem.DirectoryExists(vsoContentRootPath))
{
FileSystem.CreateDirectory(vsoContentRootPath);
}
foreach (FileInfo fileInCache in FileSystem.EnumerateFiles(legacyVsoContentRootPath, EnumerateOptions.Recurse))
{
AbsolutePath destinationPath = fileInCache.FullPath.SwapRoot(legacyVsoContentRootPath, vsoContentRootPath);
AbsolutePath destinationFolder = destinationPath.Parent;
if (!FileSystem.DirectoryExists(destinationFolder))
{
FileSystem.CreateDirectory(destinationFolder);
}
else if (FileSystem.FileExists(destinationPath))
{
continue;
}
try
{
UpgradeLegacyVsoContentRenameFile(fileInCache.FullPath, destinationPath);
}
catch (Exception fileMoveException)
{
context.Debug(
$"Could not rename [{fileInCache.FullPath}] to [{destinationPath}]. Falling back to hard-linking. {fileMoveException}");
CreateHardLinkResult result = FileSystem.CreateHardLink(fileInCache.FullPath, destinationPath, replaceExisting: false);
if (result != CreateHardLinkResult.Success)
{
throw new CacheException(
$"Failed to create hard link from [{fileInCache.FullPath}] to [{destinationPath}]: {result}");
}
}
}
try
{
UpgradeLegacyVsoContentDeleteDirectory(legacyVsoContentRootPath);
}
catch (Exception deleteDirException)
{
context.Debug(
$"After moving or copying all content to [{vsoContentRootPath}], could not delete [{legacyVsoContentRootPath}]. Will try again next time. {deleteDirException}");
}
}
await MemoryContentDirectory.TransformFile(
context,
FileSystem,
RootPath,
pair =>
{
ContentHash contentHash = pair.Key;
ContentFileInfo fileInfo = pair.Value;
if (contentHash.HashType == HashType.DeprecatedVso0)
{
var hashBytes = contentHash.ToHashByteArray();
var newContentHash = new ContentHash(HashType.Vso0, hashBytes);
return new KeyValuePair<ContentHash, ContentFileInfo>(newContentHash, fileInfo);
}
return pair;
});
}
}
/// <summary>
/// Migrates (or just deletes) the schema on disk
/// </summary>
private async Task UpgradeAsNecessaryAsync(Context context)
{
int currentVersionNumber;
try
{
currentVersionNumber = ReadVersionNumber(context);
}
catch (Exception ex)
{
throw new CacheException(
ex,
"Failed to read the cache version file. Delete {0}, {1}, and {2} and try again. Exception message: {3}",
VersionFilePath,
_contentRootDirectory,
ContentDirectory.FilePath,
ex.ToString());
}
try
{
while (true)
{
if (currentVersionNumber > (int)VersionHistory.CurrentVersion || currentVersionNumber < (int)VersionHistory.Version0)
{
throw new CacheException(
"CAS runtime version is {0}, but disk has version {1}. Delete {2} and {3} or use the latest version of the cache.",
(int)VersionHistory.CurrentVersion,
currentVersionNumber,
_contentRootDirectory,
ContentDirectory.FilePath);
}
var currentVersion = (VersionHistory)currentVersionNumber;
if (currentVersion == VersionHistory.CurrentVersion)
{
break;
}
await PerformUpgradeToNextVersionAsync(context, currentVersion);
Contract.Assert((currentVersionNumber + 1) == SerializedDataVersion.ReadValueFile());
currentVersionNumber = ReadVersionNumber(context);
}
// Upgrade any legacy VSO hashed content without a painful CAS upgrade.
await UpgradeLegacyVsoContentAsync(context);
Contract.Assert(SerializedDataVersion.ReadValueFile() == (int)VersionHistory.CurrentVersion);
}
catch (Exception ex)
{
throw new CacheException(
ex,
"Failed to upgrade local CAS. Delete {0} and {1} and try again. Exception message: {2}",
_contentRootDirectory,
ContentDirectory.FilePath,
ex.ToString());
}
}
private int ReadVersionNumber(Context context)
{
int currentVersionNumber = SerializedDataVersion.ReadValueFile();
_tracer.Debug(context, $"version is {currentVersionNumber}");
return currentVersionNumber;
}
private void DeleteTempFolder()
{
if (FileSystem.DirectoryExists(_tempFolder))
{
FileSystem.DeleteDirectory(_tempFolder, DeleteOptions.All);
}
}
/// <inheritdoc />
public IReadOnlyList<KeyValuePair<ContentHash, ContentFileInfo>> Reconstruct(Context context)
{
// NOTE: DO NOT call ContentDirectory from this method as this is called during the initialization of ContentDirectory and calls
// into ContentDirectory would cause a deadlock.
var stopwatch = Stopwatch.StartNew();
long contentCount = 0;
long contentSize = 0;
try
{
var contentHashes = ReadContentHashesFromDisk(context);
_tracer.Debug(context, $"Enumerated {contentHashes.Count} entries by {stopwatch.ElapsedMilliseconds}ms.");
var hashInfoPairs = new List<KeyValuePair<ContentHash, ContentFileInfo>>();
foreach (var grouping in contentHashes.GroupBy(hash => hash))
{
var contentFileInfo = new ContentFileInfo(Clock, grouping.First().Size, grouping.Count());
contentCount++;
contentSize += contentFileInfo.TotalSize;
hashInfoPairs.Add(
new KeyValuePair<ContentHash, ContentFileInfo>(
grouping.Key.Hash,
contentFileInfo));
}
return hashInfoPairs;
}
catch (Exception exception)
{
_tracer.ReconstructDirectoryException(context, exception);
throw;
}
finally
{
stopwatch.Stop();
_tracer.ReconstructDirectory(context, stopwatch.Elapsed, contentCount, contentSize);
}
}
/// <inheritdoc />
public IContentChangeAnnouncer Announcer
{
get { return _announcer; }
set
{
Contract.Assert(_announcer == null);
_announcer = value;
}
}
/// <inheritdoc />
protected override async Task<BoolResult> StartupCoreAsync(OperationContext context)
{
var configFileExists = false;
if (_configurationModel.Selection == ConfigurationSelection.RequireAndUseInProcessConfiguration)
{
if (_configurationModel.InProcessConfiguration == null)
{
throw new CacheException("In-process configuration selected but it is null");
}
Configuration = _configurationModel.InProcessConfiguration;
}
else if (_configurationModel.Selection == ConfigurationSelection.UseFileAllowingInProcessFallback)
{
var readConfigResult = await FileSystem.ReadContentStoreConfigurationAsync(RootPath);
if (readConfigResult.Succeeded)
{
Configuration = readConfigResult.Data;
configFileExists = true;
}
else if (_configurationModel.InProcessConfiguration != null)
{
Configuration = _configurationModel.InProcessConfiguration;
}
else
{
throw new CacheException($"{nameof(ContentStoreConfiguration)} is missing");
}
}
else
{
throw new CacheException($"Invalid {nameof(ConfigurationSelection)}={_configurationModel.Selection}");
}
if (!configFileExists && _configurationModel.MissingFileOption == MissingConfigurationFileOption.WriteOnlyIfNotExists)
{
await Configuration.Write(FileSystem, RootPath);
}
_tracer.Debug(context, $"{nameof(ContentStoreConfiguration)}: {Configuration}");
_applyDenyWriteAttributesOnContent = Configuration.DenyWriteAttributesOnContent == DenyWriteAttributesOnContentSetting.Enable;
await UpgradeAsNecessaryAsync(context);
DeleteTempFolder();
FileSystem.CreateDirectory(_tempFolder);
await ContentDirectory.StartupAsync(context).ThrowIfFailure();
var contentDirectoryCount = await ContentDirectory.GetCountAsync();
if (contentDirectoryCount != 0 && !FileSystem.DirectoryExists(_contentRootDirectory))
{
return new BoolResult(
$"Content root directory {_contentRootDirectory} is missing despite CAS metadata indicating {contentDirectoryCount} files.");
}
var size = await ContentDirectory.GetSizeAsync();
_pinSizeHistory =
await
PinSizeHistory.LoadOrCreateNewAsync(
FileSystem,
Clock,
RootPath,
Configuration.HistoryBufferSize);
_distributedEvictionSettings?.InitializeDistributedEviction(
UpdateContentWithLastAccessTimeAsync,
_tracer,
GetPinnedSize,
_nagleQueue);
var quotaKeeperConfiguration = QuotaKeeperConfiguration.Create(
Configuration,
_distributedEvictionSettings,
_settings,
size);
_quotaKeeper = QuotaKeeper.Create(
FileSystem,
_tracer,
ShutdownStartedCancellationToken,
this,
quotaKeeperConfiguration);
var result = await _quotaKeeper.StartupAsync(context);
_taskTracker = new BackgroundTaskTracker(Component, new Context(context));
_tracer.StartStats(context, size, contentDirectoryCount);
return result;
}
/// <inheritdoc />
protected override async Task<BoolResult> ShutdownCoreAsync(OperationContext context)
{
var result = BoolResult.Success;
var statsResult = await GetStatsAsync(context);
if (_quotaKeeper != null)
{
_tracer.EndStats(context, _quotaKeeper.CurrentSize, await ContentDirectory.GetCountAsync());
// NOTE: QuotaKeeper must be shut down before the content directory because it owns
// background operations which may be calling EvictAsync or GetLruOrderedContentListAsync
result &= await _quotaKeeper.ShutdownAsync(context);
}
if (_pinSizeHistory != null)
{
await _pinSizeHistory.SaveAsync(FileSystem);
}
if (_taskTracker != null)
{
await _taskTracker.Synchronize();
await _taskTracker.ShutdownAsync(context);
}
if (ContentDirectory != null)
{
result &= await ContentDirectory.ShutdownAsync(context);
}
if (_contentDirectoryMismatchCount > 0)
{
_tracer.Warning(
context,
$"Corrected {_contentDirectoryMismatchCount} mismatches between cache blobs and content directory metadata.");
}
if (FileSystem.DirectoryExists(_tempFolder))
{
foreach (FileInfo fileInfo in FileSystem.EnumerateFiles(_tempFolder, EnumerateOptions.Recurse))
{
try
{
ForceDeleteFile(fileInfo.FullPath);
_tracer.Warning(context, $"Temp file still existed at shutdown: {fileInfo.FullPath}");
}
catch (IOException ioExecption)
{
_tracer.Warning(context, $"Could not clean up temp file due to exception: {ioExecption}");
}
}
}
if (statsResult)
{
statsResult.CounterSet.LogOrderedNameValuePairs(s => _tracer.Debug(context, s));
}
return result;
}
private static bool ShouldAttemptHardLink(AbsolutePath contentPath, FileAccessMode accessMode, FileRealizationMode realizationMode)
{
return contentPath.IsLocal && accessMode == FileAccessMode.ReadOnly &&
(realizationMode == FileRealizationMode.Any ||
realizationMode == FileRealizationMode.HardLink);
}
private bool TryCreateHardlink(
Context context,
AbsolutePath source,
AbsolutePath destination,
FileRealizationMode realizationMode,
bool replaceExisting,
out CreateHardLinkResult hardLinkResult)
{
var result = CreateHardLinkResult.Unknown;
var stopwatch = Stopwatch.StartNew();
try
{
result = FileSystem.CreateHardLink(source, destination, replaceExisting);
Contract.Assert((result == CreateHardLinkResult.FailedDestinationExists).Implies(!replaceExisting));
var resultAcceptable = false;
switch (result)
{
case CreateHardLinkResult.Success:
case CreateHardLinkResult.FailedDestinationExists:
case CreateHardLinkResult.FailedMaxHardLinkLimitReached:
case CreateHardLinkResult.FailedSourceDoesNotExist:
case CreateHardLinkResult.FailedAccessDenied:
case CreateHardLinkResult.FailedSourceHandleInvalid:
resultAcceptable = true;
break;
case CreateHardLinkResult.FailedNotSupported:
case CreateHardLinkResult.FailedSourceAndDestinationOnDifferentVolumes:
resultAcceptable = realizationMode != FileRealizationMode.HardLink;
break;
}
if (!resultAcceptable)
{
throw new CacheException("Failed to create hard link from [{0}] to [{1}]: {2}", source, destination, result);
}
hardLinkResult = result;
return hardLinkResult == CreateHardLinkResult.Success;
}
finally
{
stopwatch.Stop();
_tracer.CreateHardLink(context, result, source, destination, realizationMode, replaceExisting, stopwatch.Elapsed);
}
}
/// <inheritdoc />
public Task<PutResult> PutFileAsync(
Context context, AbsolutePath path, FileRealizationMode realizationMode, ContentHash contentHash, PinRequest? pinRequest)
{
return PutFileImplAsync(context, path, realizationMode, contentHash, pinRequest);
}
private Task<PutResult> PutFileImplAsync(
Context context, AbsolutePath path, FileRealizationMode realizationMode, ContentHash contentHash, PinRequest? pinRequest, Func<Stream, Stream> wrapStream = null)
{
return PutFileCall<ContentStoreInternalTracer>.RunAsync(
_tracer, OperationContext(context), path, realizationMode, contentHash, trustedHash: false, async () =>
{
PinContext pinContext = pinRequest.HasValue ? pinRequest.Value.PinContext : null;
bool shouldAttemptHardLink = ShouldAttemptHardLink(path, FileAccessMode.ReadOnly, realizationMode);
using (LockSet<ContentHash>.LockHandle contentHashHandle = await _lockSet.AcquireAsync(contentHash))
{
CheckPinned(contentHash, pinRequest);
long contentSize = await GetContentSizeInternalAsync(context, contentHash, pinContext);
if (contentSize >= 0)
{
// The user provided a hash for content that we already have. Try to satisfy the request without hashing the given file.
bool putInternalSucceeded;
if (shouldAttemptHardLink)
{
putInternalSucceeded = await PutContentInternalAsync(
context,
contentHash,
contentHashHandle,
contentSize,
pinContext,
onContentAlreadyInCache: async (hashHandle, primaryPath, info) =>
{
var r = await PlaceLinkFromCacheAsync(
context,
path,
FileReplacementMode.ReplaceExisting,
realizationMode,
hashHandle,
info);
return r == CreateHardLinkResult.Success;
},
onContentNotInCache: primaryPath => Task.FromResult(false),
announceAddOnSuccess: false);
}
else
{
putInternalSucceeded = await PutContentInternalAsync(
context,
contentHash,
contentHashHandle,
contentSize,
pinContext,
onContentAlreadyInCache: (hashHandle, primaryPath, info) => Task.FromResult(true),
onContentNotInCache: primaryPath => Task.FromResult(false));
}
if (putInternalSucceeded)
{
return new PutResult(contentHash, contentSize);
}
}
}
var result = await PutFileAsync(
context, path, contentHash.HashType, realizationMode, wrapStream, pinRequest);
if (realizationMode != FileRealizationMode.CopyNoVerify && result.ContentHash != contentHash && result.Succeeded)
{
return new PutResult(result.ContentHash, $"Content at {path} had actual content hash {result.ContentHash} and did not match expected value of {contentHash}");
}
return result;
});
}
/// <inheritdoc />
public Task<PutResult> PutFileAsync(
Context context, AbsolutePath path, FileRealizationMode realizationMode, HashType hashType, PinRequest? pinRequest)
{
return PutFileImplAsync(context, path, realizationMode, hashType, pinRequest, trustedHashWithSize: null);
}
private Task<PutResult> PutFileImplAsync(
Context context, AbsolutePath path, FileRealizationMode realizationMode, HashType hashType, PinRequest? pinRequest, ContentHashWithSize? trustedHashWithSize, Func<Stream, Stream> wrapStream = null)
{
Contract.Requires(trustedHashWithSize == null || trustedHashWithSize.Value.Size >= 0);
return PutFileCall<ContentStoreInternalTracer>.RunAsync(_tracer, OperationContext(context), path, realizationMode, hashType, trustedHash: trustedHashWithSize != null, async () =>
{
ContentHashWithSize content = trustedHashWithSize ?? default(ContentHashWithSize);
if (trustedHashWithSize == null)
{
// We only hash the file if a trusted hash is not supplied
using (var stream = await FileSystem.OpenAsync(path, FileAccess.Read, FileMode.Open, FileShare.Read | FileShare.Delete))
{
if (stream == null)
{
return new PutResult(default(ContentHash), $"Source file not found at '{path}'.");
}
using (var wrappedStream = (wrapStream == null) ? stream : wrapStream(stream))
{
// Hash the file in place
content = await HashContentAsync(context, wrappedStream, hashType, path);
}
}
}
using (LockSet<ContentHash>.LockHandle contentHashHandle = await _lockSet.AcquireAsync(content.Hash))
{
CheckPinned(content.Hash, pinRequest);
PinContext pinContext = pinRequest.HasValue ? pinRequest.Value.PinContext : null;
var stopwatch = new Stopwatch();
if (ShouldAttemptHardLink(path, FileAccessMode.ReadOnly, realizationMode))
{
bool putInternalSucceeded = await PutContentInternalAsync(
context,
content.Hash,
contentHashHandle,
content.Size,
pinContext,
onContentAlreadyInCache: async (hashHandle, primaryPath, info) =>
{
// The content exists in the cache. Try to replace the file that is being put in
// with a link to the file that is already in the cache. Release the handle to
// allow for the hardlink to succeed.
try
{
_tracer.PutFileExistingHardLinkStart();
stopwatch.Start();
// ReSharper disable once AccessToDisposedClosure
var result = await PlaceLinkFromCacheAsync(
context,
path,
FileReplacementMode.ReplaceExisting,
realizationMode,
hashHandle,
info);
return result == CreateHardLinkResult.Success;
}
finally
{
stopwatch.Stop();
_tracer.PutFileExistingHardLinkStop(stopwatch.Elapsed);
}
},
onContentNotInCache: primaryPath =>
{
try
{
_tracer.PutFileNewHardLinkStart();
stopwatch.Start();
ApplyPermissions(context, path, FileAccessMode.ReadOnly);
var hardLinkResult = CreateHardLinkResult.Unknown;
Func<bool> tryCreateHardlinkFunc = () => TryCreateHardlink(
context, path, primaryPath, realizationMode, false, out hardLinkResult);
bool result = tryCreateHardlinkFunc();
if (hardLinkResult == CreateHardLinkResult.FailedDestinationExists)
{
// Extraneous blobs on disk. Delete them and retry.
RemoveAllReplicasFromDiskFor(context, content.Hash);
result = tryCreateHardlinkFunc();
}
return Task.FromResult(result);
}
finally
{
stopwatch.Stop();
_tracer.PutFileNewHardLinkStop(stopwatch.Elapsed);
}
},
announceAddOnSuccess: false);
if (putInternalSucceeded)
{
return new PutResult(content.Hash, content.Size);
}
}
// If hard linking failed or wasn't attempted, fall back to copy.
stopwatch = new Stopwatch();
await PutContentInternalAsync(
context,
content.Hash,
contentHashHandle,
content.Size,
pinContext,
onContentAlreadyInCache: (hashHandle, primaryPath, info) => Task.FromResult(true),
onContentNotInCache: async primaryPath =>
{
try
{
_tracer.PutFileNewCopyStart();
stopwatch.Start();
await RetryOnUnexpectedReplicaAsync(
context,
() =>
{
if (realizationMode == FileRealizationMode.Move)
{
return Task.Run(() => FileSystem.MoveFile(path, primaryPath, replaceExisting: false));
}
else
{
return SafeCopyFileAsync(context, content.Hash, path, primaryPath, FileReplacementMode.FailIfExists);
}
},
content.Hash,
expectedReplicaCount: 0);
return true;
}
finally
{
stopwatch.Stop();
_tracer.PutFileNewCopyStop(stopwatch.Elapsed);
}
});
return new PutResult(content.Hash, content.Size);
}
});
}
/// <inheritdoc />
public Task<PutResult> PutTrustedFileAsync(Context context, AbsolutePath path, FileRealizationMode realizationMode, ContentHashWithSize contentHashWithSize, PinRequest? pinContext = null)
{
return PutFileImplAsync(context, path, realizationMode, contentHashWithSize.Hash.HashType, pinContext, trustedHashWithSize: contentHashWithSize);
}
/// <inheritdoc />
public Task<GetStatsResult> GetStatsAsync(Context context)
{
return GetStatsCall<ContentStoreInternalTracer>.RunAsync(_tracer, OperationContext(context), async () =>
{
var counters = new CounterSet();
counters.Merge(_tracer.GetCounters(), $"{Component}.");
if (StartupCompleted)
{
counters.Add($"{CurrentByteCountName}", _quotaKeeper.CurrentSize);
counters.Add($"{CurrentFileCountName}", await ContentDirectory.GetCountAsync());
counters.Merge(ContentDirectory.GetCounters(), "ContentDirectory.");
var quotaKeeperCounter = _quotaKeeper.Counters;
if (quotaKeeperCounter != null)
{
counters.Merge(quotaKeeperCounter.ToCounterSet());
}
}
foreach (var kvp in _hashers)
{
counters.Merge(kvp.Value.GetCounters(), $"{Component}.{kvp.Key}");
}
return new GetStatsResult(counters);
});
}
/// <inheritdoc />
// ReSharper disable once UnusedMember.Global
public async Task<bool> Validate(Context context)
{
bool foundIssue = false;
foundIssue |= !await ValidateNameHashesMatchContentHashesAsync(context);
foundIssue |= !ValidateAcls(context);
foundIssue |= !await ValidateContentDirectoryAsync(context);
return !foundIssue;
}
/// <inheritdoc />
public Task<IReadOnlyList<ContentInfo>> EnumerateContentInfoAsync()
{
return ContentDirectory.EnumerateContentInfoAsync();
}
/// <inheritdoc />
public Task<IEnumerable<ContentHash>> EnumerateContentHashesAsync()
{
return ContentDirectory.EnumerateContentHashesAsync();
}
/// <summary>
/// Complete all pending/background operations.
/// </summary>
public async Task SyncAsync(Context context, bool purge = true)
{
await _quotaKeeper.SyncAsync(context, purge);
// Ensure there are no pending LRU updates.
await ContentDirectory.SyncAsync();
}
/// <inheritdoc />
public PinSizeHistory.ReadHistoryResult ReadPinSizeHistory(int windowSize)
{
return _pinSizeHistory.ReadHistory(windowSize);
}
private async Task<bool> ValidateNameHashesMatchContentHashesAsync(Context context)
{
int mismatchedParentDirectoryCount = 0;
int mismatchedContentHashCount = 0;
_tracer.Always(context, "Validating local CAS content hashes...");
await TaskSafetyHelpers.WhenAll(EnumerateBlobPathsFromDisk().Select(
async blobPath =>
{
var contentFile = blobPath.FullPath;
if (!contentFile.FileName.StartsWith(contentFile.Parent.FileName, StringComparison.OrdinalIgnoreCase))
{
mismatchedParentDirectoryCount++;
_tracer.Debug(
context,
$"The first {HashDirectoryNameLength} characters of the name of content file at {contentFile}" +
$" do not match the name of its parent directory {contentFile.Parent.FileName}.");
}
if (!TryGetHashFromPath(contentFile, out var hashFromPath))
{
_tracer.Debug(
context,
$"The path '{contentFile}' does not contain a well-known hash name.");
return;
}
var hasher = _hashers[hashFromPath.HashType];
ContentHash hashFromContents;
using (Stream contentStream = await FileSystem.OpenSafeAsync(
contentFile, FileAccess.Read, FileMode.Open, FileShare.Read | FileShare.Delete, FileOptions.SequentialScan, HashingExtensions.HashStreamBufferSize))
{
hashFromContents = await hasher.GetContentHashAsync(contentStream);
}
if (hashFromContents != hashFromPath)
{
mismatchedContentHashCount++;
_tracer.Debug(
context,
$"Content at {contentFile} content hash {hashFromContents} did not match expected value of {hashFromPath}.");
}
}));
_tracer.Always(context, $"{mismatchedParentDirectoryCount} mismatches between content file name and parent directory.");
_tracer.Always(context, $"{mismatchedContentHashCount} mismatches between content file name and file contents.");
return mismatchedContentHashCount == 0 && mismatchedParentDirectoryCount == 0;
}
private bool ValidateAcls(Context context)
{
// Getting ACLs currently requires using File.GetAccessControl. We should extend IAbsFileSystem to enable this query.
if (!(FileSystem is PassThroughFileSystem))
{
_tracer.Always(context, "Skipping validation of ACLs because the CAS is not using a PassThroughFileSystem.");
return true;
}
_tracer.Always(context, "Validating local CAS content file ACLs...");
int missingDenyAclCount = 0;
foreach (var blobPath in EnumerateBlobPathsFromDisk())
{
var contentFile = blobPath.FullPath;
// FileSystem has no GetAccessControl API, so we must bypass it here. We can relax the restriction to PassThroughFileSystem once we implement GetAccessControl in IAbsFileSystem.
bool denyAclExists = true;
#if !FEATURE_CORECLR
const string worldSidValue = "Everyone";
var security = File.GetAccessControl(contentFile.Path);
var fileSystemAccessRules =
security.GetAccessRules(true, false, typeof(NTAccount)).Cast<FileSystemAccessRule>();
denyAclExists = fileSystemAccessRules.Any(rule =>
rule.IdentityReference.Value.Equals(worldSidValue, StringComparison.OrdinalIgnoreCase) &&
rule.AccessControlType == AccessControlType.Deny &&
rule.FileSystemRights == (_applyDenyWriteAttributesOnContent
? (FileSystemRights.WriteData | FileSystemRights.AppendData)
: FileSystemRights.Write) && // Should this be exact (as it is now), or at least, deny ACLs?
rule.InheritanceFlags == InheritanceFlags.None &&
rule.IsInherited == false &&
rule.PropagationFlags == PropagationFlags.None
);
#endif
if (!denyAclExists)
{
missingDenyAclCount++;
_tracer.Always(context, $"Content at {contentFile} is missing proper deny ACLs.");
}
}
_tracer.Always(context, $"{missingDenyAclCount} projects are missing proper deny ACLs.");
return missingDenyAclCount == 0;
}
private async Task<bool> ValidateContentDirectoryAsync(Context context)
{
_tracer.Always(context, "Validating local CAS content directory");
int contentDirectoryMismatchCount = 0;
var fileSystemContentDirectory = EnumerateBlobPathsFromDisk()
.Select(blobPath => TryGetHashFromPath(blobPath.FullPath, out var hash) ? (ContentHash?)hash : null)
.Where(hash => hash != null)
.GroupBy(hash => hash.Value)
.ToDictionary(replicaGroup => replicaGroup.Key, replicaGroup => replicaGroup.Count());
foreach (var x in fileSystemContentDirectory.Keys)
{
var fileSystemHash = x;
int fileSystemHashReplicaCount = fileSystemContentDirectory[fileSystemHash];
await ContentDirectory.UpdateAsync(fileSystemHash, false, Clock, fileInfo =>
{
if (fileInfo == null)
{
contentDirectoryMismatchCount++;
_tracer.Always(context, $"Cache content directory for hash {fileSystemHash} from disk does not exist.");
}
else if (fileInfo.ReplicaCount != fileSystemHashReplicaCount)
{
contentDirectoryMismatchCount++;
_tracer.Always(
context,
$"Directory for hash {fileSystemHash} describes {fileInfo.ReplicaCount} replicas, but {fileSystemHashReplicaCount} replicas exist on disk.");
}
return null;
});
}
foreach (var x in (await ContentDirectory.EnumerateContentHashesAsync())
.Where(hash => !fileSystemContentDirectory.ContainsKey(hash)))
{
var missingHash = x;
contentDirectoryMismatchCount++;
await ContentDirectory.UpdateAsync(missingHash, false, Clock, fileInfo =>
{
if (fileInfo != null)
{
_tracer.Always(
context,
$"Directory for hash {missingHash} describes {fileInfo.ReplicaCount} replicas, but no replicas exist on disk.");
}
return null;
});
}
_tracer.Always(
context, $"{contentDirectoryMismatchCount} mismatches between cache content directory and content files on disk.");
return contentDirectoryMismatchCount == 0;
}
/// <summary>
/// Protected implementation of Dispose pattern.
/// </summary>
protected override void DisposeCore()
{
base.DisposeCore();
foreach (IContentHasher hasher in _hashers.Values)
{
hasher.Dispose();
}
_quotaKeeper?.Dispose();
_taskTracker?.Dispose();
ContentDirectory.Dispose();
}
/// <summary>
/// Called by PutContentInternalAsync when the content already exists in the cache.
/// </summary>
/// <returns>True if the callback is successful.</returns>
private delegate Task<bool> OnContentAlreadyExistsInCacheAsync(
LockSet<ContentHash>.LockHandle contentHashHandle, AbsolutePath primaryPath, ContentFileInfo info);
/// <summary>
/// Called by PutContentInternalAsync when the content already exists in the cache.
/// </summary>
/// <returns>True if the callback is successful.</returns>
private delegate Task<bool> OnContentNotInCacheAsync(AbsolutePath primaryPath);
private async Task<bool> PutContentInternalAsync(
Context context,
ContentHash contentHash,
LockSet<ContentHash>.LockHandle contentHashHandle,
long contentSize,
PinContext pinContext,
OnContentAlreadyExistsInCacheAsync onContentAlreadyInCache,
OnContentNotInCacheAsync onContentNotInCache,
bool announceAddOnSuccess = true)
{
AbsolutePath primaryPath = GetPrimaryPathFor(contentHash);
bool failed = false;
long addedContentSize = 0;
_tracer.PutContentInternalStart();
var stopwatch = Stopwatch.StartNew();
await ContentDirectory.UpdateAsync(contentHash, touch: true, Clock, async fileInfo =>
{
if (fileInfo == null || await RemoveEntryIfNotOnDiskAsync(context, contentHash))
{
using (var txn = await _quotaKeeper.ReserveAsync(contentSize))
{
FileSystem.CreateDirectory(primaryPath.Parent);
if (!await onContentNotInCache(primaryPath))
{
failed = true;
return null;
}
txn.Commit();
PinContentIfContext(contentHash, pinContext);
addedContentSize = contentSize;
return new ContentFileInfo(Clock, contentSize);
}
}
if (!await onContentAlreadyInCache(contentHashHandle, primaryPath, fileInfo))
{
failed = true;
return null;
}
PinContentIfContext(contentHash, pinContext);
addedContentSize = fileInfo.FileSize;
return fileInfo;
});
_tracer.PutContentInternalStop(stopwatch.Elapsed);
if (failed)
{
return false;
}
if (addedContentSize > 0)
{
_tracer.AddPutBytes(addedContentSize);
}
if (_announcer != null && addedContentSize > 0 && announceAddOnSuccess)
{
await _announcer.ContentAdded(new ContentHashWithSize(contentHash, addedContentSize));
}
return true;
}
/// <inheritdoc />
public Task<PutResult> PutStreamAsync(Context context, Stream stream, ContentHash contentHash, PinRequest? pinRequest)
{
return PutStreamCall<ContentStoreInternalTracer>.RunAsync(_tracer, OperationContext(context), contentHash, async () =>
{
PinContext pinContext = pinRequest.HasValue ? pinRequest.Value.PinContext : null;
using (LockSet<ContentHash>.LockHandle contentHashHandle = await _lockSet.AcquireAsync(contentHash))
{
CheckPinned(contentHash, pinRequest);
long contentSize = await GetContentSizeInternalAsync(context, contentHash, pinContext);
if (contentSize >= 0)
{
// The user provided a hash for content that we already have. Try to satisfy the request without hashing the given stream.
bool putInternalSucceeded = await PutContentInternalAsync(
context,
contentHash,
contentHashHandle,
contentSize,
pinContext,
onContentAlreadyInCache: (hashHandle, primaryPath, info) => Task.FromResult(true),
onContentNotInCache: primaryPath => Task.FromResult(false));
if (putInternalSucceeded)
{
return new PutResult(contentHash, contentSize);
}
}
}
var r = await PutStreamImplAsync(context, stream, contentHash.HashType, pinRequest);
return r.ContentHash != contentHash && r.Succeeded
? new PutResult(r, contentHash, $"Calculated hash={r.ContentHash} does not match caller's hash={contentHash}")
: r;
});
}
/// <inheritdoc />
public Task<PutResult> PutStreamAsync(Context context, Stream stream, HashType hashType, PinRequest? pinRequest)
{
return PutStreamCall<ContentStoreInternalTracer>.RunAsync(
_tracer, OperationContext(context), hashType, () => PutStreamImplAsync(context, stream, hashType, pinRequest));
}
private async Task<PutResult> PutStreamImplAsync(Context context, Stream stream, HashType hashType, PinRequest? pinRequest)
{
PinContext pinContext = pinRequest.HasValue ? pinRequest.Value.PinContext : null;
ContentHash contentHash = new ContentHash(hashType);
AbsolutePath pathToTempContent = null;
bool shouldDelete = false;
try
{
long contentSize;
var hasher = _hashers[hashType];
using (var hashingStream = hasher.CreateReadHashingStream(stream))
{
pathToTempContent = await WriteToTemporaryFileAsync(context, hashingStream);
contentSize = FileSystem.GetFileSize(pathToTempContent);
contentHash = hashingStream.GetContentHash();
// This our temp file and it is responsibility of this method to delete it.
shouldDelete = true;
}
using (LockSet<ContentHash>.LockHandle contentHashHandle = await _lockSet.AcquireAsync(contentHash))
{
CheckPinned(contentHash, pinRequest);
if (!await PutContentInternalAsync(
context,
contentHash,
contentHashHandle,
contentSize,
pinContext,
onContentAlreadyInCache: (hashHandle, primaryPath, info) => Task.FromResult(true),
onContentNotInCache: async primaryPath =>
{
// ReSharper disable once AccessToModifiedClosure
await RetryOnUnexpectedReplicaAsync(
context,
() =>
{
FileSystem.MoveFile(pathToTempContent, primaryPath, replaceExisting: false);
return Task.FromResult(true);
},
contentHash,
expectedReplicaCount: 0);
pathToTempContent = null;
return true;
}))
{
return new PutResult(contentHash, $"{nameof(PutStreamAsync)} failed to put {pathToTempContent} with hash {contentHash} with an unknown error");
}
return new PutResult(contentHash, contentSize);
}
}
finally
{
if (shouldDelete)
{
DeleteTempFile(context, contentHash, pathToTempContent);
}
}
}
/// <summary>
/// Deletes a file that is marked read-only
/// </summary>
/// <param name="path">Path to the file</param>
protected virtual void DeleteReadOnlyFile(AbsolutePath path)
{
Contract.Requires(path != null);
FileSystem.DeleteFile(path);
}
private void ForceDeleteFile(AbsolutePath path)
{
if (path == null)
{
return;
}
DeleteReadOnlyFile(path);
}
private void TryForceDeleteFile(Context context, AbsolutePath path)
{
try
{
ForceDeleteFile(path);
}
catch (Exception exception) when (exception is IOException || exception is BuildXLException || exception is UnauthorizedAccessException)
{
_tracer.Debug(context, $"Unable to force delete {path.Path} exception=[{exception}]");
}
}
private void DeleteTempFile(Context context, ContentHash contentHash, AbsolutePath path)
{
if (path == null)
{
return;
}
if (!path.Parent.Equals(_tempFolder))
{
_tracer.Error(context, $"Will not delete temp file in unexpected location, path=[{path}]");
return;
}
try
{
ForceDeleteFile(path);
_tracer.Debug(context, $"Deleted temp content at '{path.Path}' for {contentHash}");
}
catch (Exception exception) when (exception is IOException || exception is BuildXLException || exception is UnauthorizedAccessException)
{
_tracer.Warning(
context,
$"Unable to delete temp content at '{path.Path}' for {contentHash} due to exception: {exception}");
}
}
private AbsolutePath GetTemporaryFileName()
{
return _tempFolder / GetRandomFileName();
}
private AbsolutePath GetTemporaryFileName(ContentHash contentHash)
{
return _tempFolder / (GetRandomFileName() + contentHash.ToHex());
}
private static string GetRandomFileName()
{
// Don't use Path.GetRandomFileName(), it's not random enough when running multi-threaded.
return Guid.NewGuid().ToString("N").Substring(0, 12);
}
/// <summary>
/// Writes the content stream to local disk in a temp directory under the store's root.
/// Marks the file as Read Only and sets ACL to deny file writes.
/// </summary>
/// <param name="context">Tracing context.</param>
/// <param name="inputStream">Content stream to write</param>
/// <returns>Absolute path that points to the file</returns>
private async Task<AbsolutePath> WriteToTemporaryFileAsync(Context context, Stream inputStream)
{
AbsolutePath pathToTempContent = GetTemporaryFileName();
AbsolutePath pathToTempContentDirectory = pathToTempContent.Parent;
FileSystem.CreateDirectory(pathToTempContentDirectory);
// We want to set an ACL which denies writes before closing the destination stream. This way, there
// are no instants in which we have neither an exclusive lock on writing the file nor a protective
// ACL. Note that we can still be fooled in the event of external tampering via renames/move, but this
// approach makes it very unlikely that our own code would ever write to or truncate the file before we move it.
using (Stream tempFileStream = await FileSystem.OpenSafeAsync(pathToTempContent, FileAccess.Write, FileMode.CreateNew, FileShare.Delete))
{
await inputStream.CopyToWithFullBufferAsync(tempFileStream, FileSystemConstants.FileIOBufferSize);
ApplyPermissions(context, pathToTempContent, FileAccessMode.ReadOnly);
}
return pathToTempContent;
}
private async Task<ContentHashWithSize> HashContentAsync(Context context, Stream stream, HashType hashType, AbsolutePath path)
{
Contract.Requires(stream != null);
var stopwatch = new Stopwatch();
try
{
_tracer.HashContentFileStart(context, path);
stopwatch.Start();
ContentHash contentHash = await _hashers[hashType].GetContentHashAsync(stream);
return new ContentHashWithSize(contentHash, stream.Length);
}
catch (Exception e)
{
_tracer.Error(context, e, "Error while hashing content.");
throw;
}
finally
{
stopwatch.Stop();
_tracer.HashContentFileStop(context, path, stopwatch.Elapsed);
}
}
private void ApplyPermissions(Context context, AbsolutePath path, FileAccessMode accessMode)
{
var stopwatch = new Stopwatch();
try
{
_tracer.ApplyPermsStart();
stopwatch.Start();
if (accessMode == FileAccessMode.ReadOnly)
{
FileSystem.DenyFileWrites(path);
if (_applyDenyWriteAttributesOnContent)
{
if (_applyDenyWriteAttributesOnContent && !IsNormalEnough(path))
{
// Only normalize attributes if DenyWriteAttributesOnContent is set
Normalize(path);
}
FileSystem.DenyAttributeWrites(path);
if (!IsNormalEnough(path))
{
throw new CacheException("The attributes of file {0} were modified during ingress. Found flags: {1}", path, File.GetAttributes(path.Path).ToString());
}
}
}
else if (_applyDenyWriteAttributesOnContent && !IsNormalEnough(path))
{
// Only normalize attributes if DenyWriteAttributesOnContent is set
Normalize(path);
}
// When DenyWriteAttributesOnContent is set to false, we shouldn't give an error
// even if clearing potential Deny-WriteAttributes fails. This is especially true
// because in most cases where we're unable to clear those ACLs, we were probably
// unable to set them in the first place.
if (!_applyDenyWriteAttributesOnContent)
{
try
{
FileSystem.AllowAttributeWrites(path);
}
catch (IOException ex)
{
context.Warning(ex.ToString());
}
}
}
finally
{
stopwatch.Stop();
_tracer.ApplyPermsStop(stopwatch.Elapsed);
}
}
private void Normalize(AbsolutePath path)
{
try
{
FileSystem.SetFileAttributes(path, FileAttributes.Normal);
}
catch (IOException)
{
FileSystem.AllowAttributeWrites(path);
FileSystem.SetFileAttributes(path, FileAttributes.Normal);
}
catch (UnauthorizedAccessException)
{
FileSystem.AllowAttributeWrites(path);
FileSystem.SetFileAttributes(path, FileAttributes.Normal);
}
}
// Since setting ACLs seems to flip on the Archive bit,
// we have to be content with allowing the archive bit to be set for cache blobs
// We're whitelisting even more here because other values (that we don't care about)
// sometimes survive being set to "Normal," and we don't want to throw in those cases.
private bool IsNormalEnough(AbsolutePath path)
{
const FileAttributes ignoredFileAttributes =
FileAttributes.Normal | FileAttributes.Archive | FileAttributes.Compressed |
FileAttributes.SparseFile | FileAttributes.Encrypted | FileAttributes.Offline |
FileAttributes.IntegrityStream | FileAttributes.NoScrubData | FileAttributes.System |
FileAttributes.Temporary | FileAttributes.Device | FileAttributes.Directory |
FileAttributes.NotContentIndexed | FileAttributes.ReparsePoint | FileAttributes.Hidden;
return FileSystem.FileAttributesAreSubset(path, ignoredFileAttributes);
}
private enum ForEachReplicaCallbackResult
{
StopIterating,
TryNextReplicaIfExists,
TryNextReplica
}
private enum ReplicaExistence
{
Exists,
DoesNotExist
}
private delegate Task<ForEachReplicaCallbackResult> ForEachReplicaCallback(
AbsolutePath primaryPath, int replicaIndex, AbsolutePath replicaPath, bool replicaExists);
// Perform the callback for each replica, starting from the primary replica (index 0)
private async Task ForEachReplicaAsync(
LockSet<ContentHash>.LockHandle contentHashHandle, ContentFileInfo info, ForEachReplicaCallback pathCallback)
{
AbsolutePath primaryPath = GetPrimaryPathFor(contentHashHandle.Key);
ForEachReplicaCallbackResult result = await pathCallback(primaryPath, 0, primaryPath, true);
if (result == ForEachReplicaCallbackResult.StopIterating)
{
return;
}
for (int replicaIndex = 1;
replicaIndex < info.ReplicaCount || result == ForEachReplicaCallbackResult.TryNextReplica;
replicaIndex++)
{
var replicaPath = GetReplicaPathFor(contentHashHandle.Key, replicaIndex);
result = await pathCallback(primaryPath, replicaIndex, replicaPath, replicaIndex < info.ReplicaCount);
if (result == ForEachReplicaCallbackResult.StopIterating)
{
return;
}
}
}
/// <summary>
/// Gets the path that points to the location of a particular replica of this content hash.
/// </summary>
/// <param name="contentHash">Content hash to get path for</param>
/// <param name="replicaIndex">The index of the replica. 0 is the primary.</param>
/// <returns>Path for the hash</returns>
/// <remarks>Does not guarantee anything is at the returned path</remarks>
protected AbsolutePath GetReplicaPathFor(ContentHash contentHash, int replicaIndex)
{
Contract.Requires(replicaIndex >= 0);
// MOve hashtype into inner call
return _contentRootDirectory / contentHash.HashType.Serialize() / GetRelativePathFor(contentHash, replicaIndex);
}
/// <summary>
/// Gets the path that points to the location of this content hash.
/// </summary>
/// <param name="contentHash">Content hash to get path for</param>
/// <returns>Path for the hash</returns>
/// <remarks>Does not guarantee anything is at the returned path</remarks>
protected AbsolutePath GetPrimaryPathFor(ContentHash contentHash)
{
return GetReplicaPathFor(contentHash, 0);
}
private static RelativePath GetRelativePathFor(ContentHash contentHash, int replicaIndex)
{
string hash = contentHash.ToHex();
// Create a subdirectory to not stress directory-wide locks used by the file system
var hashSubDirectory = GetHashSubDirectory(contentHash);
if (replicaIndex == 0)
{
return hashSubDirectory / string.Format(CultureInfo.InvariantCulture, "{0}.{1}", hash, BlobNameExtension);
}
return hashSubDirectory /
string.Format(CultureInfo.InvariantCulture, "{0}.{1}.{2}", hash, replicaIndex, BlobNameExtension);
}
private static RelativePath GetHashSubDirectory(ContentHash contentHash)
{
return new RelativePath(contentHash.ToHex().Substring(0, HashDirectoryNameLength));
}
private List<ContentHashWithSize> ReadContentHashesFromDisk(Context context)
{
var contentHashes = new List<ContentHashWithSize>();
if (_settings.UseNativeBlobEnumeration)
{
EnumerateBlobPathsFromDisk(context, fileInfo => parseAndAccumulateContentHashes(fileInfo));
}
else
{
foreach (var fileInfo in EnumerateBlobPathsFromDisk())
{
parseAndAccumulateContentHashes(fileInfo);
}
}
return contentHashes;
void parseAndAccumulateContentHashes(FileInfo fileInfo)
{
// A directory could have an old hash in its name or may be renamed by the user.
// This is not an error condition if we can't get the hash out of it.
if (TryGetHashFromPath(fileInfo.FullPath, out var contentHash))
{
contentHashes.Add(new ContentHashWithSize(contentHash, fileInfo.Length));
}
else
{
_tracer.Debug(context, $"Can't process directory '{fileInfo.FullPath}' because the path does not contain a well-known hash name.");
}
}
}
private IEnumerable<FileInfo> EnumerateBlobPathsFromDisk()
{
if (!FileSystem.DirectoryExists(_contentRootDirectory))
{
return new FileInfo[] {};
}
return FileSystem
.EnumerateFiles(_contentRootDirectory, EnumerateOptions.Recurse)
.Where(
fileInfo => fileInfo.FullPath.Path.EndsWith(BlobNameExtension, StringComparison.OrdinalIgnoreCase));
}
private void EnumerateBlobPathsFromDisk(Context context, Action<FileInfo> fileHandler)
{
try
{
FileSystem.EnumerateFiles(_contentRootDirectory, $"*.{BlobNameExtension}", recursive: true, fileHandler);
}
catch (IOException e)
{
_tracer.Info(context, $"Error enumerating blobs: {e}");
}
}
private IEnumerable<FileInfo> EnumerateBlobPathsFromDiskFor(ContentHash contentHash)
{
var hashSubPath = _contentRootDirectory / contentHash.HashType.ToString() / GetHashSubDirectory(contentHash);
if (!FileSystem.DirectoryExists(hashSubPath))
{
return new FileInfo[] {};
}
return FileSystem
.EnumerateFiles(hashSubPath, EnumerateOptions.None)
.Where(fileInfo =>
{
var filePath = fileInfo.FullPath;
return TryGetHashFromPath(filePath, out var hash) &&
hash.Equals(contentHash) &&
filePath.FileName.EndsWith(BlobNameExtension, StringComparison.OrdinalIgnoreCase);
});
}
internal static bool TryGetHashFromPath(AbsolutePath path, out ContentHash contentHash)
{
var hashName = path.Parent.Parent.FileName;
if (Enum.TryParse<HashType>(hashName, ignoreCase: true, out var hashType))
{
string hashHexString = GetFileNameWithoutExtension(path);
try
{
contentHash = new ContentHash(hashType, HexUtilities.HexToBytes(hashHexString));
}
catch (ArgumentException)
{
// If the file name format is malformed, throw an exception with more actionable error message.
throw new CacheException($"Failed to obtain the hash from file name '{path}'. File name should be in hexadecimal form.");
}
return true;
}
contentHash = default;
return false;
}
/// <nodoc />
public static string GetFileNameWithoutExtension(AbsolutePath path)
{
// Unlike <see cref = "Path.GetFileNameWithoutExtension" /> this method returns the name before the first '.', not the name until the last '.'.
// I.e. for a file name <code>"foo.bar.baz"</code> this method returns "foo", but <see cref="Path.GetFileNameWithoutExtension"/> returns "foo.bar".
Contract.Requires(path != null);
string fileName = path.GetFileName();
if (fileName.IndexOf('.') is var i && i == -1)
{
// No path extension found.
return fileName;
}
return fileName.Substring(0, i);
}
private int GetReplicaIndexFromPath(AbsolutePath path)
{
if (TryGetHashFromPath(path, out var contentHash))
{
string fileName = path.GetFileName();
// ReSharper disable once PossibleNullReferenceException
if (fileName.StartsWith(contentHash.ToHex(), StringComparison.OrdinalIgnoreCase) &&
fileName.EndsWith(BlobNameExtension, StringComparison.OrdinalIgnoreCase))
{
var fileNameParts = fileName.Split('.');
if (fileNameParts.Length == 2)
{
return 0;
}
if (fileNameParts.Length == 3)
{
if (int.TryParse(fileNameParts[1], out var index))
{
return index;
}
}
}
}
return -1;
}
/// <summary>
/// Snapshots the cached content in LRU order (i.e. the order, according to last-access time, in which they should be
/// purged to make space).
/// </summary>
/// <returns>LRU-ordered hashes.</returns>
public virtual Task<IReadOnlyList<ContentHash>> GetLruOrderedContentListAsync()
{
return ContentDirectory.GetLruOrderedCacheContentAsync();
}
/// <summary>
/// Snapshots the cached content in LRU order (i.e. the order, according to last-access time, in which they should be
/// purged to make space). Coupled with its last-access time.
/// </summary>
public virtual Task<IReadOnlyList<ContentHashWithLastAccessTimeAndReplicaCount>> GetLruOrderedContentListWithTimeAsync()
{
return ContentDirectory.GetLruOrderedCacheContentWithTimeAsync();
}
/// <summary>
/// Update content with provided last access time.
/// </summary>
public async Task UpdateContentWithLastAccessTimeAsync(ContentHash contentHash, DateTime lru)
{
using (await _lockSet.AcquireAsync(contentHash))
{
ContentDirectory.UpdateContentWithLastAccessTime(contentHash, lru);
}
}
private bool TryGetContentTotalSize(ContentHash contentHash, out long size)
{
if (ContentDirectory.TryGetFileInfo(contentHash, out var fileInfo))
{
size = fileInfo.TotalSize;
return true;
}
size = 0;
return false;
}
/// <summary>
/// Remove specified content.
/// </summary>
public async Task<EvictResult> EvictAsync(Context context, ContentHashWithLastAccessTimeAndReplicaCount contentHashInfo, bool onlyUnlinked, Action<long> evicted)
{
ContentHash contentHash = contentHashInfo.ContentHash;
long pinnedSize = 0;
using (LockSet<ContentHash>.LockHandle? contentHashHandle = _lockSet.TryAcquire(contentHash))
{
if (contentHashHandle == null)
{
_tracer.Debug(context, $"Skipping check of pinned size for {contentHash} because another thread has a lock on it.");
return new EvictResult(evictedSize: 0, evictedFiles: 0, pinnedSize: 0, contentHashInfo.LastAccessTime, successfullyEvictedHash: false, contentHashInfo.ReplicaCount);
}
if (PinMap.TryGetValue(contentHash, out var pin) && pin.Count > 0)
{
// The content is pinned. Eviction is not possible in this case.
if (TryGetContentTotalSize(contentHash, out var size))
{
pinnedSize = size;
}
return new EvictResult(evictedSize: 0, evictedFiles: 0, pinnedSize: pinnedSize, contentHashInfo.LastAccessTime, successfullyEvictedHash: false, contentHashInfo.ReplicaCount);
}
// Intentionally tracking only (potentially) successful eviction.
return await EvictCall.RunAsync(
_tracer,
OperationContext(context),
contentHash,
async () =>
{
long evictedSize = 0;
long evictedFiles = 0;
bool successfullyEvictedHash = false;
await ContentDirectory.UpdateAsync(
contentHash,
touch: false,
Clock,
async fileInfo =>
{
if (fileInfo == null)
{
// The content is not found in content directory.
return null;
}
if (PinMap.TryGetValue(contentHash, out pin) && pin.Count > 0)
{
pinnedSize = fileInfo.TotalSize;
// Nothing was modified, so no need to save anything.
return null;
}
// Used by tests to inject an arbitrary delay
_preEvictFileAction?.Invoke();
await ContentDirectory.RemoveAsync(contentHash);
var remainingReplicas = new List<AbsolutePath>(0);
var evictions = new List<ContentHashWithSize>();
// ReSharper disable once AccessToDisposedClosure
await ForEachReplicaAsync(
contentHashHandle.Value,
fileInfo,
(primaryPath, replicaIndex, replicaPath, replicaExists) =>
{
bool exists = FileSystem.FileExists(replicaPath);
bool evict = !exists || !onlyUnlinked || FileSystem.GetHardLinkCount(replicaPath) <= 1;
if (evict)
{
try
{
if (exists)
{
SafeForceDeleteFile(context, replicaPath);
}
evicted?.Invoke(fileInfo.FileSize);
_tracer.Diagnostic(
context,
$"Evicted content hash=[{contentHash}] replica=[{replicaIndex}] size=[{fileInfo.FileSize}]");
evictedFiles++;
evictedSize += fileInfo.FileSize;
evictions.Add(new ContentHashWithSize(contentHash, fileInfo.FileSize));
_tracer.TrackMetric(context, "ContentHashEvictedBytes", fileInfo.FileSize);
}
catch (Exception exception)
{
_tracer.Warning(
context,
$"Unable to purge {replicaPath.Path} because of exception: {exception}");
remainingReplicas.Add(replicaPath);
}
}
else
{
remainingReplicas.Add(replicaPath);
}
return Task.FromResult(ForEachReplicaCallbackResult.TryNextReplicaIfExists);
});
if (_announcer != null)
{
foreach (var e in evictions)
{
await _announcer.ContentEvicted(e);
}
}
if (remainingReplicas.Count > 0)
{
for (int i = 0; i < remainingReplicas.Count; i++)
{
AbsolutePath destinationPath = GetReplicaPathFor(contentHash, i);
if (remainingReplicas[i] != destinationPath)
{
_tracer.Debug(
context,
$"Renaming [{remainingReplicas[i]}] to [{destinationPath}] as part of cleanup.");
FileSystem.MoveFile(remainingReplicas[i], destinationPath, false);
}
}
fileInfo.ReplicaCount = remainingReplicas.Count;
return fileInfo;
}
else
{
// Notify Redis of eviction when Distributed Eviction is turned off
if (_distributedEvictionSettings == null)
{
_nagleQueue?.Enqueue(contentHash);
}
successfullyEvictedHash = true;
}
PinMap.TryRemove(contentHash, out pin);
return null;
});
return new EvictResult(evictedSize, evictedFiles, pinnedSize, contentHashInfo.LastAccessTime, successfullyEvictedHash, contentHashInfo.ReplicaCount);
});
}
}
/// <inheritdoc />
public Task<PlaceFileResult> PlaceFileAsync(
Context context,
ContentHash contentHash,
AbsolutePath destinationPath,
FileAccessMode accessMode,
FileReplacementMode replacementMode,
FileRealizationMode realizationMode,
PinRequest? pinRequest)
{
return PlaceFileCall<ContentStoreInternalTracer>.RunAsync(
_tracer,
OperationContext(context),
contentHash,
destinationPath,
accessMode,
replacementMode,
realizationMode,
async () => await PlaceFileInternalAsync(
context,
new ContentHashWithPath(contentHash, destinationPath),
accessMode,
replacementMode,
realizationMode,
pinRequest));
}
/// <inheritdoc />
public async Task<IEnumerable<Task<Indexed<PlaceFileResult>>>> PlaceFileAsync(
Context context,
IReadOnlyList<ContentHashWithPath> placeFileArgs,
FileAccessMode accessMode,
FileReplacementMode replacementMode,
FileRealizationMode realizationMode,
PinRequest? pinRequest = null)
{
var placeFileInternalBlock = new TransformBlock<Indexed<ContentHashWithPath>, Indexed<PlaceFileResult>>(
async p =>
(await PlaceFileAsync(context, p.Item.Hash, p.Item.Path, accessMode, replacementMode, realizationMode, pinRequest)).WithIndex(p.Index),
new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = ParallelPlaceFilesLimit, });
// TODO: Better way ? (bug 1365340)
placeFileInternalBlock.PostAll(placeFileArgs.AsIndexed());
var results = await Task.WhenAll(Enumerable.Range(0, placeFileArgs.Count).Select(i => placeFileInternalBlock.ReceiveAsync()));
placeFileInternalBlock.Complete();
return results.AsTasks();
}
private async Task<PlaceFileResult> PlaceFileInternalAsync(
Context context,
ContentHashWithPath contentHashWithPath,
FileAccessMode accessMode,
FileReplacementMode replacementMode,
FileRealizationMode realizationMode,
PinRequest? pinRequest)
{
try
{
var contentHash = contentHashWithPath.Hash;
var destinationPath = contentHashWithPath.Path;
// Check for file existing in the non-racing SkipIfExists case.
if ((replacementMode == FileReplacementMode.SkipIfExists || replacementMode == FileReplacementMode.FailIfExists) && FileSystem.FileExists(destinationPath))
{
return new PlaceFileResult(PlaceFileResult.ResultCode.NotPlacedAlreadyExists);
}
// If this is the empty hash, then put the empty file into the cache
if (_settings.UseEmptyFileHashShortcut && contentHashWithPath.Hash.IsEmptyHash() && !await ContainsAsync(context, contentHashWithPath.Hash, pinRequest))
{
// Put the empty file
var putResult = await PutStreamAsync(context, _emptyFileStream, contentHash, pinRequest);
if (!putResult.Succeeded)
{
// Because this is an optimization for the empty file, we shouldn't fail here.
// Instead, let the normal path have a try.
context.Debug($"Failed to place empty file by putting the empty stream: {putResult}");
}
}
// Lookup hash in content directory
using (LockSet<ContentHash>.LockHandle contentHashHandle = await _lockSet.AcquireAsync(contentHash))
{
if (pinRequest.HasValue)
{
PinContentIfContext(contentHash, pinRequest.Value.PinContext);
}
var code = PlaceFileResult.ResultCode.Unknown;
long contentSize = 0;
DateTime lastAccessTime = DateTime.MinValue;
await ContentDirectory.UpdateAsync(contentHash, true, Clock, async fileInfo =>
{
if (fileInfo == null)
{
code = PlaceFileResult.ResultCode.NotPlacedContentNotFound;
return null;
}
contentSize = fileInfo.FileSize;
lastAccessTime = DateTime.FromFileTimeUtc(fileInfo.LastAccessedFileTimeUtc);
if (ShouldAttemptHardLink(destinationPath, accessMode, realizationMode))
{
// ReSharper disable once AccessToDisposedClosure
CreateHardLinkResult hardLinkResult = await PlaceLinkFromCacheAsync(
context,
destinationPath,
replacementMode,
realizationMode,
contentHashHandle,
fileInfo);
if (hardLinkResult == CreateHardLinkResult.Success)
{
code = PlaceFileResult.ResultCode.PlacedWithHardLink;
}
else if (hardLinkResult == CreateHardLinkResult.FailedDestinationExists)
{
code = PlaceFileResult.ResultCode.NotPlacedAlreadyExists;
}
else if (hardLinkResult == CreateHardLinkResult.FailedSourceDoesNotExist)
{
await RemoveEntryIfNotOnDiskAsync(context, contentHash);
code = PlaceFileResult.ResultCode.NotPlacedContentNotFound;
return null;
}
}
return fileInfo;
});
if (code != PlaceFileResult.ResultCode.Unknown)
{
return new PlaceFileResult(code, contentSize);
}
// If hard linking failed or wasn't attempted, fall back to copy.
var stopwatch = Stopwatch.StartNew();
try
{
PlaceFileResult result;
if (realizationMode == FileRealizationMode.CopyNoVerify)
{
result = await CopyFileWithNoValidationAsync(
context, contentHash, destinationPath, accessMode, replacementMode);
}
else
{
result = await CopyFileAndValidateStreamAsync(
context, contentHash, destinationPath, accessMode, replacementMode);
}
result.FileSize = contentSize;
result.LastAccessTime = lastAccessTime;
return result;
}
finally
{
stopwatch.Stop();
_tracer.PlaceFileCopy(context, destinationPath, contentHash, stopwatch.Elapsed);
}
}
}
catch (Exception e)
{
return new PlaceFileResult(e);
}
}
private async Task<PlaceFileResult> CopyFileWithNoValidationAsync(
Context context,
ContentHash contentHash,
AbsolutePath destinationPath,
FileAccessMode accessMode,
FileReplacementMode replacementMode)
{
var code = PlaceFileResult.ResultCode.PlacedWithCopy;
AbsolutePath contentPath = await PinContentAndGetFullPathAsync(contentHash, null);
try
{
if (contentPath == null)
{
code = PlaceFileResult.ResultCode.NotPlacedContentNotFound;
}
else
{
try
{
var replaceExisting = replacementMode == FileReplacementMode.ReplaceExisting;
await FileSystem.CopyFileAsync(contentPath, destinationPath, replaceExisting);
}
catch (IOException e)
{
if ((uint)e.HResult == Hresult.FileExists || (e.InnerException != null &&
(uint)e.InnerException.HResult == Hresult.FileExists))
{
// File existing in the racing SkipIfExists case.
code = PlaceFileResult.ResultCode.NotPlacedAlreadyExists;
}
else
{
return new PlaceFileResult(e, $"Failed to place hash=[{contentHash}] to path=[{destinationPath}]");
}
}
ApplyPermissions(context, destinationPath, accessMode);
}
}
finally
{
if (PinMap.TryGetValue(contentHash, out var pin))
{
pin.Decrement();
}
}
return new PlaceFileResult(code);
}
private async Task<PlaceFileResult> CopyFileAndValidateStreamAsync(
Context context,
ContentHash contentHash,
AbsolutePath destinationPath,
FileAccessMode accessMode,
FileReplacementMode replacementMode)
{
var code = PlaceFileResult.ResultCode.Unknown;
var hasher = _hashers[contentHash.HashType];
ContentHash computedHash = new ContentHash(contentHash.HashType);
using (Stream contentStream =
await OpenStreamInternalWithLockAsync(context, contentHash, null, FileShare.Read | FileShare.Delete))
{
if (contentStream == null)
{
code = PlaceFileResult.ResultCode.NotPlacedContentNotFound;
}
else
{
using (var hashingStream = hasher.CreateReadHashingStream(contentStream))
{
try
{
FileSystem.CreateDirectory(destinationPath.Parent);
var fileMode = replacementMode == FileReplacementMode.ReplaceExisting ? FileMode.Create : FileMode.CreateNew;
using (Stream targetFileStream = await FileSystem.OpenSafeAsync(destinationPath, FileAccess.Write, fileMode, FileShare.Delete))
{
await hashingStream.CopyToWithFullBufferAsync(
targetFileStream, FileSystemConstants.FileIOBufferSize);
ApplyPermissions(context, destinationPath, accessMode);
}
computedHash = hashingStream.GetContentHash();
}
catch (IOException e)
{
if (e.InnerException != null && (long)e.InnerException.HResult == Hresult.FileExists)
{
// File existing in the racing SkipIfExists case.
code = PlaceFileResult.ResultCode.NotPlacedAlreadyExists;
}
else
{
return new PlaceFileResult(e, $"Failed to place hash=[{contentHash}] to path=[{destinationPath}]");
}
}
}
}
}
if (code == PlaceFileResult.ResultCode.Unknown)
{
if (computedHash != contentHash)
{
await RemoveCorruptedThenThrowAsync(context, contentHash, computedHash, destinationPath);
}
code = PlaceFileResult.ResultCode.PlacedWithCopy;
}
return new PlaceFileResult(code);
}
private async Task<CreateHardLinkResult> PlaceLinkFromCacheAsync(
Context context,
AbsolutePath destinationPath,
FileReplacementMode replacementMode,
FileRealizationMode realizationMode,
LockSet<ContentHash>.LockHandle contentHashHandle,
ContentFileInfo info)
{
FileSystem.CreateDirectory(destinationPath.Parent);
int defaultStartIndex = info.ReplicaCount - 1;
// If a cursor has been saved for this hash, try that one first
if (_replicaCursors.TryGetValue(contentHashHandle.Key, out var startIndex))
{
if (startIndex >= info.ReplicaCount || startIndex < 0)
{
// Remove an out-of-range cursor
_replicaCursors.TryRemove(contentHashHandle.Key, out startIndex);
startIndex = defaultStartIndex;
}
}
else
{
// If not, try the most recently created replica first
startIndex = defaultStartIndex;
}
CreateHardLinkResult result = await PlaceLinkFromReplicaAsync(
context,
destinationPath,
replacementMode,
realizationMode,
contentHashHandle,
info,
startIndex,
ReplicaExistence.Exists);
if (result != CreateHardLinkResult.FailedMaxHardLinkLimitReached)
{
return result;
}
// This replica is full
_replicaCursors.TryRemove(contentHashHandle.Key, out _);
if (info.ReplicaCount > 1)
{
// Try a random existing replica before making a new one.
var randomIndex = ThreadSafeRandom.Generator.Next(info.ReplicaCount - 1);
result = await PlaceLinkFromReplicaAsync(
context,
destinationPath,
replacementMode,
realizationMode,
contentHashHandle,
info,
randomIndex,
ReplicaExistence.Exists);
if (result != CreateHardLinkResult.FailedMaxHardLinkLimitReached)
{
// Save the cursor here as the most recent replica tried. No contention on the value due to the lock.
_replicaCursors.AddOrUpdate(contentHashHandle.Key, randomIndex, (hash, i) => randomIndex);
_tracer.Debug(
context,
$"Moving replica cursor to index {randomIndex} because callback stopped on replica {GetReplicaPathFor(contentHashHandle.Key, randomIndex).Path}.");
return result;
}
}
var newReplicaIndex = info.ReplicaCount;
return await PlaceLinkFromReplicaAsync(
context,
destinationPath,
replacementMode,
realizationMode,
contentHashHandle,
info,
newReplicaIndex,
ReplicaExistence.DoesNotExist);
}
private async Task<CreateHardLinkResult> PlaceLinkFromReplicaAsync(
Context context,
AbsolutePath destinationPath,
FileReplacementMode replacementMode,
FileRealizationMode realizationMode,
LockSet<ContentHash>.LockHandle contentHashHandle,
ContentFileInfo info,
int replicaIndex,
ReplicaExistence replicaExistence)
{
var primaryPath = GetPrimaryPathFor(contentHashHandle.Key);
var replicaPath = GetReplicaPathFor(contentHashHandle.Key, replicaIndex);
if (replicaExistence == ReplicaExistence.DoesNotExist)
{
// Create a new replica
using (var txn = await _quotaKeeper.ReserveAsync(info.FileSize))
{
await RetryOnUnexpectedReplicaAsync(
context,
() => SafeCopyFileAsync(
context,
contentHashHandle.Key,
primaryPath,
replicaPath,
FileReplacementMode.FailIfExists),
contentHashHandle.Key,
info.ReplicaCount);
txn.Commit();
}
if (_announcer != null)
{
await _announcer.ContentAdded(new ContentHashWithSize(contentHashHandle.Key, info.FileSize));
}
info.ReplicaCount++;
}
if (!TryCreateHardlink(
context,
replicaPath,
destinationPath,
realizationMode,
replacementMode == FileReplacementMode.ReplaceExisting,
out CreateHardLinkResult hardLinkResult))
{
if (hardLinkResult == CreateHardLinkResult.FailedSourceDoesNotExist &&
primaryPath != replicaPath &&
FileSystem.FileExists(primaryPath))
{
_tracer.Warning(
context,
$"Missing replica for hash=[{contentHashHandle.Key}]. Recreating replica=[{replicaPath}] from primary replica.");
Interlocked.Increment(ref _contentDirectoryMismatchCount);
await SafeCopyFileAsync(
context,
contentHashHandle.Key,
primaryPath,
replicaPath,
FileReplacementMode.FailIfExists);
TryCreateHardlink(
context,
replicaPath,
destinationPath,
realizationMode,
replacementMode == FileReplacementMode.ReplaceExisting,
out hardLinkResult);
}
}
return hardLinkResult;
}
private async Task SafeCopyFileAsync(
Context context,
ContentHash contentHash,
AbsolutePath sourcePath,
AbsolutePath destinationPath,
FileReplacementMode replacementMode)
{
AbsolutePath tempPath = GetTemporaryFileName(contentHash);
await FileSystem.CopyFileAsync(sourcePath, tempPath, false);
ApplyPermissions(context, tempPath, FileAccessMode.ReadOnly);
FileSystem.MoveFile(tempPath, destinationPath, replacementMode == FileReplacementMode.ReplaceExisting);
}
private async Task RetryOnUnexpectedReplicaAsync(
Context context, Func<Task> tryFunc, ContentHash contentHash, int expectedReplicaCount)
{
try
{
await tryFunc();
}
catch (IOException)
{
RemoveExtraReplicasFromDiskFor(context, contentHash, expectedReplicaCount);
await tryFunc();
}
}
/// <summary>
/// Removes the corresponding entry from the content directory if the content for a hash doesn't exist on disk.
/// </summary>
/// <param name="context">Tracing context</param>
/// <param name="contentHash">The hash whose content and content directory entry are in question.</param>
/// <returns>Whether a bad entry was removed.</returns>
private async Task<bool> RemoveEntryIfNotOnDiskAsync(Context context, ContentHash contentHash)
{
var primaryPath = GetPrimaryPathFor(contentHash);
if (!FileSystem.FileExists(primaryPath) && (await ContentDirectory.RemoveAsync(contentHash) != null))
{
_tracer.Warning(
context,
$"Removed content directory entry for hash {contentHash} because the cache does not have content at {primaryPath}.");
Interlocked.Increment(ref _contentDirectoryMismatchCount);
return true;
}
return false;
}
private void RemoveAllReplicasFromDiskFor(Context context, ContentHash contentHash)
{
RemoveExtraReplicasFromDiskFor(context, contentHash, 0);
}
/// <summary>
/// Removes all replicas for the given hash beyond the expected number from disk.
/// </summary>
/// <param name="context">Tracing context</param>
/// <param name="contentHash">The hash whose replicas are to be limited.</param>
/// <param name="expectedReplicaCount">The number of replicas to which the hash's replicas are to be limited.</param>
private void RemoveExtraReplicasFromDiskFor(Context context, ContentHash contentHash, int expectedReplicaCount)
{
AbsolutePath[] extraReplicaPaths =
EnumerateBlobPathsFromDiskFor(contentHash)
.Select(blobPath => blobPath.FullPath)
.Where(replicaPath => GetReplicaIndexFromPath(replicaPath) >= expectedReplicaCount).ToArray();
if (extraReplicaPaths.Any())
{
_tracer.Warning(context, $"Unexpected cache blob for hash=[{contentHash}]. Removing extra blob(s).");
Interlocked.Increment(ref _contentDirectoryMismatchCount);
}
foreach (AbsolutePath extraReplicaPath in extraReplicaPaths)
{
_tracer.Debug(context, $"Deleting extra blob {extraReplicaPath.Path}.");
SafeForceDeleteFile(context, extraReplicaPath);
}
}
private async Task RemoveCorruptedThenThrowAsync(Context context, ContentHash contentHash, ContentHash computedHash, AbsolutePath destinationPath)
{
AbsolutePath[] replicaPaths = EnumerateBlobPathsFromDiskFor(contentHash).Select(blobPath => blobPath.FullPath).ToArray();
foreach (AbsolutePath replicaPath in replicaPaths)
{
_tracer.Debug(context, $"Deleting corrupted blob {replicaPath.Path}.");
SafeForceDeleteFile(context, replicaPath);
}
_tracer.Debug(context, $"Removing content directory entry for corrupted hash {contentHash}.");
await ContentDirectory.RemoveAsync(contentHash);
throw new ContentHashMismatchException(destinationPath, computedHash, contentHash);
}
/// <summary>
/// Delete the file or, if unable, move it to a temp location and force delete it.
/// </summary>
/// <remarks>
/// Use this to safely delete blobs from their canonical locations without leaving unprotected files around.
/// </remarks>
private void SafeForceDeleteFile(Context context, AbsolutePath path)
{
try
{
DeleteReadOnlyFile(path);
}
catch (Exception exception) when (exception is IOException || exception is BuildXLException || exception is UnauthorizedAccessException)
{
AbsolutePath tempPath = GetTemporaryFileName();
_tracer.Debug(
context,
$"Unable to delete {path.Path} exception=[{exception}]. Moving to temp path=[{tempPath}] instead and attempting to delete more thoroughly.");
FileSystem.MoveFile(path, tempPath, replaceExisting: false);
TryForceDeleteFile(context, tempPath);
}
}
private async Task PinContextDisposeAsync(IEnumerable<KeyValuePair<ContentHash, int>> pinCounts)
{
long pinnedSize = 0;
foreach (var pinCount in pinCounts)
{
using (await _lockSet.AcquireAsync(pinCount.Key))
{
if (PinMap.TryGetValue(pinCount.Key, out Pin pin))
{
pin.Add(-1 * pinCount.Value);
if (pin.Count == 0)
{
PinMap.TryRemoveSpecific(pinCount.Key, pin);
}
}
if (TryGetContentTotalSize(pinCount.Key, out var size))
{
pinnedSize += size;
}
}
}
_quotaKeeper.Calibrate();
lock (_pinSizeHistory)
{
_maxPinSize = Math.Max(pinnedSize, _maxPinSize);
if (Interlocked.Decrement(ref _pinContextCount) == 0)
{
_pinSizeHistory.Add(_maxPinSize);
_maxPinSize = -1;
}
}
}
/// <summary>
/// Increment the info's pin count and add the hash to the given context.
/// </summary>
/// <param name="hash">Hash to pin.</param>
/// <param name="pinContext">Context to pin the hash to.</param>
private void PinContentIfContext(ContentHash hash, PinContext pinContext)
{
if (pinContext != null)
{
IncrementPin(hash);
pinContext.AddPin(hash);
}
}
private void IncrementPin(ContentHash hash)
{
PinMap.GetOrAdd(hash, new Pin()).Increment();
}
/// <summary>
/// Provides a PinContext for this cache which can be used in conjunction with other APIs to pin relevant content in
/// the cache.
/// The content may be unpinned by disposing of the PinContext.
/// </summary>
/// <returns>The created PinContext.</returns>
public PinContext CreatePinContext()
{
Interlocked.Increment(ref _pinContextCount);
// ReSharper disable once RedundantArgumentName
return new PinContext(_taskTracker, unpinAsync: pairs => PinContextDisposeAsync(pairs));
}
/// <summary>
/// Pin existing content.
/// </summary>
public Task<PinResult> PinAsync(Context context, ContentHash contentHash, PinContext pinContext)
{
return PinCall<ContentStoreInternalTracer>.RunAsync(_tracer, OperationContext(context), contentHash, async () =>
{
var bulkResults = await PinAsync(context, new[] { contentHash }, pinContext);
return bulkResults.Single().Item;
});
}
/// <inheritdoc />
public async Task<IEnumerable<Indexed<PinResult>>> PinAsync(Context context, IReadOnlyList<ContentHash> contentHashes, PinContext pinContext)
{
var stopwatch = Stopwatch.StartNew();
var (results, error) = await PinCoreAsync(context, contentHashes, pinContext);
_tracer.PinBulkStop(context, stopwatch.Elapsed, contentHashes: contentHashes, results: results, error);
return results;
}
private async Task<(IEnumerable<Indexed<PinResult>> results, Exception error)> PinCoreAsync(Context context, IReadOnlyList<ContentHash> contentHashes, PinContext pinContext)
{
var results = new List<PinResult>(contentHashes.Count);
try
{
_tracer.PinBulkStart(context, contentHashes);
var pinRequest = new PinRequest(pinContext);
// TODO: This is still relatively inefficient. We're taking a lock per hash and pinning each individually. (bug 1365340)
// The batching needs to go further down.
foreach (var contentHash in contentHashes)
{
if (_settings.UseEmptyFileHashShortcut && contentHash.IsEmptyHash())
{
results.Add(new PinResult(contentSize: 0, lastAccessTime: Clock.UtcNow, code: PinResult.ResultCode.Success));
}
else
{
ContentFileInfo contentInfo = await GetContentSizeAndLastAccessTimeAsync(context, contentHash, pinRequest);
results.Add(contentInfo != null ? new PinResult(contentInfo.FileSize, DateTime.FromFileTimeUtc(contentInfo.LastAccessedFileTimeUtc)) : PinResult.ContentNotFound);
}
}
return (results: results.AsIndexed(), error: null);
}
catch (Exception exception)
{
return (results: contentHashes.Select(x => PinResult.ContentNotFound).AsIndexed(), error: exception);
}
}
/// <inheritdoc />
public async Task<bool> ContainsAsync(Context context, ContentHash contentHash, PinRequest? pinRequest)
{
PinContext pinContext = pinRequest?.PinContext;
using (await _lockSet.AcquireAsync(contentHash))
{
bool found = false;
await ContentDirectory.UpdateAsync(contentHash, touch: true, clock: Clock, updateFileInfo: async fileInfo =>
{
// If _checkFiles is true, make an additional check whether the file is actually on the disk.
// Otherwise, we will just trust our in-memory record.
if (fileInfo != null && !(_settings.CheckFiles && await RemoveEntryIfNotOnDiskAsync(context, contentHash)))
{
found = true;
PinContentIfContext(contentHash, pinContext);
}
return null;
});
return found;
}
}
private void CheckPinned(ContentHash contentHash, PinRequest? pinRequest)
{
if (pinRequest?.VerifyAlreadyPinned == true)
{
IsPinned(contentHash, pinRequest);
}
}
/// <summary>
/// Checks if whether content is locally pinned.
/// </summary>
public bool IsPinned(ContentHash contentHash, PinRequest? pinRequest = null)
{
var verifyAlreadyPinned = false;
PinContext verifyPinContext = null;
if (pinRequest.HasValue)
{
verifyAlreadyPinned = pinRequest.Value.VerifyAlreadyPinned;
verifyPinContext = pinRequest.Value.VerifyPinContext;
}
bool pinned = PinMap.TryGetValue(contentHash, out var pin) && pin.Count > 0;
if (verifyAlreadyPinned)
{
if (!pinned)
{
throw new CacheException("Expected content with hash {0} to be pinned, but it was not.", contentHash);
}
if (verifyPinContext != null && !verifyPinContext.Contains(contentHash))
{
throw new CacheException(
"Expected content with hash {0} was pinned, but not to the expected pin context.", contentHash);
}
}
return pinned;
}
/// <inheritdoc />
public async Task<GetContentSizeResult> GetContentSizeAndCheckPinnedAsync(Context context, ContentHash contentHash, PinRequest? pinRequest)
{
using (await _lockSet.AcquireAsync(contentHash))
{
var contentWasPinned = IsPinned(contentHash, pinRequest);
PinContext pinContext = pinRequest?.PinContext;
long contentSize = await GetContentSizeInternalAsync(context, contentHash, pinContext);
return new GetContentSizeResult(contentSize, contentWasPinned);
}
}
private async Task<ContentFileInfo> GetContentSizeAndLastAccessTimeAsync(Context context, ContentHash contentHash, PinRequest? pinRequest)
{
using (await _lockSet.AcquireAsync(contentHash))
{
PinContext pinContext = pinRequest?.PinContext;
return await GetContentSizeAndLastAccessTimeInternalAsync(context, contentHash, pinContext);
}
}
/// <summary>
/// Gets total pinned size. Returns -1 if unpinned.
/// </summary>
private long GetPinnedSize(Context context, ContentHash contentHash)
{
long pinnedSize = -1;
if (IsPinned(contentHash))
{
TryGetContentTotalSize(contentHash, out pinnedSize);
}
return pinnedSize;
}
private async Task<long> GetContentSizeInternalAsync(Context context, ContentHash contentHash, PinContext pinContext = null)
{
var info = await GetContentSizeAndLastAccessTimeInternalAsync(context, contentHash, pinContext);
return info?.FileSize ?? -1;
}
private async Task<ContentFileInfo> GetContentSizeAndLastAccessTimeInternalAsync(Context context, ContentHash contentHash, PinContext pinContext = null)
{
ContentFileInfo info = null;
await ContentDirectory.UpdateAsync(contentHash, touch: true, clock: Clock, updateFileInfo: async contentFileInfo =>
{
if (contentFileInfo != null && !await RemoveEntryIfNotOnDiskAsync(context, contentHash))
{
info = contentFileInfo;
PinContentIfContext(contentHash, pinContext);
}
return null;
});
return info;
}
/// <inheritdoc />
public Task<OpenStreamResult> OpenStreamAsync(Context context, ContentHash contentHash, PinRequest? pinRequest)
{
return OpenStreamCall<ContentStoreInternalTracer>.RunAsync(_tracer, OperationContext(context), contentHash, async () =>
{
using (await _lockSet.AcquireAsync(contentHash))
{
if (_settings.UseEmptyFileHashShortcut && contentHash.IsEmptyHash())
{
return new OpenStreamResult(_emptyFileStream);
}
var stream = await OpenStreamInternalWithLockAsync(context, contentHash, pinRequest, FileShare.Read | FileShare.Delete);
return new OpenStreamResult(stream);
}
});
}
private async Task<Stream> OpenStreamInternalWithLockAsync(Context context, ContentHash contentHash, PinRequest? pinRequest, FileShare share)
{
AbsolutePath contentPath = await PinContentAndGetFullPathAsync(contentHash, pinRequest);
if (contentPath == null)
{
return null;
}
var contentStream = await FileSystem.OpenAsync(contentPath, FileAccess.Read, FileMode.Open, share);
if (contentStream == null)
{
await RemoveEntryIfNotOnDiskAsync(context, contentHash);
return null;
}
return contentStream;
}
/// <summary>
/// OpenStream helper method.
/// </summary>
private async Task<AbsolutePath> PinContentAndGetFullPathAsync(ContentHash contentHash, PinRequest? pinRequest)
{
CheckPinned(contentHash, pinRequest);
var found = false;
await ContentDirectory.UpdateAsync(contentHash, true, Clock, fileInfo =>
{
if (fileInfo != null)
{
found = true;
PinContentIfContext(contentHash, pinRequest?.PinContext);
}
return null;
});
if (!found)
{
return null;
}
return GetPrimaryPathFor(contentHash);
}
/// <summary>
/// Gets whether the store contains the given content
/// </summary>
public bool Contains(ContentHash hash)
{
return ContentDirectory.TryGetFileInfo(hash, out _);
}
/// <summary>
/// Gives the maximum path to files stored under the cache root.
/// </summary>
/// <returns>Max length</returns>
public static int GetMaxContentPathLengthRelativeToCacheRoot()
{
var maxHashNameLength = HashInfoLookup.All().Max(v => v.Name.Length);
var maxHashStringLength = HashInfoLookup.All().Max(v => v.StringLength);
int maxContentPathLengthRelativeToCacheRoot =
Constants.SharedDirectoryName.Length +
1 + // path separator
maxHashNameLength +
1 + // path separator
HashDirectoryNameLength + // hash directory
1 + // path separator
maxHashStringLength + // filename base, 2 characters per byte in hex string
1 + // dot preceding filename extension
BlobNameExtensionLength; // filename extension
return maxContentPathLengthRelativeToCacheRoot;
}
/// <inheritdoc />
public Task<PutResult> PutFileAsync(Context context, AbsolutePath path, HashType hashType, FileRealizationMode realizationMode, Func<Stream, Stream> wrapStream, PinRequest? pinRequest)
{
return PutFileImplAsync(context, path, realizationMode, hashType, pinRequest, trustedHashWithSize: null, wrapStream);
}
/// <inheritdoc />
public Task<PutResult> PutFileAsync(Context context, AbsolutePath path, ContentHash contentHash, FileRealizationMode realizationMode, Func<Stream, Stream> wrapStream, PinRequest? pinRequest)
{
return PutFileImplAsync(context, path, realizationMode, contentHash, pinRequest, wrapStream);
}
}
}
| 44.165195 | 210 | 0.52135 | [
"MIT"
] | kittinap/kunnjae | Public/Src/Cache/ContentStore/Library/Stores/FileSystemContentStoreInternal.cs | 135,013 | C# |
// Accord Statistics Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Statistics.Models.Markov.Hybrid
{
using System;
/// <summary>
/// Common interface for Hybrid Hidden Markov Models.
/// </summary>
///
public interface IHybridMarkovModel
{
/// <summary>
/// Calculates the most likely sequence of hidden states
/// that produced the given observation sequence.
/// </summary>
/// <remarks>
/// Decoding problem. Given the HMM M = (A, B, pi) and the observation sequence
/// O = {o1,o2, ..., oK}, calculate the most likely sequence of hidden states Si
/// that produced this observation sequence O. This can be computed efficiently
/// using the Viterbi algorithm.
/// </remarks>
/// <param name="observations">
/// A sequence of observations.</param>
/// <param name="logLikelihood">
/// The state optimized probability.</param>
/// <returns>
/// The sequence of states that most likely produced the sequence.
/// </returns>
///
int[] Decode(double[][] observations, out double logLikelihood);
/// <summary>
/// Calculates the probability that this model has generated the given sequence.
/// </summary>
/// <remarks>
/// Evaluation problem. Given the HMM M = (A, B, pi) and the observation
/// sequence O = {o1, o2, ..., oK}, calculate the probability that model
/// M has generated sequence O. This can be computed efficiently using the
/// Forward algorithm. </remarks>
/// <param name="observations">
/// A sequence of observations. </param>
/// <returns>
/// The probability that the given sequence has been generated by this model.
/// </returns>
///
double Evaluate(double[][] observations);
/// <summary>
/// Gets the expected number of dimensions in each observation.
/// </summary>
///
int Dimension { get; }
/// <summary>
/// Gets the number of states of this model.
/// </summary>
///
int States { get; }
/// <summary>
/// Gets or sets a user-defined tag.
/// </summary>
///
object Tag { get; set; }
}
}
| 36.065934 | 91 | 0.595064 | [
"MIT"
] | mastercs999/fn-trading | src/Accord/Accord.Statistics/Models/Markov/Hybrid/IHybridMarkovModel.cs | 3,286 | C# |
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SMECommerce.Databases.DbContexts;
namespace EFcoreExamples.Migrations
{
[DbContext(typeof(SMECommerceDbContext))]
[Migration("20211106065621_Category_Name_LengthChangedto250FromMax")]
partial class Category_Name_LengthChangedto250FromMax
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.11")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("EFcoreExamples.Models.EntityModels.Category", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.HasMaxLength(250)
.HasColumnType("nvarchar(250)");
b.HasKey("Id");
b.ToTable("Categories");
});
#pragma warning restore 612, 618
}
}
}
| 37.785714 | 125 | 0.645873 | [
"MIT"
] | MoksedurRahman/Dot_Net_Core_Token_Base_Summary_ | SMECommerc.Databases/Migrations/20211106065621_Category_Name_LengthChangedto250FromMax.Designer.cs | 1,589 | C# |
using System;
using System.Collections.Generic;
using Android.Runtime;
using Java.Interop;
namespace FrostWire.Libtorrent {
// Metadata.xml XPath class reference: path="/api/package[@name='com.frostwire.jlibtorrent']/class[@name='IntSeries']"
[global::Android.Runtime.Register ("com/frostwire/jlibtorrent/IntSeries", DoNotGenerateAcw=true)]
public sealed partial class IntSeries : global::Java.Lang.Object {
internal new static readonly JniPeerMembers _members = new XAPeerMembers ("com/frostwire/jlibtorrent/IntSeries", typeof (IntSeries));
internal static new IntPtr class_ref {
get {
return _members.JniPeerType.PeerReference.Handle;
}
}
public override global::Java.Interop.JniPeerMembers JniPeerMembers {
get { return _members; }
}
protected override IntPtr ThresholdClass {
get { return _members.JniPeerType.PeerReference.Handle; }
}
protected override global::System.Type ThresholdType {
get { return _members.ManagedPeerType; }
}
internal IntSeries (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
// Metadata.xml XPath method reference: path="/api/package[@name='com.frostwire.jlibtorrent']/class[@name='IntSeries']/method[@name='get' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("get", "(I)J", "")]
public unsafe long Get (int index)
{
const string __id = "get.(I)J";
try {
JniArgumentValue* __args = stackalloc JniArgumentValue [1];
__args [0] = new JniArgumentValue (index);
var __rm = _members.InstanceMethods.InvokeAbstractInt64Method (__id, this, __args);
return __rm;
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.frostwire.jlibtorrent']/class[@name='IntSeries']/method[@name='last' and count(parameter)=0]"
[Register ("last", "()J", "")]
public unsafe long Last ()
{
const string __id = "last.()J";
try {
var __rm = _members.InstanceMethods.InvokeAbstractInt64Method (__id, this, null);
return __rm;
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='com.frostwire.jlibtorrent']/class[@name='IntSeries']/method[@name='size' and count(parameter)=0]"
[Register ("size", "()I", "")]
public unsafe int Size ()
{
const string __id = "size.()I";
try {
var __rm = _members.InstanceMethods.InvokeAbstractInt32Method (__id, this, null);
return __rm;
} finally {
}
}
}
}
| 33.917808 | 194 | 0.699515 | [
"Apache-2.0"
] | PascalBenstrong/TorrentStream | obj/Debug/generated/src/FrostWire.Libtorrent.IntSeries.cs | 2,476 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace EID.Wrapper
{
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
[Guid("ee8f42af-4b88-4b3c-8bf8-fc1ed64807e1")]
[ComVisible(true)]
public interface ICard
{
CardStatus CardStatus { get; }
Exception Error { get; }
/// <summary>
/// An array containing a list of warnings that occurred when reading data from the card. If an error occurs during the parsing of data, the field will be set to
/// string.empty and a warning will be set
/// </summary>
string[] Warnings { get; }
/// <summary>
/// Returns the name of the card slot the data represents
/// </summary>
string CardSlot { get; }
string BirthDate { get; }
string BirthPlace { get; }
string FirstNames { get; }
string Gender { get; }
string Municipality { get; }
string Nationality { get; }
string NationalNumber { get; }
string StreetAndNumber { get; }
string Surname { get; }
string ZipCode { get; }
string MemberOfFamily { get; }
string SpecialOrganization { get; }
string Duplicata { get; }
string SpecialStatus { get; }
string DocumentType { get; }
string IssuingMunicipality { get; }
string ValidityEndDate { get; }
string ValidityBeginDate { get; }
/// <summary>
/// Chip Number is not in a 'readable' format as it is just an array of 16 bytes. This displays the value base64-encoded
/// </summary>
string ChipNumber { get; }
string CardNumber { get; }
/// <summary>
/// The raw byte array of photo data on the card (jpg-image)
/// </summary>
byte[] PhotoData { get; }
/// <summary>
/// Saves the photo data to a file
/// </summary>
/// <param name="fileName">Full path of the file to save to</param>
void SavePhoto(string fileName);
}
}
| 33.428571 | 169 | 0.592593 | [
"MIT"
] | jdt/EID.Wrapper | Source/EID.Wrapper/ICard.cs | 2,108 | C# |
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TTT_UWP.Model;
using TTT_UWP.Services;
using TTT_UWP.Tests.Mocks;
using TTT_UWP.ViewModels;
namespace TTT_UWP.Tests.Viewmodels
{
public class HumidityPageViewModelTests
{
private INavigationService navigationService;
private IObservationDataService observationDataService;
[TestInitialize]
public void Init()
{
navigationService = new MockNavigationService();
observationDataService = new MockObservationDataService(new MockObservationRepository());
}
[TestMethod]
public void LoadObservations()
{
//Arrange
ObservableCollection<Observation> observations = null;
var expectedObservations = observationDataService.GetObservations();
//Act
var viewModel = new HumidityPageViewModel(this.navigationService);
observations = viewModel.Observations;
//Assert
CollectionAssert.AreEqual(expectedObservations, observations);
}
}
}
| 29.325581 | 101 | 0.697066 | [
"MIT"
] | pxlit-projects/entmob2016_5 | TTT_UWP/TTT_UWP.Tests/Tests/Viewmodels/HumidityPageViewModelTests.cs | 1,263 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Vpc.V20170312.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DetachNetworkInterfaceRequest : AbstractModel
{
/// <summary>
/// The ID of the ENI instance, such as `eni-m6dyj72l`.
/// </summary>
[JsonProperty("NetworkInterfaceId")]
public string NetworkInterfaceId{ get; set; }
/// <summary>
/// The ID of the CVM instance, such as `ins-r8hr2upy`.
/// </summary>
[JsonProperty("InstanceId")]
public string InstanceId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "NetworkInterfaceId", this.NetworkInterfaceId);
this.SetParamSimple(map, prefix + "InstanceId", this.InstanceId);
}
}
}
| 32.411765 | 93 | 0.653358 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet-intl-en | TencentCloud/Vpc/V20170312/Models/DetachNetworkInterfaceRequest.cs | 1,653 | C# |
using System.ServiceModel;
namespace FilterServiceContract
{
public interface IFilterServiceCallback
{
[OperationContract(IsOneWay = true)]
void ProgressCallback(int progress);
[OperationContract(IsOneWay = true)]
void ImageCallback(byte[] img);
}
}
| 20.8 | 45 | 0.650641 | [
"MIT"
] | kirill-ivanov-a/programming-practice | Third term/FiltersService/FilterServiceContract/IFilterServiceCallback.cs | 314 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Skender.Stock.Indicators
{
public static partial class Indicator
{
// SUPERTREND
/// <include file='./info.xml' path='indicator/*' />
///
public static IEnumerable<SuperTrendResult> GetSuperTrend<TQuote>(
this IEnumerable<TQuote> quotes,
int lookbackPeriods = 10,
double multiplier = 3)
where TQuote : IQuote
{
// convert quotes
List<QuoteD> quotesList = quotes.ConvertToList();
// check parameter arguments
ValidateSuperTrend(quotes, lookbackPeriods, multiplier);
// initialize
List<SuperTrendResult> results = new(quotesList.Count);
List<AtrResult> atrResults = GetAtr(quotes, lookbackPeriods).ToList();
bool isBullish = true;
double? upperBand = null;
double? lowerBand = null;
// roll through quotes
for (int i = 0; i < quotesList.Count; i++)
{
QuoteD q = quotesList[i];
SuperTrendResult r = new()
{
Date = q.Date
};
if (i >= lookbackPeriods - 1)
{
double mid = (q.High + q.Low) / 2;
double atr = (double)atrResults[i].Atr;
double prevClose = quotesList[i - 1].Close;
// potential bands
double upperEval = mid + multiplier * atr;
double lowerEval = mid - multiplier * atr;
// initial values
if (i == lookbackPeriods - 1)
{
isBullish = (q.Close >= mid);
upperBand = upperEval;
lowerBand = lowerEval;
}
// new upper band
if (upperEval < upperBand || prevClose > upperBand)
{
upperBand = upperEval;
}
// new lower band
if (lowerEval > lowerBand || prevClose < lowerBand)
{
lowerBand = lowerEval;
}
// supertrend
if (q.Close <= ((isBullish) ? lowerBand : upperBand))
{
r.SuperTrend = (decimal?)upperBand;
r.UpperBand = (decimal?)upperBand;
isBullish = false;
}
else
{
r.SuperTrend = (decimal?)lowerBand;
r.LowerBand = (decimal?)lowerBand;
isBullish = true;
}
}
results.Add(r);
}
return results;
}
// remove recommended periods
/// <include file='../../_common/Results/info.xml' path='info/type[@name="Prune"]/*' />
///
public static IEnumerable<SuperTrendResult> RemoveWarmupPeriods(
this IEnumerable<SuperTrendResult> results)
{
int removePeriods = results
.ToList()
.FindIndex(x => x.SuperTrend != null);
return results.Remove(removePeriods);
}
// parameter validation
private static void ValidateSuperTrend<TQuote>(
IEnumerable<TQuote> quotes,
int lookbackPeriods,
double multiplier)
where TQuote : IQuote
{
// check parameter arguments
if (lookbackPeriods <= 1)
{
throw new ArgumentOutOfRangeException(nameof(lookbackPeriods), lookbackPeriods,
"Lookback periods must be greater than 1 for SuperTrend.");
}
if (multiplier <= 0)
{
throw new ArgumentOutOfRangeException(nameof(multiplier), multiplier,
"Multiplier must be greater than 0 for SuperTrend.");
}
// check quotes
int qtyHistory = quotes.Count();
int minHistory = lookbackPeriods + 100;
if (qtyHistory < minHistory)
{
string message = "Insufficient quotes provided for SuperTrend. " +
string.Format(EnglishCulture,
"You provided {0} periods of quotes when at least {1} are required. "
+ "Since this uses a smoothing technique, "
+ "we recommend you use at least N+250 data points prior to the intended "
+ "usage date for better precision.", qtyHistory, minHistory);
throw new BadQuotesException(nameof(quotes), message);
}
}
}
}
| 33.241611 | 95 | 0.473047 | [
"Apache-2.0"
] | myalgomate/Stock.Indicators | src/s-z/SuperTrend/SuperTrend.cs | 4,953 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// </auto-generated>
namespace Microsoft.Azure.Management.Network.Fluent
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// AvailableDelegationsOperations operations.
/// </summary>
public partial interface IAvailableDelegationsOperations
{
/// <summary>
/// Gets all of the available subnet delegations for this subscription
/// in this region.
/// </summary>
/// <param name='location'>
/// The location of the subnet.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AvailableDelegationInner>>> ListWithHttpMessagesAsync(string location, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all of the available subnet delegations for this subscription
/// in this region.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AvailableDelegationInner>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 42.541667 | 242 | 0.648057 | [
"MIT"
] | Azure/azure-libraries-for-net | src/ResourceManagement/Network/Generated/IAvailableDelegationsOperations.cs | 3,063 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
namespace RX_Explorer.Class
{
public sealed class OperationListDeleteUndoModel : OperationListUndoModel
{
public override string FromDescription
{
get
{
return string.Empty;
}
}
public override string ToDescription
{
get
{
if (UndoFrom.Length > 5)
{
return $"{Globalization.GetString("TaskList_To_Label")}: {Environment.NewLine}{string.Join(Environment.NewLine, UndoFrom.Take(5))}{Environment.NewLine}({UndoFrom.Length - 5} {Globalization.GetString("TaskList_More_Items")})...";
}
else
{
return $"{Globalization.GetString("TaskList_To_Label")}: {Environment.NewLine}{string.Join(Environment.NewLine, UndoFrom)}";
}
}
}
public string[] UndoFrom { get; }
public override async Task PrepareSizeDataAsync()
{
ulong TotalSize = 0;
foreach (FileSystemStorageItemBase Item in await FileSystemStorageItemBase.OpenInBatchAsync(UndoFrom))
{
switch (Item)
{
case FileSystemStorageFolder Folder:
{
TotalSize += await Folder.GetFolderSizeAsync();
break;
}
case FileSystemStorageFile File:
{
TotalSize += File.Size;
break;
}
}
}
Calculator = new ProgressCalculator(TotalSize);
}
public OperationListDeleteUndoModel(string[] UndoFrom, EventHandler OnCompleted = null, EventHandler OnErrorHappended = null, EventHandler OnCancelled = null) : base(OnCompleted, OnErrorHappended, OnCancelled)
{
if (UndoFrom.Any((Path) => string.IsNullOrWhiteSpace(Path)))
{
throw new ArgumentNullException(nameof(UndoFrom), "Parameter could not be empty or null");
}
this.UndoFrom = UndoFrom;
}
}
}
| 33.289855 | 248 | 0.520679 | [
"Apache-2.0"
] | silentmoooon/RX-Explorer | RX_Explorer/Class/OperationListDeleteUndoModel.cs | 2,299 | C# |
using System.Collections.Generic;
using Xunit;
namespace MSJennings.CodeGeneration.Tests
{
public class ReflectionExtensionsTests
{
[Fact]
public void ToModelPropertyType_WithBool_ShouldReturnExpectedResult()
{
// Arrange
var testValue = true;
var testValueType = testValue.GetType();
// Act
var modelPropertyType = testValueType.ToModelPropertyType();
// Assert
Assert.Equal(ModelPropertyLogicalType.Boolean, modelPropertyType.LogicalType);
Assert.Null(modelPropertyType.ObjectTypeName);
Assert.Null(modelPropertyType.ListItemType);
}
[Fact]
public void ToModelPropertyType_WithListOfStrings_ShouldReturnExpectedResult()
{
// Arrange
var testValue = new List<string> { "One", "Two", "Three" };
var testValueType = testValue.GetType();
// Act
var modelPropertyType = testValueType.ToModelPropertyType();
// Assert
Assert.Equal(ModelPropertyLogicalType.List, modelPropertyType.LogicalType);
Assert.Null(modelPropertyType.ObjectTypeName);
Assert.Equal(ModelPropertyLogicalType.String, modelPropertyType.ListItemType.LogicalType);
}
[Fact]
public void ToModelPropertyType_WithArrayOfInts_ShouldReturnExpectedResult()
{
// Arrange
var testValue = new int[] { 1, 2, 3 };
var testValueType = testValue.GetType();
// Act
var modelPropertyType = testValueType.ToModelPropertyType();
// Assert
Assert.Equal(ModelPropertyLogicalType.List, modelPropertyType.LogicalType);
Assert.Null(modelPropertyType.ObjectTypeName);
Assert.Equal(ModelPropertyLogicalType.Integer, modelPropertyType.ListItemType.LogicalType);
}
[Fact]
public void ToModelPropertyType_WithDictionary_ShouldReturnExpectedResult()
{
// Arrange
var testValue = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"},
{3, "Three"},
};
var testValueType = testValue.GetType();
// Act
var modelPropertyType = testValueType.ToModelPropertyType();
// Assert
Assert.Equal(ModelPropertyLogicalType.List, modelPropertyType.LogicalType);
Assert.Null(modelPropertyType.ObjectTypeName);
Assert.Equal(ModelPropertyLogicalType.KeyValuePair, modelPropertyType.ListItemType.LogicalType);
}
[Fact]
public void ToModelPropertyType_WithObject_ShouldReturnExpectedResult()
{
// Arrange
var testValue = new CodeGenerationModel();
var testValueType = testValue.GetType();
// Act
var modelPropertyType = testValueType.ToModelPropertyType();
// Assert
Assert.Equal(ModelPropertyLogicalType.Object, modelPropertyType.LogicalType);
Assert.Equal(testValueType.Name, modelPropertyType.ObjectTypeName);
Assert.Null(modelPropertyType.ListItemType);
}
}
}
| 34.505263 | 108 | 0.61867 | [
"MIT"
] | michaelsjennings/code-generation | MSJennings.CodeGeneration/MSJennings.CodeGeneration.Tests/ReflectionExtensionsTests.cs | 3,280 | C# |
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlockchainObserver.Currencies
{
public interface ICurrencyAdapter
{
/// <summary>
/// Get number of confirmations of given transaction
/// </summary>
/// <returns>null if transaction was not found</returns>
int? TransactionConfirmations(JToken tx);
/// <summary>
/// Get number of confirmations of given address
/// </summary>
/// <returns>null if transaction was not found</returns>
int? TransactionConfirmations(string txHash);
void ImportAddress(string address);
/// <summary>
/// Get last transactions on blockchain
/// </summary>
/// <returns>JArray</returns>
JArray GetLastTransactions();
}
}
| 27.46875 | 64 | 0.633675 | [
"MIT"
] | simplifate/crypto-invoice-blockchain-observer | BlockchainObserver/Currencies/ICurrencyAdapter.cs | 881 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Lclb.Cllb.Interfaces
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for Citydistricts.
/// </summary>
public static partial class CitydistrictsExtensions
{
/// <summary>
/// Get entities from adoxio_citydistricts
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
public static MicrosoftDynamicsCRMadoxioCitydistrictCollection Get(this ICitydistricts operations, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>))
{
return operations.GetAsync(top, skip, search, filter, count, orderby, select, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Get entities from adoxio_citydistricts
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<MicrosoftDynamicsCRMadoxioCitydistrictCollection> GetAsync(this ICitydistricts operations, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(top, skip, search, filter, count, orderby, select, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get entities from adoxio_citydistricts
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<MicrosoftDynamicsCRMadoxioCitydistrictCollection> GetWithHttpMessages(this ICitydistricts operations, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null)
{
return operations.GetWithHttpMessagesAsync(top, skip, search, filter, count, orderby, select, expand, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Add new entity to adoxio_citydistricts
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// New entity
/// </param>
/// <param name='prefer'>
/// Required in order for the service to return a JSON representation of the
/// object.
/// </param>
public static MicrosoftDynamicsCRMadoxioCitydistrict Create(this ICitydistricts operations, MicrosoftDynamicsCRMadoxioCitydistrict body, string prefer = "return=representation")
{
return operations.CreateAsync(body, prefer).GetAwaiter().GetResult();
}
/// <summary>
/// Add new entity to adoxio_citydistricts
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// New entity
/// </param>
/// <param name='prefer'>
/// Required in order for the service to return a JSON representation of the
/// object.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<MicrosoftDynamicsCRMadoxioCitydistrict> CreateAsync(this ICitydistricts operations, MicrosoftDynamicsCRMadoxioCitydistrict body, string prefer = "return=representation", CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(body, prefer, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Add new entity to adoxio_citydistricts
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// New entity
/// </param>
/// <param name='prefer'>
/// Required in order for the service to return a JSON representation of the
/// object.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<MicrosoftDynamicsCRMadoxioCitydistrict> CreateWithHttpMessages(this ICitydistricts operations, MicrosoftDynamicsCRMadoxioCitydistrict body, string prefer = "return=representation", Dictionary<string, List<string>> customHeaders = null)
{
return operations.CreateWithHttpMessagesAsync(body, prefer, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Get entity from adoxio_citydistricts by key
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioCitydistrictid'>
/// key: adoxio_citydistrictid of adoxio_citydistrict
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
public static MicrosoftDynamicsCRMadoxioCitydistrict GetByKey(this ICitydistricts operations, string adoxioCitydistrictid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>))
{
return operations.GetByKeyAsync(adoxioCitydistrictid, select, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Get entity from adoxio_citydistricts by key
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioCitydistrictid'>
/// key: adoxio_citydistrictid of adoxio_citydistrict
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<MicrosoftDynamicsCRMadoxioCitydistrict> GetByKeyAsync(this ICitydistricts operations, string adoxioCitydistrictid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetByKeyWithHttpMessagesAsync(adoxioCitydistrictid, select, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get entity from adoxio_citydistricts by key
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioCitydistrictid'>
/// key: adoxio_citydistrictid of adoxio_citydistrict
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<MicrosoftDynamicsCRMadoxioCitydistrict> GetByKeyWithHttpMessages(this ICitydistricts operations, string adoxioCitydistrictid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null)
{
return operations.GetByKeyWithHttpMessagesAsync(adoxioCitydistrictid, select, expand, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Update entity in adoxio_citydistricts
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioCitydistrictid'>
/// key: adoxio_citydistrictid of adoxio_citydistrict
/// </param>
/// <param name='body'>
/// New property values
/// </param>
public static void Update(this ICitydistricts operations, string adoxioCitydistrictid, MicrosoftDynamicsCRMadoxioCitydistrict body)
{
operations.UpdateAsync(adoxioCitydistrictid, body).GetAwaiter().GetResult();
}
/// <summary>
/// Update entity in adoxio_citydistricts
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioCitydistrictid'>
/// key: adoxio_citydistrictid of adoxio_citydistrict
/// </param>
/// <param name='body'>
/// New property values
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateAsync(this ICitydistricts operations, string adoxioCitydistrictid, MicrosoftDynamicsCRMadoxioCitydistrict body, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdateWithHttpMessagesAsync(adoxioCitydistrictid, body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Update entity in adoxio_citydistricts
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioCitydistrictid'>
/// key: adoxio_citydistrictid of adoxio_citydistrict
/// </param>
/// <param name='body'>
/// New property values
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse UpdateWithHttpMessages(this ICitydistricts operations, string adoxioCitydistrictid, MicrosoftDynamicsCRMadoxioCitydistrict body, Dictionary<string, List<string>> customHeaders = null)
{
return operations.UpdateWithHttpMessagesAsync(adoxioCitydistrictid, body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Delete entity from adoxio_citydistricts
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioCitydistrictid'>
/// key: adoxio_citydistrictid of adoxio_citydistrict
/// </param>
/// <param name='ifMatch'>
/// ETag
/// </param>
public static void Delete(this ICitydistricts operations, string adoxioCitydistrictid, string ifMatch = default(string))
{
operations.DeleteAsync(adoxioCitydistrictid, ifMatch).GetAwaiter().GetResult();
}
/// <summary>
/// Delete entity from adoxio_citydistricts
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioCitydistrictid'>
/// key: adoxio_citydistrictid of adoxio_citydistrict
/// </param>
/// <param name='ifMatch'>
/// ETag
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this ICitydistricts operations, string adoxioCitydistrictid, string ifMatch = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(adoxioCitydistrictid, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Delete entity from adoxio_citydistricts
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioCitydistrictid'>
/// key: adoxio_citydistrictid of adoxio_citydistrict
/// </param>
/// <param name='ifMatch'>
/// ETag
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse DeleteWithHttpMessages(this ICitydistricts operations, string adoxioCitydistrictid, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null)
{
return operations.DeleteWithHttpMessagesAsync(adoxioCitydistrictid, ifMatch, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
}
}
| 47.758152 | 495 | 0.561138 | [
"Apache-2.0"
] | brianorwhatever/jag-lcrb-carla-public | cllc-interfaces/Dynamics-Autorest/CitydistrictsExtensions.cs | 17,575 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.ResourceManager.IotCentral.Models
{
public partial class IotCentralAppPatch : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (Optional.IsCollectionDefined(Tags))
{
writer.WritePropertyName("tags");
writer.WriteStartObject();
foreach (var item in Tags)
{
writer.WritePropertyName(item.Key);
writer.WriteStringValue(item.Value);
}
writer.WriteEndObject();
}
if (Optional.IsDefined(Sku))
{
writer.WritePropertyName("sku");
writer.WriteObjectValue(Sku);
}
if (Optional.IsDefined(Identity))
{
writer.WritePropertyName("identity");
JsonSerializer.Serialize(writer, Identity);
}
writer.WritePropertyName("properties");
writer.WriteStartObject();
if (Optional.IsDefined(DisplayName))
{
writer.WritePropertyName("displayName");
writer.WriteStringValue(DisplayName);
}
if (Optional.IsDefined(Subdomain))
{
writer.WritePropertyName("subdomain");
writer.WriteStringValue(Subdomain);
}
if (Optional.IsDefined(Template))
{
writer.WritePropertyName("template");
writer.WriteStringValue(Template);
}
if (Optional.IsDefined(PublicNetworkAccess))
{
writer.WritePropertyName("publicNetworkAccess");
writer.WriteStringValue(PublicNetworkAccess.Value.ToString());
}
if (Optional.IsDefined(NetworkRuleSets))
{
writer.WritePropertyName("networkRuleSets");
writer.WriteObjectValue(NetworkRuleSets);
}
writer.WriteEndObject();
writer.WriteEndObject();
}
}
}
| 32.943662 | 78 | 0.54425 | [
"MIT"
] | ChenTanyi/azure-sdk-for-net | sdk/iotcentral/Azure.ResourceManager.IotCentral/src/Generated/Models/IotCentralAppPatch.Serialization.cs | 2,339 | C# |
namespace HousingFinanceInterimApi.Tests.V1.E2ETests
{
//For guidance on writing integration tests see the wiki page https://github.com/LBHackney-IT/lbh-base-api/wiki/Integration-Tests
public class ExampleTest : IntegrationTests<Startup>
{
}
}
| 29 | 133 | 0.758621 | [
"MIT"
] | LBHSPreston/housing-finance-interim-api | HousingFinanceInterimApi.Tests/V1/E2ETests/ExampleTest.cs | 261 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.