language stringclasses 1 value | repo stringclasses 133 values | path stringlengths 13 229 | class_span dict | source stringlengths 14 2.92M | target stringlengths 1 153 |
|---|---|---|---|---|---|
csharp | AutoFixture__AutoFixture | Src/AutoFixtureUnitTest/UnwrapMemberRequestTest.cs | {
"start": 177,
"end": 3301
} | public class ____
{
[Fact]
public void ShouldThrowIfNullInnerBuilderIsPassedToConstructor()
{
// Act & Assert
Assert.Throws<ArgumentNullException>(() =>
new UnwrapMemberRequest(builder: null));
}
[Fact]
public void ShouldSaveThePassedBuilderToProperty()
{
// Arrange
var builder = new DelegatingSpecimenBuilder();
// Act
var sut = new UnwrapMemberRequest(builder);
// Assert
Assert.Same(builder, sut.Builder);
}
[Fact]
public void DefaultResolverShouldHaveCorrectType()
{
// Act
var sut = new UnwrapMemberRequest(new DelegatingSpecimenBuilder());
// Assert
Assert.IsType<RequestMemberTypeResolver>(sut.MemberTypeResolver);
}
[Fact]
public void ShouldThrowIfNullMemberTypeResolverIsAssigned()
{
// Arrange
var sut = new UnwrapMemberRequest(new DelegatingSpecimenBuilder());
// Act & Assert
Assert.Throws<ArgumentNullException>(() =>
sut.MemberTypeResolver = null);
}
[Fact]
public void ShouldPassUnwrappedTypeToInnerBuilder()
{
// Arrange
var memberRequest = new object();
var memberType = typeof(List<int>);
var memberTypeResolver = new DelegatingRequestMemberTypeResolver
{
OnTryGetMemberType = r => r == memberRequest ? memberType : null
};
var expectedResult = new object();
var innerBuilder = new DelegatingSpecimenBuilder
{
OnCreate = (r, c) => memberType.Equals(r) ? expectedResult : new NoSpecimen()
};
var sut = new UnwrapMemberRequest(innerBuilder)
{
MemberTypeResolver = memberTypeResolver
};
var ctx = new DelegatingSpecimenContext();
// Act
var result = sut.Create(memberRequest, ctx);
// Assert
Assert.Equal(expectedResult, result);
}
[Fact]
public void ShouldNotInvokeInnerBuilderIfUnableToResolveMemberType()
{
// Arrange
var nonMemberRequest = new object();
var memberTypeResolver = new DelegatingRequestMemberTypeResolver
{
OnTryGetMemberType = _ => null
};
var innerBuilder = new DelegatingSpecimenBuilder
{
OnCreate = (r, c) => throw new InvalidOperationException("Should not be invoked")
};
var sut = new UnwrapMemberRequest(innerBuilder)
{
MemberTypeResolver = memberTypeResolver
};
var ctx = new DelegatingSpecimenContext();
// Act
var result = sut.Create(nonMemberRequest, ctx);
// Assert
Assert.Equal(new NoSpecimen(), result);
}
}
} | UnwrapMemberRequestTest |
csharp | dotnetcore__Util | test/Util.Localization.Tests.Integration/ResourceTypes/Resource4.cs | {
"start": 85,
"end": 175
} | public class ____ {
/// <summary>
/// 资源类型41 - 测试内部类
/// </summary>
| Resource4 |
csharp | kgrzybek__modular-monolith-with-ddd | src/Modules/Meetings/Domain/MeetingComments/Rules/CommentCanBeAddedOnlyByMeetingGroupMemberRule.cs | {
"start": 269,
"end": 813
} | public class ____ : IBusinessRule
{
private readonly MemberId _authorId;
private readonly MeetingGroup _meetingGroup;
public CommentCanBeAddedOnlyByMeetingGroupMemberRule(MemberId authorId, MeetingGroup meetingGroup)
{
_authorId = authorId;
_meetingGroup = meetingGroup;
}
public bool IsBroken() => !_meetingGroup.IsMemberOfGroup(_authorId);
public string Message => "Only meeting attendee can add comments";
}
} | CommentCanBeAddedOnlyByMeetingGroupMemberRule |
csharp | Cysharp__MemoryPack | sandbox/SandboxConsoleApp/Program.cs | {
"start": 10644,
"end": 10702
} | public partial class ____ : UnionType
{
}
[MemoryPackable]
| A |
csharp | dotnet__aspnetcore | src/FileProviders/Manifest.MSBuildTask/src/Manifest.cs | {
"start": 2195,
"end": 2608
} | private sealed class ____
{
public const string Directory = "Directory";
public const string Name = "Name";
public const string FileSystem = "FileSystem";
public const string Root = "Manifest";
public const string File = "File";
public const string ResourcePath = "ResourcePath";
public const string ManifestVersion = "ManifestVersion";
}
}
| ElementNames |
csharp | unoplatform__uno | src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Shapes/Path_Geometries.xaml.cs | {
"start": 144,
"end": 256
} | partial class ____ : Page
{
public Path_Geometries()
{
this.InitializeComponent();
}
}
}
| Path_Geometries |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Base/Media/GradientSpreadMethod.cs | {
"start": 31,
"end": 123
} | public enum ____
{
Pad,
Reflect,
Repeat
}
}
| GradientSpreadMethod |
csharp | xunit__xunit | src/common/MessagePartials/TestOutput.cs | {
"start": 277,
"end": 699
} | partial class ____ : TestMessage, ITestOutput
{
/// <inheritdoc/>
protected override void Serialize(JsonObjectSerializer serializer)
{
Guard.ArgumentNotNull(serializer);
base.Serialize(serializer);
serializer.Serialize(nameof(Output), Output);
}
/// <inheritdoc/>
public override string ToString() =>
string.Format(CultureInfo.CurrentCulture, "{0} output={1}", base.ToString(), Output.Quoted());
}
| TestOutput |
csharp | dotnet__maui | src/Compatibility/Core/src/WPF/Microsoft.Windows.Shell/Standard/NativeMethods.cs | {
"start": 29682,
"end": 30226
} | internal enum ____
{
NONE = 0x00000000,
INFO = 0x00000001,
WARNING = 0x00000002,
ERROR = 0x00000003,
/// <summary>XP SP2 and later.</summary>
USER = 0x00000004,
/// <summary>XP and later.</summary>
NOSOUND = 0x00000010,
/// <summary>Vista and later.</summary>
LARGE_ICON = 0x00000020,
/// <summary>Windows 7 and later</summary>
NIIF_RESPECT_QUIET_TIME = 0x00000080,
/// <summary>XP and later. Native version called NIIF_ICON_MASK.</summary>
XP_ICON_MASK = 0x0000000F,
}
/// <summary>
/// AC_*
/// </summary>
| NIIF |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenDropCollectionTest.cs | {
"start": 796,
"end": 2484
} | public sealed class ____ : JsonDrivenDatabaseTest
{
// private fields
private string _collectionName;
private DropCollectionOptions _dropCollectionOptions;
// public constructors
public JsonDrivenDropCollectionTest(IMongoDatabase database, Dictionary<string, object> objectMap)
: base(database, objectMap)
{
_dropCollectionOptions = new DropCollectionOptions();
}
// public methods
public override void Arrange(BsonDocument document)
{
JsonDrivenHelper.EnsureAllFieldsAreValid(document, "name", "object", "arguments", "encryptedFields");
base.Arrange(document);
}
// protected methods
protected override void CallMethod(CancellationToken cancellationToken)
{
_database.DropCollection(_collectionName, options: _dropCollectionOptions, cancellationToken);
}
protected override async Task CallMethodAsync(CancellationToken cancellationToken)
{
await _database.DropCollectionAsync(_collectionName, options: _dropCollectionOptions, cancellationToken).ConfigureAwait(false);
}
protected override void SetArgument(string name, BsonValue value)
{
switch (name)
{
case "collection":
_collectionName = value.AsString;
return;
case "encryptedFields":
_dropCollectionOptions.EncryptedFields = value.AsBsonDocument;
return;
}
base.SetArgument(name, value);
}
}
}
| JsonDrivenDropCollectionTest |
csharp | AutoMapper__AutoMapper | src/UnitTests/ForPath.cs | {
"start": 9155,
"end": 9253
} | public struct ____
{
public string Name;
public decimal Total;
}
| Customer |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.DataAnnotations/test/DataAnnotationsMetadataProviderTest.cs | {
"start": 77490,
"end": 77619
} | private class ____
{
public int Id { get; set; }
public string Name { get; set; }
}
| ClassWithProperties |
csharp | EventStore__EventStore | src/KurrentDB.Projections.Core/Messages/CoreProjectionManagementMessage.cs | {
"start": 705,
"end": 935
} | public partial class ____ : CoreProjectionManagementControlMessage {
public LoadStopped(Guid correlationId, Guid workerId)
: base(correlationId, workerId) {
}
}
[DerivedMessage(ProjectionMessage.CoreManagement)]
| LoadStopped |
csharp | abpframework__abp | modules/cms-kit/src/Volo.CmsKit.Admin.HttpApi/Volo/CmsKit/Admin/Tags/EntityTagAdminController.cs | {
"start": 486,
"end": 1295
} | public class ____ : CmsKitAdminController, IEntityTagAdminAppService
{
protected IEntityTagAdminAppService EntityTagAdminAppService { get; }
public EntityTagAdminController(IEntityTagAdminAppService entityTagAdminAppService)
{
EntityTagAdminAppService = entityTagAdminAppService;
}
[HttpPost]
public Task AddTagToEntityAsync(EntityTagCreateDto input)
{
return EntityTagAdminAppService.AddTagToEntityAsync(input);
}
[HttpDelete]
public Task RemoveTagFromEntityAsync(EntityTagRemoveDto input)
{
return EntityTagAdminAppService.RemoveTagFromEntityAsync(input);
}
[HttpPut]
public Task SetEntityTagsAsync(EntityTagSetDto input)
{
return EntityTagAdminAppService.SetEntityTagsAsync(input);
}
}
| EntityTagAdminController |
csharp | microsoft__semantic-kernel | dotnet/src/VectorData/VectorData.Abstractions/RecordDefinition/VectorStoreProperty.cs | {
"start": 339,
"end": 580
} | public abstract class ____
{
/// <summary>
/// Initializes a new instance of the <see cref="VectorStoreProperty"/> class.
/// </summary>
/// <param name="name">The name of the property on the data model. If the | VectorStoreProperty |
csharp | dotnet__orleans | src/api/Orleans.Serialization/Orleans.Serialization.cs | {
"start": 38446,
"end": 38933
} | public partial struct ____
{
private object _dummy;
private int _dummyPrimitive;
public System.ReadOnlyMemory<byte> CurrentMemory;
public MemoryEnumerator(PooledBuffer buffer) { }
public System.ReadOnlyMemory<byte> Current { get { throw null; } }
public readonly MemoryEnumerator GetEnumerator() { throw null; }
public bool MoveNext() { throw null; }
}
public ref | MemoryEnumerator |
csharp | louthy__language-ext | LanguageExt.Core/Effects/Schedule/Schedule.DSL.cs | {
"start": 192,
"end": 367
} | internal record ____(Iterable<Duration> Items) : Schedule
{
public override Iterable<Duration> Run() =>
Items;
}
/// <summary>
/// Functor map
/// </summary>
| SchItems |
csharp | dotnet__aspnetcore | src/Shared/HttpSys/RequestProcessing/RequestHeaders.cs | {
"start": 514,
"end": 8750
} | partial class ____ : IHeaderDictionary
{
private IDictionary<string, StringValues>? _extra;
private readonly NativeRequestContext _requestMemoryBlob;
private long? _contentLength;
private StringValues _contentLengthText;
internal RequestHeaders(NativeRequestContext requestMemoryBlob)
{
_requestMemoryBlob = requestMemoryBlob;
}
public bool IsReadOnly { get; internal set; }
private IDictionary<string, StringValues> Extra
{
get
{
if (_extra == null)
{
var newDict = new Dictionary<string, StringValues>(StringComparer.OrdinalIgnoreCase);
GetUnknownHeaders(newDict);
Interlocked.CompareExchange(ref _extra, newDict, null);
}
return _extra;
}
}
StringValues IDictionary<string, StringValues>.this[string key]
{
get
{
StringValues value;
return PropertiesTryGetValue(key, out value) ? value : Extra[key];
}
set
{
ThrowIfReadOnly();
if (!PropertiesTrySetValue(key, value))
{
Extra[key] = value;
}
}
}
private string? GetKnownHeader(HttpSysRequestHeader header)
{
return _requestMemoryBlob.GetKnownHeader(header);
}
private void GetUnknownHeaders(IDictionary<string, StringValues> extra)
{
_requestMemoryBlob.GetUnknownHeaders(extra);
}
void IDictionary<string, StringValues>.Add(string key, StringValues value)
{
if (ContainsKey(key))
{
ThrowDuplicateKeyException();
}
if (!PropertiesTrySetValue(key, value))
{
Extra.Add(key, value);
}
}
public bool ContainsKey(string key)
{
return PropertiesContainsKey(key) || Extra.ContainsKey(key);
}
public ICollection<string> Keys
{
get
{
var destination = new string[Count];
int knownHeadersCount = GetKnownHeadersKeys(destination);
if (_extra != null)
{
foreach (var item in _extra)
{
destination[knownHeadersCount++] = item.Key;
}
}
else
{
_requestMemoryBlob.GetUnknownKeys(destination.AsSpan(knownHeadersCount));
}
return destination;
}
}
ICollection<StringValues> IDictionary<string, StringValues>.Values
{
get { return PropertiesValues().Concat(Extra.Values).ToArray(); }
}
public int Count
{
get
{
int count = GetKnownHeadersCount();
count += _extra != null ? _extra.Count : _requestMemoryBlob.CountUnknownHeaders();
return count;
}
}
public bool Remove(string key)
{
// Although this is a mutating operation, Extra is used instead of StrongExtra,
// because if a real dictionary has not been allocated the default behavior of the
// nil dictionary is perfectly fine.
return PropertiesTryRemove(key) || Extra.Remove(key);
}
public bool TryGetValue(string key, out StringValues value)
{
return PropertiesTryGetValue(key, out value) || Extra.TryGetValue(key, out value);
}
internal void ResetFlags()
{
_flag0 = 0;
_flag1 = 0;
_extra = null;
}
void ICollection<KeyValuePair<string, StringValues>>.Add(KeyValuePair<string, StringValues> item)
{
((IDictionary<string, StringValues>)this).Add(item.Key, item.Value);
}
void ICollection<KeyValuePair<string, StringValues>>.Clear()
{
foreach (var key in PropertiesKeys())
{
PropertiesTryRemove(key);
}
Extra.Clear();
}
bool ICollection<KeyValuePair<string, StringValues>>.Contains(KeyValuePair<string, StringValues> item)
{
return ((IDictionary<string, StringValues>)this).TryGetValue(item.Key, out var value) && Equals(value, item.Value);
}
void ICollection<KeyValuePair<string, StringValues>>.CopyTo(KeyValuePair<string, StringValues>[] array, int arrayIndex)
{
PropertiesEnumerable().Concat(Extra).ToArray().CopyTo(array, arrayIndex);
}
bool ICollection<KeyValuePair<string, StringValues>>.IsReadOnly
{
get { return false; }
}
long? IHeaderDictionary.ContentLength
{
get
{
long value;
var rawValue = this[HeaderNames.ContentLength];
if (_contentLengthText.Equals(rawValue))
{
return _contentLength;
}
if (rawValue.Count == 1 &&
!string.IsNullOrWhiteSpace(rawValue[0]) &&
HeaderUtilities.TryParseNonNegativeInt64(new StringSegment(rawValue[0]).Trim(), out value))
{
_contentLengthText = rawValue;
_contentLength = value;
return value;
}
return null;
}
set
{
ThrowIfReadOnly();
if (value.HasValue)
{
if (value.Value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value.Value, "Cannot be negative.");
}
_contentLengthText = HeaderUtilities.FormatNonNegativeInt64(value.Value);
this[HeaderNames.ContentLength] = _contentLengthText;
_contentLength = value;
}
else
{
Remove(HeaderNames.ContentLength);
_contentLengthText = StringValues.Empty;
_contentLength = null;
}
}
}
public StringValues this[string key]
{
get
{
return TryGetValue(key, out var values) ? values : StringValues.Empty;
}
set
{
if (value.Count == 0)
{
Remove(key);
}
else if (!PropertiesTrySetValue(key, value))
{
Extra[key] = value;
}
}
}
bool ICollection<KeyValuePair<string, StringValues>>.Remove(KeyValuePair<string, StringValues> item)
{
return ((IDictionary<string, StringValues>)this).Contains(item) &&
((IDictionary<string, StringValues>)this).Remove(item.Key);
}
IEnumerator<KeyValuePair<string, StringValues>> IEnumerable<KeyValuePair<string, StringValues>>.GetEnumerator()
{
return PropertiesEnumerable().Concat(Extra).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IDictionary<string, StringValues>)this).GetEnumerator();
}
private void ThrowIfReadOnly()
{
if (IsReadOnly)
{
throw new InvalidOperationException("The response headers cannot be modified because the response has already started.");
}
}
private static void ThrowDuplicateKeyException()
{
throw new ArgumentException("An item with the same key has already been added.");
}
public IEnumerable<string> GetValues(string key)
{
StringValues values;
if (TryGetValue(key, out values))
{
return HeaderParser.SplitValues(values);
}
return HeaderParser.Empty;
}
private int GetKnownHeadersKeys(Span<string> observedHeaders)
{
int observedHeadersCount = 0;
for (int i = 0; i < HeaderKeys.Length; i++)
{
var header = HeaderKeys[i];
if (HasKnownHeader(header))
{
observedHeaders[observedHeadersCount++] = GetHeaderKeyName(header);
}
}
return observedHeadersCount;
}
private int GetKnownHeadersCount()
{
int observedHeadersCount = 0;
for (int i = 0; i < HeaderKeys.Length; i++)
{
var header = HeaderKeys[i];
if (HasKnownHeader(header))
{
observedHeadersCount++;
}
}
return observedHeadersCount;
}
}
| RequestHeaders |
csharp | dotnet__maui | src/Controls/src/Core/DoubleCollectionConverter.cs | {
"start": 280,
"end": 1941
} | public class ____ : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
=> sourceType == typeof(string)
|| sourceType == typeof(double[])
|| sourceType == typeof(float[]);
public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destinationType)
=> destinationType == typeof(string);
public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
{
if (value is double[] doublesArray)
{
return (DoubleCollection)doublesArray;
}
else if (value is float[] floatsArray)
{
return (DoubleCollection)floatsArray;
}
var strValue = value.ToString();
if (strValue is null)
{
throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", strValue, typeof(DoubleCollection)));
}
string[] doubles = strValue.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
var doubleCollection = new DoubleCollection();
foreach (string d in doubles)
{
if (double.TryParse(d, NumberStyles.Number, CultureInfo.InvariantCulture, out double number))
{
doubleCollection.Add(number);
}
else
{
throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", d, typeof(double)));
}
}
return doubleCollection;
}
public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType)
{
if (value is not DoubleCollection dc)
{
throw new NotSupportedException();
}
return string.Join(", ", dc);
}
}
}
| DoubleCollectionConverter |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/PropertyValuesTestBase.cs | {
"start": 165712,
"end": 165791
} | protected class ____
{
public string? Text { get; set; }
}
| Tag |
csharp | NSubstitute__NSubstitute | src/NSubstitute/Core/IResultsForType.cs | {
"start": 30,
"end": 194
} | public interface ____
{
void SetResult(Type type, IReturn resultToReturn);
bool TryGetResult(ICall call, out object? result);
void Clear();
} | IResultsForType |
csharp | cake-build__cake | src/Cake.Core.Tests/Fixtures/ScriptAnalyzerFixture.cs | {
"start": 451,
"end": 1839
} | public sealed class ____
{
public FakeFileSystem FileSystem { get; set; }
public FakeEnvironment Environment { get; set; }
public IGlobber Globber { get; set; }
public ICakeLog Log { get; set; }
public List<ILoadDirectiveProvider> Providers { get; set; }
public ScriptAnalyzerFixture(bool windows = false)
{
Environment = windows
? FakeEnvironment.CreateWindowsEnvironment()
: FakeEnvironment.CreateUnixEnvironment();
FileSystem = new FakeFileSystem(Environment);
Globber = new Globber(FileSystem, Environment);
Log = Substitute.For<ICakeLog>();
Providers = new List<ILoadDirectiveProvider>();
}
public void AddFileLoadDirectiveProvider()
{
Providers.Add(new FileLoadDirectiveProvider(Globber, Log));
}
public ScriptAnalyzer CreateAnalyzer()
{
return new ScriptAnalyzer(FileSystem, Environment, Log, Providers);
}
public ScriptAnalyzerResult Analyze(FilePath script)
{
return CreateAnalyzer().Analyze(script, new ScriptAnalyzerSettings());
}
public void GivenScriptExist(FilePath path, string content)
{
FileSystem.CreateFile(path).SetContent(content);
}
}
} | ScriptAnalyzerFixture |
csharp | dotnet__extensions | test/Shared/JsonSchemaExporter/TestTypes.cs | {
"start": 48947,
"end": 49323
} | public class ____
{
public ClassWithComponentModelAttributes(string stringValue, [DefaultValue(42)] int intValue)
{
StringValue = stringValue;
IntValue = intValue;
}
[RegularExpression(@"\w+")]
public string StringValue { get; }
public int IntValue { get; }
}
| ClassWithComponentModelAttributes |
csharp | fluentassertions__fluentassertions | Tests/FluentAssertions.Specs/Events/EventAssertionSpecs.cs | {
"start": 44048,
"end": 44150
} | public interface ____
{
event EventHandler Interface2Event;
}
| IEventRaisingInterface2 |
csharp | CommunityToolkit__WindowsCommunityToolkit | UnitTests/UnitTests.Notifications.Shared/Test_Toast_Xml.cs | {
"start": 370,
"end": 57960
} | public class ____
{
[TestMethod]
public void Test_Toast_XML_Toast_Defaults()
{
AssertPayload("<toast/>", new ToastContent());
}
[TestMethod]
public void Test_Toast_XML_Toast_Launch_Value()
{
var toast = new ToastContent()
{
Launch = "tacos"
};
AssertPayload("<toast launch='tacos'/>", toast);
}
[TestMethod]
public void Test_Toast_XML_Toast_ActivationType_Foreground()
{
var toast = new ToastContent()
{
ActivationType = ToastActivationType.Foreground
};
AssertPayload("<toast />", toast);
}
[TestMethod]
public void Test_Toast_XML_Toast_ActivationType_Background()
{
var toast = new ToastContent()
{
ActivationType = ToastActivationType.Background
};
AssertPayload("<toast activationType='background' />", toast);
}
[TestMethod]
public void Test_Toast_XML_Toast_ActivationType_Protocol()
{
var toast = new ToastContent()
{
ActivationType = ToastActivationType.Protocol
};
AssertPayload("<toast activationType='protocol' />", toast);
}
[TestMethod]
public void Test_Toast_XML_Toast_Scenario_Default()
{
var toast = new ToastContent()
{
Scenario = ToastScenario.Default
};
AssertPayload("<toast />", toast);
}
[TestMethod]
public void Test_Toast_XML_Toast_Scenarios()
{
AssertToastScenario(ToastScenario.Reminder, "reminder");
AssertToastScenario(ToastScenario.Alarm, "alarm");
AssertToastScenario(ToastScenario.IncomingCall, "incomingCall");
}
private void AssertToastScenario(ToastScenario scenario, string scenarioText)
{
var toast = new ToastContent()
{
Scenario = scenario
};
AssertPayload("<toast scenario='" + scenarioText + "'/>", toast);
}
[TestMethod]
public void Test_Toast_XML_Toast_Duration_Short()
{
var toast = new ToastContent()
{
Duration = ToastDuration.Short
};
AssertPayload("<toast />", toast);
}
[TestMethod]
public void Test_Toast_XML_Toast_Duration_Long()
{
var toast = new ToastContent()
{
Duration = ToastDuration.Long
};
AssertPayload("<toast duration='long' />", toast);
}
[TestMethod]
public void Test_Toast_XML_Toast_HintToastId()
{
var toast = new ToastContent()
{
HintToastId = "AppointmentReminder"
};
AssertPayload("<toast hint-toastId='AppointmentReminder' />", toast);
}
[TestMethod]
public void Test_Toast_XML_Toast_HintPeople_RemoteId()
{
var toast = new ToastContent()
{
HintPeople = new ToastPeople()
{
RemoteId = "1234"
}
};
AssertPayload("<toast hint-people='remoteid:1234' />", toast);
}
[TestMethod]
public void Test_Toast_XML_Toast_HintPeople_EmailAddress()
{
var toast = new ToastContent()
{
HintPeople = new ToastPeople()
{
EmailAddress = "johndoe@mydomain.com"
}
};
AssertPayload("<toast hint-people='mailto:johndoe@mydomain.com' />", toast);
}
[TestMethod]
public void Test_Toast_XML_Toast_HintPeople_PhoneNumber()
{
var toast = new ToastContent()
{
HintPeople = new ToastPeople()
{
PhoneNumber = "888-888-8888"
}
};
AssertPayload("<toast hint-people='tel:888-888-8888' />", toast);
}
[TestMethod]
public void Test_Toast_XML_Toast_HintPeople_Precedence()
{
// Email should take precedence over phone number
var toast = new ToastContent()
{
HintPeople = new ToastPeople()
{
EmailAddress = "johndoe@mydomain.com",
PhoneNumber = "888-888-8888"
}
};
AssertPayload("<toast hint-people='mailto:johndoe@mydomain.com' />", toast);
// RemoteId should take precedence over phone number
toast.HintPeople = new ToastPeople()
{
RemoteId = "1234",
PhoneNumber = "888-888-8888"
};
AssertPayload("<toast hint-people='remoteid:1234' />", toast);
// RemoteId should take precedence over all
toast.HintPeople = new ToastPeople()
{
RemoteId = "1234",
PhoneNumber = "888-888-8888",
EmailAddress = "johndoe@mydomain.com"
};
AssertPayload("<toast hint-people='remoteid:1234' />", toast);
}
[TestMethod]
public void Test_Toast_XML_Toast_AdditionalProperties()
{
AssertPayload("<toast hint-tacos='yummy://kind=beans,c=0' />", new ToastContent()
{
AdditionalProperties =
{
{ "hint-tacos", "yummy://kind=beans,c=0" }
}
});
// Multiple
AssertPayload("<toast avacado='definitely' burrito='true' />", new ToastContent()
{
AdditionalProperties =
{
{ "burrito", "true" },
{ "avacado", "definitely" }
}
});
// XML encoding
AssertPayload("<toast request='eggs & beans' />", new ToastContent()
{
AdditionalProperties =
{
{ "request", "eggs & beans" }
}
});
}
[TestMethod]
public void Test_ToastV2_Visual_Defaults()
{
AssertPayload("<toast></toast>", new ToastContent());
}
[TestMethod]
public void Test_ToastV2_Visual_AddImageQuery_False()
{
var visual = new ToastVisual()
{
AddImageQuery = false
};
AssertVisualPayloadProperties(@"addImageQuery='false'", visual);
}
[TestMethod]
public void Test_ToastV2_Visual_AddImageQuery_True()
{
var visual = new ToastVisual()
{
AddImageQuery = true
};
AssertVisualPayloadProperties(@"addImageQuery=""true""", visual);
}
[TestMethod]
public void Test_ToastV2_Visual_BaseUri_Value()
{
var visual = new ToastVisual()
{
BaseUri = new Uri("http://msn.com")
};
AssertVisualPayloadProperties(@"baseUri=""http://msn.com/""", visual);
}
[TestMethod]
public void Test_ToastV2_Visual_Language_Value()
{
var visual = new ToastVisual()
{
Language = "en-US"
};
AssertVisualPayloadProperties(@"lang=""en-US""", visual);
}
[TestMethod]
public void Test_ToastV2_Visual_AdaptiveText_Defaults()
{
AssertAdaptiveText(@"<text/>", new AdaptiveText());
}
[TestMethod]
public void Test_ToastV2_Visual_AdaptiveText_All()
{
AssertAdaptiveText(@"<text lang=""en-US"" hint-align=""right"" hint-maxLines=""3"" hint-minLines=""2"" hint-style=""header"" hint-wrap=""true"">Hi, I am a title</text>", new AdaptiveText()
{
Text = "Hi, I am a title",
Language = "en-US",
HintAlign = AdaptiveTextAlign.Right,
HintMaxLines = 3,
HintMinLines = 2,
HintStyle = AdaptiveTextStyle.Header,
HintWrap = true
});
}
[TestMethod]
public void Test_ToastV2_Xml_Attribution()
{
var visual = new ToastVisual()
{
BindingGeneric = new ToastBindingGeneric()
{
Children =
{
new AdaptiveText()
{
Text = "My title"
},
new AdaptiveText()
{
Text = "My body 1"
}
},
Attribution = new ToastGenericAttributionText()
{
Text = "cnn.com"
}
}
};
AssertVisualPayload(@"<visual><binding template=""ToastGeneric""><text>My title</text><text>My body 1</text><text placement='attribution'>cnn.com</text></binding></visual>", visual);
}
[TestMethod]
public void Test_ToastV2_Xml_Attribution_Lang()
{
var visual = new ToastVisual()
{
BindingGeneric = new ToastBindingGeneric()
{
Children =
{
new AdaptiveText()
{
Text = "My title"
},
new AdaptiveText()
{
Text = "My body 1"
}
},
Attribution = new ToastGenericAttributionText()
{
Text = "cnn.com",
Language = "en-US"
}
}
};
AssertVisualPayload(@"<visual><binding template=""ToastGeneric""><text>My title</text><text>My body 1</text><text placement='attribution' lang='en-US'>cnn.com</text></binding></visual>", visual);
}
[TestMethod]
public void Test_ToastV2_BindingGeneric_BaseUri()
{
AssertBindingGenericProperty("baseUri", "http://msn.com/images/", new ToastBindingGeneric()
{
BaseUri = new Uri("http://msn.com/images/", UriKind.Absolute)
});
}
[TestMethod]
public void Test_ToastV2_BindingGeneric_AddImageQuery()
{
AssertBindingGenericProperty("addImageQuery", "false", new ToastBindingGeneric()
{
AddImageQuery = false
});
AssertBindingGenericProperty("addImageQuery", "true", new ToastBindingGeneric()
{
AddImageQuery = true
});
}
[TestMethod]
public void Test_ToastV2_BindingGeneric_Language()
{
AssertBindingGenericProperty("lang", "en-US", new ToastBindingGeneric()
{
Language = "en-US"
});
}
[TestMethod]
public void Test_ToastV2_BindingGeneric_DefaultNullValues()
{
AssertBindingGenericPayload("<binding template='ToastGeneric' />", new ToastBindingGeneric()
{
AddImageQuery = null,
AppLogoOverride = null,
BaseUri = null,
Language = null,
HeroImage = null,
Attribution = null
});
}
private static void AssertBindingGenericProperty(string expectedPropertyName, string expectedPropertyValue, ToastBindingGeneric binding)
{
AssertBindingGenericPayload($"<binding template='ToastGeneric' {expectedPropertyName}='{expectedPropertyValue}'/>", binding);
}
[TestMethod]
public void Test_ToastV2_BindingShoulderTap_BaseUri()
{
AssertBindingShoulderTapProperty("baseUri", "http://msn.com/images/", new ToastBindingShoulderTap()
{
BaseUri = new Uri("http://msn.com/images/", UriKind.Absolute)
});
}
[TestMethod]
public void Test_ToastV2_BindingShoulderTap_AddImageQuery()
{
AssertBindingShoulderTapProperty("addImageQuery", "false", new ToastBindingShoulderTap()
{
AddImageQuery = false
});
AssertBindingShoulderTapProperty("addImageQuery", "true", new ToastBindingShoulderTap()
{
AddImageQuery = true
});
}
[TestMethod]
public void Test_ToastV2_BindingShoulderTap_Language()
{
AssertBindingShoulderTapProperty("lang", "en-US", new ToastBindingShoulderTap()
{
Language = "en-US"
});
}
private static void AssertBindingShoulderTapProperty(string expectedPropertyName, string expectedPropertyValue, ToastBindingShoulderTap binding)
{
AssertBindingShoulderTapPayload($"<binding template='ToastGeneric' experienceType='shoulderTap' {expectedPropertyName}='{expectedPropertyValue}'/>", binding);
}
[TestMethod]
public void Test_ToastV2_ShoulderTapImage()
{
AssertShoulderTapImagePayload("<image src='img.png' addImageQuery='true' alt='alt text'/>", new ToastShoulderTapImage()
{
Source = "img.png",
AddImageQuery = true,
AlternateText = "alt text"
});
// Defaults shouldn't have anything assigned
AssertShoulderTapImagePayload("<image src='img.png'/>", new ToastShoulderTapImage()
{
Source = "img.png"
});
}
[TestMethod]
public void Test_ToastV2_ShoulderTapImage_SourceRequired()
{
Assert.ThrowsException<NullReferenceException>(() =>
{
AssertShoulderTapImagePayload("exception should be thrown", new ToastShoulderTapImage());
});
Assert.ThrowsException<ArgumentNullException>(() =>
{
new ToastShoulderTapImage()
{
Source = null
};
});
}
private static void AssertShoulderTapImagePayload(string expectedImageXml, ToastShoulderTapImage image)
{
AssertBindingShoulderTapPayload($"<binding template='ToastGeneric' experienceType='shoulderTap'>{expectedImageXml}</binding>", new ToastBindingShoulderTap()
{
Image = image
});
}
[TestMethod]
public void Test_ToastV2_SpriteSheet()
{
AssertSpriteSheetProperties("spritesheet-src='sprite.png' spritesheet-height='80' spritesheet-fps='25' spritesheet-startingFrame='15'", new ToastSpriteSheet()
{
Source = "sprite.png",
FrameHeight = 80,
Fps = 25,
StartingFrame = 15
});
// Defaults shouldn't have anything assigned
AssertSpriteSheetProperties("spritesheet-src='sprite.png'", new ToastSpriteSheet()
{
Source = "sprite.png"
});
// Can assign invalid values
AssertSpriteSheetProperties("spritesheet-src='sprite.png' spritesheet-height='0' spritesheet-fps='150' spritesheet-startingFrame='15'", new ToastSpriteSheet()
{
Source = "sprite.png",
FrameHeight = 0,
Fps = 150,
StartingFrame = 15
});
}
[TestMethod]
public void Test_ToastV2_SpriteSheet_SourceRequired()
{
Assert.ThrowsException<NullReferenceException>(() =>
{
AssertSpriteSheetProperties("exception should be thrown", new ToastSpriteSheet());
});
Assert.ThrowsException<ArgumentNullException>(() =>
{
new ToastSpriteSheet()
{
Source = null
};
});
}
private static void AssertSpriteSheetProperties(string expectedProperties, ToastSpriteSheet spriteSheet)
{
AssertShoulderTapImagePayload($"<image src='img.png' {expectedProperties} />", new ToastShoulderTapImage()
{
Source = "img.png",
SpriteSheet = spriteSheet
});
}
private static void AssertBindingShoulderTapPayload(string expectedBindingXml, ToastBindingShoulderTap binding)
{
AssertVisualPayload("<visual><binding template='ToastGeneric'/>" + expectedBindingXml + "</visual>", new ToastVisual()
{
BindingGeneric = new ToastBindingGeneric(),
BindingShoulderTap = binding
});
}
[TestMethod]
public void Test_ToastV2_AppLogo_Crop_None()
{
var appLogo = new ToastGenericAppLogo()
{
HintCrop = ToastGenericAppLogoCrop.None,
Source = "img.png"
};
AssertAppLogoPayload(@"<image src='img.png' placement=""appLogoOverride"" hint-crop='none'/>", appLogo);
}
[TestMethod]
public void Test_ToastV2_AppLogo_Crop_Circle()
{
var appLogo = new ToastGenericAppLogo()
{
HintCrop = ToastGenericAppLogoCrop.Circle,
Source = "img.png"
};
AssertAppLogoPayload(@"<image src=""img.png"" placement=""appLogoOverride"" hint-crop=""circle""/>", appLogo);
}
[TestMethod]
public void Test_ToastV2_AppLogo_Source_Defaults()
{
var appLogo = new ToastGenericAppLogo()
{
Source = "http://xbox.com/Avatar.jpg"
};
AssertAppLogoPayload(@"<image placement=""appLogoOverride"" src=""http://xbox.com/Avatar.jpg""/>", appLogo);
}
[TestMethod]
public void Test_ToastV2_AppLogo_Source_Alt()
{
var appLogo = new ToastGenericAppLogo()
{
Source = "http://xbox.com/Avatar.jpg",
AlternateText = "alternate"
};
AssertAppLogoPayload(@"<image placement=""appLogoOverride"" src=""http://xbox.com/Avatar.jpg"" alt=""alternate""/>", appLogo);
}
[TestMethod]
public void Test_ToastV2_AppLogo_Source_AddImageQuery_False()
{
var appLogo = new ToastGenericAppLogo()
{
Source = "http://xbox.com/Avatar.jpg",
AddImageQuery = false
};
AssertAppLogoPayload(@"<image placement=""appLogoOverride"" src=""http://xbox.com/Avatar.jpg"" addImageQuery='false'/>", appLogo);
}
[TestMethod]
public void Test_ToastV2_AppLogo_Source_AddImageQuery_True()
{
var appLogo = new ToastGenericAppLogo()
{
Source = "http://xbox.com/Avatar.jpg",
AddImageQuery = true
};
AssertAppLogoPayload(@"<image placement=""appLogoOverride"" src=""http://xbox.com/Avatar.jpg"" addImageQuery=""true""/>", appLogo);
}
[TestMethod]
public void Test_ToastV2_Xml_HeroImage_Default()
{
var hero = new ToastGenericHeroImage();
try
{
AssertHeroImagePayload("<image placement='hero'/>", hero);
}
catch (NullReferenceException)
{
return;
}
Assert.Fail("Exception should have been thrown since Source wasn't provided.");
}
[TestMethod]
public void Test_ToastV2_Xml_HeroImage_WithSource()
{
var hero = new ToastGenericHeroImage()
{
Source = "http://food.com/peanuts.jpg"
};
AssertHeroImagePayload("<image placement='hero' src='http://food.com/peanuts.jpg'/>", hero);
}
[TestMethod]
public void Test_ToastV2_Xml_HeroImage_Alt()
{
var hero = new ToastGenericHeroImage()
{
Source = "http://food.com/peanuts.jpg",
AlternateText = "peanuts"
};
AssertHeroImagePayload("<image placement='hero' src='http://food.com/peanuts.jpg' alt='peanuts'/>", hero);
}
[TestMethod]
public void Test_ToastV2_Xml_HeroImage_AddImageQuery()
{
var hero = new ToastGenericHeroImage()
{
Source = "http://food.com/peanuts.jpg",
AddImageQuery = true
};
AssertHeroImagePayload("<image placement='hero' src='http://food.com/peanuts.jpg' addImageQuery='true'/>", hero);
}
[TestMethod]
public void Test_ToastV2_Xml_HeroImage_AllProperties()
{
var hero = new ToastGenericHeroImage()
{
Source = "http://food.com/peanuts.jpg",
AddImageQuery = true,
AlternateText = "peanuts"
};
AssertHeroImagePayload("<image placement='hero' src='http://food.com/peanuts.jpg' addImageQuery='true' alt='peanuts'/>", hero);
}
private static ToastContent GenerateFromVisual(ToastVisual visual)
{
return new ToastContent()
{
Visual = visual
};
}
/// <summary>
/// Used for testing properties of visual without needing to specify the Generic binding
/// </summary>
private static void AssertVisualPayloadProperties(string expectedVisualProperties, ToastVisual visual)
{
visual.BindingGeneric = new ToastBindingGeneric();
AssertVisualPayload("<visual " + expectedVisualProperties + "><binding template='ToastGeneric'></binding></visual>", visual);
}
private static void AssertBindingGenericPayload(string expectedBindingXml, ToastBindingGeneric binding)
{
AssertVisualPayload("<visual>" + expectedBindingXml + "</visual>", new ToastVisual()
{
BindingGeneric = binding
});
}
private static void AssertAdaptiveText(string expectedAdaptiveTextXml, AdaptiveText text)
{
AssertBindingGenericPayload("<binding template='ToastGeneric'>" + expectedAdaptiveTextXml + "</binding>", new ToastBindingGeneric()
{
Children =
{
text
}
});
}
private static void AssertAppLogoPayload(string expectedAppLogoXml, ToastGenericAppLogo appLogo)
{
AssertVisualPayload(@"<visual><binding template=""ToastGeneric"">" + expectedAppLogoXml + "</binding></visual>", new ToastVisual()
{
BindingGeneric = new ToastBindingGeneric()
{
AppLogoOverride = appLogo
}
});
}
private static void AssertHeroImagePayload(string expectedHeroXml, ToastGenericHeroImage heroImage)
{
AssertVisualPayload(@"<visual><binding template=""ToastGeneric"">" + expectedHeroXml + "</binding></visual>", new ToastVisual()
{
BindingGeneric = new ToastBindingGeneric()
{
HeroImage = heroImage
}
});
}
[TestMethod]
public void Test_Toast_Xml_Audio_Defaults()
{
var audio = new ToastAudio();
AssertAudioPayload("<audio />", audio);
}
[TestMethod]
public void Test_Toast_Xml_Audio_Loop_False()
{
var audio = new ToastAudio()
{
Loop = false
};
AssertAudioPayload("<audio />", audio);
}
[TestMethod]
public void Test_Toast_Xml_Audio_Loop_True()
{
var audio = new ToastAudio()
{
Loop = true
};
AssertAudioPayload("<audio loop='true'/>", audio);
}
[TestMethod]
public void Test_Toast_Xml_Audio_Silent_False()
{
var audio = new ToastAudio()
{
Silent = false
};
AssertAudioPayload("<audio/>", audio);
}
[TestMethod]
public void Test_Toast_Xml_Audio_Silent_True()
{
var audio = new ToastAudio()
{
Silent = true
};
AssertAudioPayload("<audio silent='true'/>", audio);
}
[TestMethod]
public void Test_Toast_Xml_Audio_Src_Value()
{
var audio = new ToastAudio()
{
Src = new Uri("ms-appx:///Assets/audio.mp3")
};
AssertAudioPayload("<audio src='ms-appx:///Assets/audio.mp3'/>", audio);
}
[TestMethod]
public void Test_Toast_Xml_Actions_SnoozeAndDismiss()
{
AssertActionsPayload("<actions hint-systemCommands='SnoozeAndDismiss'/>", new ToastActionsSnoozeAndDismiss());
}
[TestMethod]
public void Test_Toast_Xml_Actions_Custom_Defaults()
{
AssertActionsPayload("<actions/>", new ToastActionsCustom());
}
[TestMethod]
public void Test_Toast_Xml_Actions_TextBoxAndButton()
{
AssertActionsPayload("<actions><input id='tb1' type='text'/><action content='Click me!' arguments='clickArgs'/></actions>", new ToastActionsCustom()
{
Buttons =
{
new ToastButton("Click me!", "clickArgs")
},
Inputs =
{
new ToastTextBox("tb1")
}
});
}
[TestMethod]
public void Test_Toast_Xml_Actions_TwoTextBoxes()
{
AssertActionsPayload("<actions><input id='tb1' type='text'/><input id='tb2' type='text'/></actions>", new ToastActionsCustom()
{
Inputs =
{
new ToastTextBox("tb1"),
new ToastTextBox("tb2")
}
});
}
[TestMethod]
public void Test_Toast_Xml_Actions_FiveTextBoxes()
{
AssertActionsPayload("<actions><input id='tb1' type='text'/><input id='tb2' type='text'/><input id='tb3' type='text'/><input id='tb4' type='text'/><input id='tb5' type='text'/></actions>", new ToastActionsCustom()
{
Inputs =
{
new ToastTextBox("tb1"),
new ToastTextBox("tb2"),
new ToastTextBox("tb3"),
new ToastTextBox("tb4"),
new ToastTextBox("tb5")
}
});
}
[TestMethod]
public void Test_Toast_Xml_Actions_SixTextBoxes()
{
try
{
new ToastActionsCustom()
{
Inputs =
{
new ToastTextBox("tb1"),
new ToastTextBox("tb2"),
new ToastTextBox("tb3"),
new ToastTextBox("tb4"),
new ToastTextBox("tb5"),
new ToastTextBox("tb6")
}
};
}
catch
{
return;
}
Assert.Fail("Exception should have been thrown.");
}
[TestMethod]
public void Test_Toast_Xml_Actions_SelectionAndButton()
{
AssertActionsPayload("<actions><input id='s1' type='selection'><selection id='1' content='First'/><selection id='2' content='Second'/></input><action content='Click me!' arguments='clickArgs'/></actions>", new ToastActionsCustom()
{
Inputs =
{
new ToastSelectionBox("s1")
{
Items =
{
new ToastSelectionBoxItem("1", "First"),
new ToastSelectionBoxItem("2", "Second")
}
}
},
Buttons =
{
new ToastButton("Click me!", "clickArgs")
}
});
}
[TestMethod]
public void Test_Toast_Xml_Actions_TwoButtons()
{
AssertActionsPayload("<actions><action content='Button 1' arguments='1'/><action content='Button 2' arguments='2'/></actions>", new ToastActionsCustom()
{
Buttons =
{
new ToastButton("Button 1", "1"),
new ToastButton("Button 2", "2")
}
});
}
[TestMethod]
public void Test_Toast_Xml_Actions_FiveButtons()
{
AssertActionsPayload("<actions><action content='Button 1' arguments='1'/><action content='Button 2' arguments='2'/><action content='Button 3' arguments='3'/><action content='Button 4' arguments='4'/><action content='Button 5' arguments='5'/></actions>", new ToastActionsCustom()
{
Buttons =
{
new ToastButton("Button 1", "1"),
new ToastButton("Button 2", "2"),
new ToastButton("Button 3", "3"),
new ToastButton("Button 4", "4"),
new ToastButton("Button 5", "5")
}
});
}
[TestMethod]
public void Test_Toast_Xml_Actions_SixButtons()
{
try
{
new ToastActionsCustom()
{
Buttons =
{
new ToastButton("Button 1", "1"),
new ToastButton("Button 2", "2"),
new ToastButton("Button 3", "3"),
new ToastButton("Button 4", "4"),
new ToastButton("Button 5", "5"),
new ToastButton("Button 6", "6")
}
};
}
catch
{
return;
}
Assert.Fail("Exception should have been thrown.");
}
[TestMethod]
public void Test_Toast_Xml_Actions_SixTotal()
{
try
{
AssertActionsPayload("doesn't matter", new ToastActionsCustom()
{
Buttons =
{
new ToastButton("Button 1", "1"),
new ToastButton("Button 2", "2"),
new ToastButton("Button 3", "3"),
new ToastButton("Button 4", "4"),
new ToastButton("Button 5", "5")
},
ContextMenuItems =
{
new ToastContextMenuItem("Menu item 1", "1")
}
});
}
catch (InvalidOperationException)
{
return;
}
Assert.Fail("Exception should have been thrown, only 5 actions are allowed.");
}
[TestMethod]
public void Test_Toast_Xml_Actions_SnoozeAndDismissUsingBuilders()
{
AssertActionsPayload("<actions><action content='' activationType='system' arguments='snooze'/><action content='' activationType='system' arguments='dismiss'/><action content='Hide' activationType='system' arguments='dismiss'/><action content='Later' activationType='system' arguments='snooze'/><action content='Remind me' activationType='system' arguments='snooze' hint-inputId='snoozePicker'/></actions>", new ToastActionsCustom()
{
Buttons =
{
// Allowing system to auto-generate text content
new ToastButton()
.SetSnoozeActivation(),
// Allowing system to auto-generate text content
new ToastButton()
.SetDismissActivation(),
// Specifying specific content
new ToastButton()
.SetContent("Hide")
.SetDismissActivation(),
new ToastButton()
.SetContent("Later")
.SetSnoozeActivation(),
new ToastButton()
.SetContent("Remind me")
.SetSnoozeActivation("snoozePicker")
}
});
}
[TestMethod]
public void Test_Toast_Xml_Actions_TwoContextMenuItems()
{
AssertActionsPayload("<actions><action placement='contextMenu' content='Menu item 1' arguments='1'/><action placement='contextMenu' content='Menu item 2' arguments='2'/></actions>", new ToastActionsCustom()
{
ContextMenuItems =
{
new ToastContextMenuItem("Menu item 1", "1"),
new ToastContextMenuItem("Menu item 2", "2")
}
});
}
[TestMethod]
public void Test_Toast_Xml_Actions_FiveContextMenuItems()
{
AssertActionsPayload("<actions><action placement='contextMenu' content='Menu item 1' arguments='1'/><action placement='contextMenu' content='Menu item 2' arguments='2'/><action placement='contextMenu' content='Menu item 3' arguments='3'/><action placement='contextMenu' content='Menu item 4' arguments='4'/><action placement='contextMenu' content='Menu item 5' arguments='5'/></actions>", new ToastActionsCustom()
{
ContextMenuItems =
{
new ToastContextMenuItem("Menu item 1", "1"),
new ToastContextMenuItem("Menu item 2", "2"),
new ToastContextMenuItem("Menu item 3", "3"),
new ToastContextMenuItem("Menu item 4", "4"),
new ToastContextMenuItem("Menu item 5", "5")
}
});
}
[TestMethod]
public void Test_Toast_Xml_Actions_SixContextMenuItems()
{
try
{
AssertActionsPayload("doesn't matter", new ToastActionsCustom()
{
ContextMenuItems =
{
new ToastContextMenuItem("Menu item 1", "1"),
new ToastContextMenuItem("Menu item 2", "2"),
new ToastContextMenuItem("Menu item 3", "3"),
new ToastContextMenuItem("Menu item 4", "4"),
new ToastContextMenuItem("Menu item 5", "5"),
new ToastContextMenuItem("Menu item 6", "6")
}
});
}
catch
{
return;
}
Assert.Fail("Exception should have been thrown.");
}
[TestMethod]
public void Test_Toast_Xml_ActionsSnoozeDismiss_TwoContextMenuItems()
{
AssertActionsPayload("<actions hint-systemCommands='SnoozeAndDismiss'><action placement='contextMenu' content='Menu item 1' arguments='1'/><action placement='contextMenu' content='Menu item 2' arguments='2'/></actions>", new ToastActionsSnoozeAndDismiss()
{
ContextMenuItems =
{
new ToastContextMenuItem("Menu item 1", "1"),
new ToastContextMenuItem("Menu item 2", "2")
}
});
}
[TestMethod]
public void Test_Toast_Xml_Actions_ActionsSnoozeDismiss_FiveContextMenuItems()
{
AssertActionsPayload("<actions hint-systemCommands='SnoozeAndDismiss'><action placement='contextMenu' content='Menu item 1' arguments='1'/><action placement='contextMenu' content='Menu item 2' arguments='2'/><action placement='contextMenu' content='Menu item 3' arguments='3'/><action placement='contextMenu' content='Menu item 4' arguments='4'/><action placement='contextMenu' content='Menu item 5' arguments='5'/></actions>", new ToastActionsSnoozeAndDismiss()
{
ContextMenuItems =
{
new ToastContextMenuItem("Menu item 1", "1"),
new ToastContextMenuItem("Menu item 2", "2"),
new ToastContextMenuItem("Menu item 3", "3"),
new ToastContextMenuItem("Menu item 4", "4"),
new ToastContextMenuItem("Menu item 5", "5")
}
});
}
[TestMethod]
public void Test_Toast_Xml_Actions_ActionsSnoozeDismiss_SixContextMenuItems()
{
try
{
AssertActionsPayload("doesn't matter", new ToastActionsSnoozeAndDismiss()
{
ContextMenuItems =
{
new ToastContextMenuItem("Menu item 1", "1"),
new ToastContextMenuItem("Menu item 2", "2"),
new ToastContextMenuItem("Menu item 3", "3"),
new ToastContextMenuItem("Menu item 4", "4"),
new ToastContextMenuItem("Menu item 5", "5"),
new ToastContextMenuItem("Menu item 6", "6")
}
});
}
catch
{
return;
}
Assert.Fail("Exception should have been thrown.");
}
[TestMethod]
public void Test_Toast_Xml_Button_Defaults()
{
ToastButton button = new ToastButton("my content", "myArgs");
AssertButtonPayload("<action content='my content' arguments='myArgs' />", button);
}
[TestMethod]
public void Test_Toast_Xml_Button_NullContent()
{
try
{
new ToastButton(null, "args");
}
catch
{
return;
}
Assert.Fail("Exception should have been thrown.");
}
[TestMethod]
public void Test_Toast_Xml_Button_NullArguments()
{
try
{
new ToastButton("content", null);
}
catch
{
return;
}
Assert.Fail("Exception should have been thrown.");
}
[TestMethod]
public void Test_Toast_Xml_Button_ActivationType_Foreground()
{
ToastButton button = new ToastButton("my content", "myArgs")
{
ActivationType = ToastActivationType.Foreground
};
AssertButtonPayload("<action content='my content' arguments='myArgs' />", button);
}
[TestMethod]
public void Test_Toast_Xml_Button_ActivationType_Background()
{
ToastButton button = new ToastButton("my content", "myArgs")
{
ActivationType = ToastActivationType.Background
};
AssertButtonPayload("<action content='my content' arguments='myArgs' activationType='background' />", button);
}
[TestMethod]
public void Test_Toast_Xml_Button_ActivationType_Protocol()
{
ToastButton button = new ToastButton("my content", "myArgs")
{
ActivationType = ToastActivationType.Protocol
};
AssertButtonPayload("<action content='my content' arguments='myArgs' activationType='protocol' />", button);
}
[TestMethod]
public void Test_Toast_Xml_Button_ImageUri_Value()
{
ToastButton button = new ToastButton("my content", "myArgs")
{
ImageUri = "Assets/button.png"
};
AssertButtonPayload("<action content='my content' arguments='myArgs' imageUri='Assets/button.png' />", button);
}
[TestMethod]
public void Test_Toast_Xml_Button_TextBoxId_Value()
{
ToastButton button = new ToastButton("my content", "myArgs")
{
TextBoxId = "myTextBox"
};
AssertButtonPayload("<action content='my content' arguments='myArgs' hint-inputId='myTextBox' />", button);
}
[TestMethod]
public void Test_Toast_Xml_Button_HintActionId_Value()
{
ToastButton button = new ToastButton("my content", "myArgs")
{
HintActionId = "MyAction1"
};
AssertButtonPayload("<action content='my content' arguments='myArgs' hint-actionId='MyAction1' />", button);
}
[TestMethod]
public void Test_Toast_Xml_ButtonSnooze_Defaults()
{
ToastButtonSnooze button = new ToastButtonSnooze();
AssertButtonPayload("<action activationType='system' arguments='snooze' content=''/>", button);
}
[TestMethod]
public void Test_Toast_Xml_ButtonSnooze_CustomContent()
{
ToastButtonSnooze button = new ToastButtonSnooze("my snooze");
AssertButtonPayload("<action activationType='system' arguments='snooze' content='my snooze'/>", button);
}
[TestMethod]
public void Test_Toast_Xml_ButtonSnooze_Image()
{
ToastButtonSnooze button = new ToastButtonSnooze()
{
ImageUri = "Assets/Snooze.png"
};
AssertButtonPayload("<action activationType='system' arguments='snooze' content='' imageUri='Assets/Snooze.png'/>", button);
}
[TestMethod]
public void Test_Toast_Xml_ButtonSnooze_SelectionId()
{
ToastButtonSnooze button = new ToastButtonSnooze()
{
SelectionBoxId = "snoozeId"
};
AssertButtonPayload("<action activationType='system' arguments='snooze' content='' hint-inputId='snoozeId'/>", button);
}
[TestMethod]
public void Test_Toast_Xml_ButtonSnooze_HintActionId()
{
ToastButtonSnooze button = new ToastButtonSnooze()
{
HintActionId = "MySnoozeButton1"
};
AssertButtonPayload("<action activationType='system' arguments='snooze' content='' hint-actionId='MySnoozeButton1'/>", button);
}
[TestMethod]
public void Test_Toast_Xml_ButtonDismiss_Defaults()
{
ToastButtonDismiss button = new ToastButtonDismiss();
AssertButtonPayload("<action activationType='system' arguments='dismiss' content=''/>", button);
}
[TestMethod]
public void Test_Toast_Xml_ButtonDismiss_CustomContent()
{
ToastButtonDismiss button = new ToastButtonDismiss("my dismiss");
AssertButtonPayload("<action activationType='system' arguments='dismiss' content='my dismiss'/>", button);
}
[TestMethod]
public void Test_Toast_Xml_ButtonDismiss_Image()
{
ToastButtonDismiss button = new ToastButtonDismiss()
{
ImageUri = "Assets/Dismiss.png"
};
AssertButtonPayload("<action activationType='system' arguments='dismiss' content='' imageUri='Assets/Dismiss.png'/>", button);
}
[TestMethod]
public void Test_Toast_Xml_ButtonDismiss_HintActionId()
{
ToastButtonDismiss button = new ToastButtonDismiss()
{
HintActionId = "MyDismissButton1"
};
AssertButtonPayload("<action activationType='system' arguments='dismiss' content='' hint-actionId='MyDismissButton1'/>", button);
}
[TestMethod]
public void Test_Toast_Xml_ContextMenuItem_Defaults()
{
ToastContextMenuItem item = new ToastContextMenuItem("content", "args");
AssertContextMenuItemPayload("<action placement='contextMenu' content='content' arguments='args'/>", item);
}
[TestMethod]
public void Test_Toast_Xml_ContextMenuItem_NullContent()
{
try
{
new ToastContextMenuItem(null, "args");
}
catch
{
return;
}
Assert.Fail("Exception should have been thrown.");
}
[TestMethod]
public void Test_Toast_Xml_ContextMenuItem_NullArguments()
{
try
{
new ToastContextMenuItem("content", null);
}
catch
{
return;
}
Assert.Fail("Exception should have been thrown.");
}
[TestMethod]
public void Test_Toast_Xml_ContextMenuItem_ActivationType_Foreground()
{
ToastContextMenuItem item = new ToastContextMenuItem("content", "args")
{
ActivationType = ToastActivationType.Foreground
};
AssertContextMenuItemPayload("<action placement='contextMenu' content='content' arguments='args'/>", item);
}
[TestMethod]
public void Test_Toast_Xml_ContextMenuItem_ActivationType_Background()
{
ToastContextMenuItem item = new ToastContextMenuItem("content", "args")
{
ActivationType = ToastActivationType.Background
};
AssertContextMenuItemPayload("<action placement='contextMenu' content='content' arguments='args' activationType='background'/>", item);
}
[TestMethod]
public void Test_Toast_Xml_ContextMenuItem_ActivationType_Protocol()
{
ToastContextMenuItem item = new ToastContextMenuItem("content", "args")
{
ActivationType = ToastActivationType.Protocol
};
AssertContextMenuItemPayload("<action placement='contextMenu' content='content' arguments='args' activationType='protocol'/>", item);
}
[TestMethod]
public void Test_Toast_Xml_ContextMenuItem_HintActionId()
{
ToastContextMenuItem item = new ToastContextMenuItem("content", "args")
{
HintActionId = "MyContextMenu1"
};
AssertContextMenuItemPayload("<action placement='contextMenu' content='content' arguments='args' hint-actionId='MyContextMenu1'/>", item);
}
[TestMethod]
public void Test_Toast_Xml_TextBox_Defaults()
{
var textBox = new ToastTextBox("myId");
AssertInputPayload("<input id='myId' type='text' />", textBox);
}
[TestMethod]
public void Test_Toast_Xml_TextBox_DefaultTextInput_Value()
{
var textBox = new ToastTextBox("myId")
{
DefaultInput = "Default text input"
};
AssertInputPayload("<input id='myId' type='text' defaultInput='Default text input' />", textBox);
}
[TestMethod]
public void Test_Toast_Xml_TextBox_PlaceholderContent_Value()
{
var textBox = new ToastTextBox("myId")
{
PlaceholderContent = "My placeholder content"
};
AssertInputPayload("<input id='myId' type='text' placeHolderContent='My placeholder content' />", textBox);
}
[TestMethod]
public void Test_Toast_Xml_TextBox_Title_Value()
{
var textBox = new ToastTextBox("myId")
{
Title = "My title"
};
AssertInputPayload("<input id='myId' type='text' title='My title' />", textBox);
}
[TestMethod]
public void Test_Toast_Xml_TextBox_NullId()
{
try
{
new ToastTextBox(null);
}
catch
{
return;
}
Assert.Fail("Exception should have been thrown.");
}
[TestMethod]
public void Test_Toast_Xml_TextBox_EmptyId()
{
var textBox = new ToastTextBox(string.Empty);
AssertInputPayload("<input id='' type='text' />", textBox);
}
[TestMethod]
public void Test_Toast_Xml_SelectionBox_Defaults()
{
var selectionBox = new ToastSelectionBox("myId");
AssertInputPayload("<input id='myId' type='selection' />", selectionBox);
}
[TestMethod]
public void Test_Toast_Xml_SelectionBox_EmptyId()
{
var selectionBox = new ToastSelectionBox(string.Empty);
AssertInputPayload("<input id='' type='selection' />", selectionBox);
}
[TestMethod]
public void Test_Toast_Xml_SelectionBox_NullId()
{
try
{
new ToastSelectionBox(null);
}
catch
{
return;
}
Assert.Fail("Exception should have been thrown.");
}
[TestMethod]
public void Test_Toast_Xml_SelectionBox_DefaultSelectionBoxItemId_Value()
{
var selectionBox = new ToastSelectionBox("myId")
{
DefaultSelectionBoxItemId = "2"
};
AssertInputPayload("<input id='myId' type='selection' defaultInput='2' />", selectionBox);
}
[TestMethod]
public void Test_Toast_Xml_SelectionBox_Title_Value()
{
var selectionBox = new ToastSelectionBox("myId")
{
Title = "My title"
};
AssertInputPayload("<input id='myId' type='selection' title='My title' />", selectionBox);
}
[TestMethod]
public void Test_Toast_Xml_SelectionBoxItem()
{
var selectionBoxItem = new ToastSelectionBoxItem("myId", "My content");
AssertSelectionPayload("<selection id='myId' content='My content' />", selectionBoxItem);
}
[TestMethod]
public void Test_Toast_Xml_SelectionBoxItem_NullId()
{
try
{
new ToastSelectionBoxItem(null, "My content");
}
catch
{
return;
}
Assert.Fail("Exception should have been thrown.");
}
[TestMethod]
public void Test_Toast_Xml_SelectionBoxItem_NullContent()
{
try
{
new ToastSelectionBoxItem("myId", null);
}
catch
{
return;
}
Assert.Fail("Exception should have been thrown.");
}
[TestMethod]
public void Test_Toast_Xml_SelectionBoxItem_EmptyId()
{
var selectionBoxItem = new ToastSelectionBoxItem(string.Empty, "My content");
AssertSelectionPayload("<selection id='' content='My content' />", selectionBoxItem);
}
[TestMethod]
public void Test_Toast_Xml_SelectionBoxItem_EmptyContent()
{
var selectionBoxItem = new ToastSelectionBoxItem("myId", string.Empty);
AssertSelectionPayload("<selection id='myId' content='' />", selectionBoxItem);
}
[TestMethod]
public void Test_Toast_Header_AllValues()
{
AssertHeaderPayload("<header id='myId' title='My header' arguments='myArgs' activationType='protocol' />", new ToastHeader("myId", "My header", "myArgs")
{
ActivationType = ToastActivationType.Protocol
});
}
[TestMethod]
public void Test_Toast_Header_NullId()
{
try
{
new ToastHeader(null, "Title", "Args");
}
catch (ArgumentNullException)
{
try
{
new ToastHeader("Id", "Title", "Args")
{
Id = null
};
}
catch (ArgumentNullException)
{
return;
}
}
Assert.Fail("ArgumentNullException for Id should have been thrown.");
}
[TestMethod]
public void Test_Toast_Header_NullTitle()
{
try
{
new ToastHeader("id", null, "Args");
}
catch (ArgumentNullException)
{
try
{
new ToastHeader("Id", "Title", "Args")
{
Title = null
};
}
catch (ArgumentNullException)
{
return;
}
}
Assert.Fail("ArgumentNullException for Title should have been thrown.");
}
[TestMethod]
public void Test_Toast_Header_NullArguments()
{
try
{
new ToastHeader("id", "Title", null);
}
catch (ArgumentNullException)
{
try
{
new ToastHeader("id", "Title", "args")
{
Arguments = null
};
}
catch (ArgumentNullException)
{
return;
}
}
Assert.Fail("ArgumentNullException for Arguments should have been thrown.");
}
[TestMethod]
public void Test_Toast_Header_EmptyStrings()
{
AssertHeaderPayload("<header id='' title='' arguments='' />", new ToastHeader(string.Empty, string.Empty, string.Empty));
}
[TestMethod]
public void Test_Toast_Header_ActivationTypes()
{
AssertHeaderActivationType("foreground", ToastActivationType.Foreground);
try
{
AssertHeaderActivationType("background", ToastActivationType.Background);
throw new Exception("ArgumentException should have been thrown, since activation type of background isn't allowed.");
}
catch (ArgumentException)
{
}
AssertHeaderActivationType("protocol", ToastActivationType.Protocol);
}
[TestMethod]
public void Test_Toast_DisplayTimestamp()
{
AssertPayload("<toast displayTimestamp='2016-10-19T09:00:00Z' />", new ToastContent()
{
DisplayTimestamp = new DateTime(2016, 10, 19, 9, 0, 0, DateTimeKind.Utc)
});
AssertPayload("<toast displayTimestamp='2016-10-19T09:00:00-08:00' />", new ToastContent()
{
DisplayTimestamp = new DateTimeOffset(2016, 10, 19, 9, 0, 0, TimeSpan.FromHours(-8))
});
// If devs use DateTime.Now, or directly use ticks (like this code), they can actually end up with a seconds decimal
// value that is more than 3 decimal places. The platform notification parser will fail if there are
// more than three decimal places. Hence this test normally would produce "2017-04-04T10:28:34.7047925Z"
// but we've added code to ensure it strips to only at most 3 decimal places.
AssertPayload("<toast displayTimestamp='2017-04-04T10:28:34.704Z' />", new ToastContent()
{
DisplayTimestamp = new DateTimeOffset(636268985147047925, TimeSpan.FromHours(0))
});
}
[TestMethod]
public void Test_Toast_Button_ActivationOptions()
{
AssertButtonPayload("<action content='My content' arguments='myArgs' activationType='protocol' afterActivationBehavior='pendingUpdate' protocolActivationTargetApplicationPfn='Microsoft.Settings' />", new ToastButton("My content", "myArgs")
{
ActivationType = ToastActivationType.Protocol,
ActivationOptions = new ToastActivationOptions()
{
AfterActivationBehavior = ToastAfterActivationBehavior.PendingUpdate,
ProtocolActivationTargetApplicationPfn = "Microsoft.Settings"
}
});
// Empty | Test_Toast_Xml |
csharp | unoplatform__uno | src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml_Media_Imaging/Given_BitmapSource.cs | {
"start": 7689,
"end": 8484
} | public class ____ : Stream
{
public override void Flush() => throw new Given_BitmapSource_Exception();
public override int Read(byte[] buffer, int offset, int count) => throw new Given_BitmapSource_Exception();
public override long Seek(long offset, SeekOrigin origin) => throw new Given_BitmapSource_Exception();
public override void SetLength(long value) => throw new Given_BitmapSource_Exception();
public override void Write(byte[] buffer, int offset, int count) => throw new Given_BitmapSource_Exception();
public override bool CanRead { get; } = true;
public override bool CanSeek { get; } = true;
public override bool CanWrite { get; }
public override long Length { get; } = 1024;
public override long Position { get; set; }
}
}
}
| Given_BitmapSource_Stream |
csharp | dotnet__aspnetcore | src/SignalR/perf/Microbenchmarks/DefaultHubDispatcherBenchmark.cs | {
"start": 3813,
"end": 15034
} | public class ____ : Hub
{
public void Invocation()
{
}
public Task InvocationAsync()
{
return Task.CompletedTask;
}
public int InvocationReturnValue()
{
return 1;
}
public Task<int> InvocationReturnAsync()
{
return Task.FromResult(1);
}
public ValueTask<int> InvocationValueTaskAsync()
{
return new ValueTask<int>(1);
}
public ChannelReader<int> StreamChannelReader()
{
var channel = Channel.CreateUnbounded<int>();
channel.Writer.Complete();
return channel;
}
public Task<ChannelReader<int>> StreamChannelReaderAsync()
{
var channel = Channel.CreateUnbounded<int>();
channel.Writer.Complete();
return Task.FromResult<ChannelReader<int>>(channel);
}
public ValueTask<ChannelReader<int>> StreamChannelReaderValueTaskAsync()
{
var channel = Channel.CreateUnbounded<int>();
channel.Writer.Complete();
return new ValueTask<ChannelReader<int>>(channel);
}
public ChannelReader<int> StreamChannelReaderCount(int count)
{
var channel = Channel.CreateUnbounded<int>();
_ = Task.Run(async () =>
{
for (var i = 0; i < count; i++)
{
await channel.Writer.WriteAsync(i);
}
channel.Writer.Complete();
});
return channel.Reader;
}
public async IAsyncEnumerable<int> StreamIAsyncEnumerableCount(int count)
{
await Task.Yield();
for (var i = 0; i < count; i++)
{
yield return i;
}
}
public async IAsyncEnumerable<int> StreamIAsyncEnumerableCountCompletedTask(int count)
{
await Task.CompletedTask;
for (var i = 0; i < count; i++)
{
yield return i;
}
}
public async Task UploadStream(ChannelReader<string> channelReader)
{
while (await channelReader.WaitToReadAsync())
{
while (channelReader.TryRead(out var item))
{
}
}
}
public async Task UploadStreamIAsynEnumerable(IAsyncEnumerable<string> stream)
{
await foreach (var item in stream)
{
}
}
}
[Benchmark]
public Task Invocation()
{
return _dispatcher.DispatchMessageAsync(_connectionContext, new InvocationMessage("123", "Invocation", Array.Empty<object>()));
}
[Benchmark]
public Task InvocationAsync()
{
return _dispatcher.DispatchMessageAsync(_connectionContext, new InvocationMessage("123", "InvocationAsync", Array.Empty<object>()));
}
[Benchmark]
public Task InvocationReturnValue()
{
return _dispatcher.DispatchMessageAsync(_connectionContext, new InvocationMessage("123", "InvocationReturnValue", Array.Empty<object>()));
}
[Benchmark]
public Task InvocationReturnAsync()
{
return _dispatcher.DispatchMessageAsync(_connectionContext, new InvocationMessage("123", "InvocationReturnAsync", Array.Empty<object>()));
}
[Benchmark]
public Task InvocationValueTaskAsync()
{
return _dispatcher.DispatchMessageAsync(_connectionContext, new InvocationMessage("123", "InvocationValueTaskAsync", Array.Empty<object>()));
}
[Benchmark]
public Task StreamChannelReader()
{
return _dispatcher.DispatchMessageAsync(_connectionContext, new StreamInvocationMessage("123", "StreamChannelReader", Array.Empty<object>()));
}
[Benchmark]
public Task StreamChannelReaderAsync()
{
return _dispatcher.DispatchMessageAsync(_connectionContext, new StreamInvocationMessage("123", "StreamChannelReaderAsync", Array.Empty<object>()));
}
[Benchmark]
public Task StreamChannelReaderValueTaskAsync()
{
return _dispatcher.DispatchMessageAsync(_connectionContext, new StreamInvocationMessage("123", "StreamChannelReaderValueTaskAsync", Array.Empty<object>()));
}
[Benchmark]
public async Task StreamChannelReaderCount_Zero()
{
await _dispatcher.DispatchMessageAsync(_connectionContext, new StreamInvocationMessage("123", "StreamChannelReaderCount", new object[] { 0 }));
await (_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted.Task;
(_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted = new TaskCompletionSource();
}
[Benchmark]
public async Task StreamIAsyncEnumerableCount_Zero()
{
await _dispatcher.DispatchMessageAsync(_connectionContext, new StreamInvocationMessage("123", "StreamIAsyncEnumerableCount", new object[] { 0 }));
await (_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted.Task;
(_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted = new TaskCompletionSource();
}
[Benchmark]
public async Task StreamIAsyncEnumerableCompletedTaskCount_Zero()
{
await _dispatcher.DispatchMessageAsync(_connectionContext, new StreamInvocationMessage("123", "StreamIAsyncEnumerableCountCompletedTask", new object[] { 0 }));
await (_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted.Task;
(_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted = new TaskCompletionSource();
}
[Benchmark]
public async Task StreamChannelReaderCount_One()
{
await _dispatcher.DispatchMessageAsync(_connectionContext, new StreamInvocationMessage("123", "StreamChannelReaderCount", new object[] { 1 }));
await (_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted.Task;
(_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted = new TaskCompletionSource();
}
[Benchmark]
public async Task StreamIAsyncEnumerableCount_One()
{
await _dispatcher.DispatchMessageAsync(_connectionContext, new StreamInvocationMessage("123", "StreamIAsyncEnumerableCount", new object[] { 1 }));
await (_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted.Task;
(_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted = new TaskCompletionSource();
}
[Benchmark]
public async Task StreamIAsyncEnumerableCompletedTaskCount_One()
{
await _dispatcher.DispatchMessageAsync(_connectionContext, new StreamInvocationMessage("123", "StreamIAsyncEnumerableCountCompletedTask", new object[] { 1 }));
await (_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted.Task;
(_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted = new TaskCompletionSource();
}
[Benchmark]
public async Task StreamChannelReaderCount_Thousand()
{
await _dispatcher.DispatchMessageAsync(_connectionContext, new StreamInvocationMessage("123", "StreamChannelReaderCount", new object[] { 1000 }));
await (_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted.Task;
(_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted = new TaskCompletionSource();
}
[Benchmark]
public async Task StreamIAsyncEnumerableCount_Thousand()
{
await _dispatcher.DispatchMessageAsync(_connectionContext, new StreamInvocationMessage("123", "StreamIAsyncEnumerableCount", new object[] { 1000 }));
await (_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted.Task;
(_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted = new TaskCompletionSource();
}
[Benchmark]
public async Task StreamIAsyncEnumerableCompletedTaskCount_Thousand()
{
await _dispatcher.DispatchMessageAsync(_connectionContext, new StreamInvocationMessage("123", "StreamIAsyncEnumerableCountCompletedTask", new object[] { 1000 }));
await (_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted.Task;
(_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted = new TaskCompletionSource();
}
[Benchmark]
public async Task UploadStream_One()
{
await _dispatcher.DispatchMessageAsync(_connectionContext, new InvocationMessage("123", nameof(TestHub.UploadStream), Array.Empty<object>(), streamIds: new string[] { "1" }));
await _dispatcher.DispatchMessageAsync(_connectionContext, new StreamItemMessage("1", "test"));
await _dispatcher.DispatchMessageAsync(_connectionContext, CompletionMessage.Empty("1"));
await (_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted.Task;
(_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted = new TaskCompletionSource();
}
[Benchmark]
public async Task UploadStreamIAsyncEnumerable_One()
{
await _dispatcher.DispatchMessageAsync(_connectionContext, new InvocationMessage("123", nameof(TestHub.UploadStreamIAsynEnumerable), Array.Empty<object>(), streamIds: new string[] { "1" }));
await _dispatcher.DispatchMessageAsync(_connectionContext, new StreamItemMessage("1", "test"));
await _dispatcher.DispatchMessageAsync(_connectionContext, CompletionMessage.Empty("1"));
await (_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted.Task;
(_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted = new TaskCompletionSource();
}
[Benchmark]
public async Task UploadStream_Thousand()
{
await _dispatcher.DispatchMessageAsync(_connectionContext, new InvocationMessage("123", nameof(TestHub.UploadStream), Array.Empty<object>(), streamIds: new string[] { "1" }));
for (var i = 0; i < 1000; ++i)
{
await _dispatcher.DispatchMessageAsync(_connectionContext, new StreamItemMessage("1", "test"));
}
await _dispatcher.DispatchMessageAsync(_connectionContext, CompletionMessage.Empty("1"));
await (_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted.Task;
(_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted = new TaskCompletionSource();
}
[Benchmark]
public async Task UploadStreamIAsyncEnumerable_Thousand()
{
await _dispatcher.DispatchMessageAsync(_connectionContext, new InvocationMessage("123", nameof(TestHub.UploadStreamIAsynEnumerable), Array.Empty<object>(), streamIds: new string[] { "1" }));
for (var i = 0; i < 1000; ++i)
{
await _dispatcher.DispatchMessageAsync(_connectionContext, new StreamItemMessage("1", "test"));
}
await _dispatcher.DispatchMessageAsync(_connectionContext, CompletionMessage.Empty("1"));
await (_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted.Task;
(_connectionContext as NoErrorHubConnectionContext).ReceivedCompleted = new TaskCompletionSource();
}
}
| TestHub |
csharp | dotnet__maui | src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/CollectionViewUI.CollectionViewVisibility.cs | {
"start": 115,
"end": 821
} | public class ____ : _IssuesUITest
{
const string Success = "Success";
const string Show = "Show";
public CollectionViewVisibilityUITests(TestDevice device)
: base(device)
{
}
public override string Issue => "iOS application suspended at UICollectionViewFlowLayout.PrepareLayout() when using IsVisible = false";
// InitiallyInvisbleCollectionViewSurvivesiOSLayoutNonsense(src\Compatibility\ControlGallery\src\Issues.Shared\Issue12714.cs)
[Test]
[Category(UITestCategories.CollectionView)]
public void InitiallyInvisbleCollectionViewSurvivesiOSLayoutNonsense()
{
App.WaitForElement(Show);
App.Click(Show);
App.WaitForElement(Success);
}
}
} | CollectionViewVisibilityUITests |
csharp | AvaloniaUI__Avalonia | tests/Avalonia.Markup.Xaml.UnitTests/Xaml/ParentStackProviderTests.cs | {
"start": 1714,
"end": 2687
} | public class ____
{
public object ProvideValue(IServiceProvider serviceProvider)
{
var parentsProvider = serviceProvider.GetRequiredService<IAvaloniaXamlIlParentStackProvider>();
var eagerParentsProvider = Assert.IsAssignableFrom<IAvaloniaXamlIlEagerParentStackProvider>(parentsProvider);
var capturedParents = AvaloniaLocator.Current.GetRequiredService<CapturedParents>();
capturedParents.LazyParents = parentsProvider.Parents.ToArray();
capturedParents.EagerParents = EnumerateEagerParents(eagerParentsProvider);
return Colors.Blue;
}
private static object[] EnumerateEagerParents(IAvaloniaXamlIlEagerParentStackProvider provider)
{
var parents = new List<object>();
var enumerator = new EagerParentStackEnumerator(provider);
while (enumerator.TryGetNext() is { } parent)
parents.Add(parent);
return parents.ToArray();
}
}
| CapturingParentsMarkupExtension |
csharp | dotnet__aspnetcore | src/Http/WebUtilities/test/FormReaderAsyncTest.cs | {
"start": 224,
"end": 592
} | public class ____ : FormReaderTests
{
protected override async Task<Dictionary<string, StringValues>> ReadFormAsync(FormReader reader)
{
return await reader.ReadFormAsync();
}
protected override async Task<KeyValuePair<string, string>?> ReadPair(FormReader reader)
{
return await reader.ReadNextPairAsync();
}
}
| FormReaderAsyncTest |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.System/AppResourceGroupMemoryReport.cs | {
"start": 289,
"end": 3229
} | public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal AppResourceGroupMemoryReport()
{
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.System.AppMemoryUsageLevel CommitUsageLevel
{
get
{
throw new global::System.NotImplementedException("The member AppMemoryUsageLevel AppResourceGroupMemoryReport.CommitUsageLevel is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=AppMemoryUsageLevel%20AppResourceGroupMemoryReport.CommitUsageLevel");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public ulong CommitUsageLimit
{
get
{
throw new global::System.NotImplementedException("The member ulong AppResourceGroupMemoryReport.CommitUsageLimit is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=ulong%20AppResourceGroupMemoryReport.CommitUsageLimit");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public ulong PrivateCommitUsage
{
get
{
throw new global::System.NotImplementedException("The member ulong AppResourceGroupMemoryReport.PrivateCommitUsage is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=ulong%20AppResourceGroupMemoryReport.PrivateCommitUsage");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public ulong TotalCommitUsage
{
get
{
throw new global::System.NotImplementedException("The member ulong AppResourceGroupMemoryReport.TotalCommitUsage is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=ulong%20AppResourceGroupMemoryReport.TotalCommitUsage");
}
}
#endif
// Forced skipping of method Windows.System.AppResourceGroupMemoryReport.CommitUsageLimit.get
// Forced skipping of method Windows.System.AppResourceGroupMemoryReport.CommitUsageLevel.get
// Forced skipping of method Windows.System.AppResourceGroupMemoryReport.PrivateCommitUsage.get
// Forced skipping of method Windows.System.AppResourceGroupMemoryReport.TotalCommitUsage.get
}
}
| AppResourceGroupMemoryReport |
csharp | AvaloniaUI__Avalonia | samples/ControlCatalog/Pages/OpenGl/OpenGlLeasePage.xaml.cs | {
"start": 4807,
"end": 6531
} | public class ____
{
}
public OpenGlLeasePage()
{
InitializeComponent();
}
private void KnobsPropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs change)
{
if (change.Property == GlPageKnobs.YawProperty
|| change.Property == GlPageKnobs.RollProperty
|| change.Property == GlPageKnobs.PitchProperty
|| change.Property == GlPageKnobs.DiscoProperty)
_visual?.SendHandlerMessage(GetParameters());
}
Parameters GetParameters() => new()
{
Yaw = Knobs!.Yaw, Pitch = Knobs.Pitch, Roll = Knobs.Roll, Disco = Knobs.Disco
};
private void ViewportAttachedToVisualTree(object? sender, VisualTreeAttachmentEventArgs e)
{
var visual = ElementComposition.GetElementVisual(Viewport);
if(visual == null)
return;
_visual = visual.Compositor.CreateCustomVisual(new GlVisual(new OpenGlContent(), GetParameters()));
ElementComposition.SetElementChildVisual(Viewport, _visual);
UpdateSize(Bounds.Size);
}
private void UpdateSize(Size size)
{
if (_visual != null)
_visual.Size = new Vector(size.Width, size.Height);
}
protected override Size ArrangeOverride(Size finalSize)
{
var size = base.ArrangeOverride(finalSize);
UpdateSize(size);
return size;
}
private void ViewportDetachedFromVisualTree(object? sender, VisualTreeAttachmentEventArgs e)
{
_visual?.SendHandlerMessage(new DisposeMessage());
_visual = null;
ElementComposition.SetElementChildVisual(Viewport, null);
base.OnDetachedFromVisualTree(e);
}
}
| DisposeMessage |
csharp | MassTransit__MassTransit | src/MassTransit/Configuration/Configuration/Timeout/TimeoutConsumerConfigurationObserver.cs | {
"start": 62,
"end": 1065
} | public class ____<TConsumer> :
IConsumerConfigurationObserver
where TConsumer : class
{
readonly IConsumerConfigurator<TConsumer> _configurator;
readonly Action<ITimeoutConfigurator> _configure;
public TimeoutConsumerConfigurationObserver(IConsumerConfigurator<TConsumer> configurator, Action<ITimeoutConfigurator> configure)
{
_configurator = configurator;
_configure = configure;
}
void IConsumerConfigurationObserver.ConsumerConfigured<T>(IConsumerConfigurator<T> configurator)
{
}
void IConsumerConfigurationObserver.ConsumerMessageConfigured<T, TMessage>(IConsumerMessageConfigurator<T, TMessage> configurator)
{
var specification = new TimeoutSpecification<TMessage>();
_configure?.Invoke(specification);
_configurator.Message<TMessage>(x => x.AddPipeSpecification(specification));
}
}
}
| TimeoutConsumerConfigurationObserver |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Api.Analyzers/test/TestFiles/ApiConventionAnalyzerIntegrationTest/NoDiagnosticsAreReturned_ForApiController_WhenMethodNeverReturns.cs | {
"start": 253,
"end": 427
} | public class ____ : ControllerBase
{
public IActionResult GetItem() => throw new NotImplementedException();
}
| NoDiagnosticsAreReturned_ForApiController_WhenMethodNeverReturns |
csharp | ChilliCream__graphql-platform | src/StrawberryShake/CodeGeneration/test/CodeGeneration.CSharp.Tests/Integration/AnyScalarDefaultSerializationTest.Client.cs | {
"start": 30295,
"end": 31589
} | public partial class ____ : global::StrawberryShake.IOperationResultDataInfo
{
private readonly global::System.Collections.Generic.IReadOnlyCollection<global::StrawberryShake.EntityId> _entityIds;
private readonly global::System.UInt64 _version;
public GetJsonResultInfo(global::System.Text.Json.JsonElement json, global::System.Collections.Generic.IReadOnlyCollection<global::StrawberryShake.EntityId> entityIds, global::System.UInt64 version)
{
Json = json;
_entityIds = entityIds ?? throw new global::System.ArgumentNullException(nameof(entityIds));
_version = version;
}
public global::System.Text.Json.JsonElement Json { get; }
public global::System.Collections.Generic.IReadOnlyCollection<global::StrawberryShake.EntityId> EntityIds => _entityIds;
public global::System.UInt64 Version => _version;
public global::StrawberryShake.IOperationResultDataInfo WithVersion(global::System.UInt64 version)
{
return new GetJsonResultInfo(Json, _entityIds, version);
}
}
// StrawberryShake.CodeGeneration.CSharp.Generators.JsonResultBuilderGenerator
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")]
| GetJsonResultInfo |
csharp | Testably__Testably.Abstractions | Tests/Testably.Abstractions.Tests/FileSystem/FileStream/AdjustTimesTests.cs | {
"start": 152,
"end": 17351
} | public partial class ____
{
[Theory]
[AutoData]
public async Task CopyTo_ShouldAdjustTimes(string path, byte[] bytes)
{
Skip.If(Test.IsNetFramework && FileSystem is RealFileSystem,
"Works unreliable on .NET Framework");
SkipIfLongRunningTestsShouldBeSkipped();
byte[] buffer = new byte[bytes.Length];
DateTime creationTimeStart = TimeSystem.DateTime.UtcNow;
FileSystem.File.WriteAllBytes(path, bytes);
DateTime creationTimeEnd = TimeSystem.DateTime.UtcNow;
TimeSystem.Thread.Sleep(FileTestHelper.AdjustTimesDelay);
using FileSystemStream stream = FileSystem.File.OpenRead(path);
using MemoryStream destination = new(buffer);
DateTime updateTime = TimeSystem.DateTime.UtcNow;
stream.CopyTo(destination);
destination.Flush();
DateTime lastAccessTime = WaitToBeUpdatedToAfter(
() => FileSystem.File.GetLastAccessTimeUtc(path), updateTime);
DateTime creationTime = FileSystem.File.GetCreationTimeUtc(path);
DateTime lastWriteTime = FileSystem.File.GetLastWriteTimeUtc(path);
if (Test.RunsOnWindows)
{
await That(creationTime).IsBetween(creationTimeStart).And(creationTimeEnd)
.Within(TimeComparison.Tolerance);
await That(lastAccessTime).IsBetween(creationTimeStart).And(creationTimeEnd)
.Within(TimeComparison.Tolerance);
}
else
{
await That(lastAccessTime).IsOnOrAfter(updateTime.ApplySystemClockTolerance());
}
await That(lastWriteTime).IsBetween(creationTimeStart).And(creationTimeEnd)
.Within(TimeComparison.Tolerance);
}
#if FEATURE_SPAN
[Theory]
[AutoData]
public async Task Read_AsSpan_ShouldAdjustTimes(string path, byte[] bytes)
{
SkipIfLongRunningTestsShouldBeSkipped();
byte[] buffer = new byte[2];
DateTime creationTimeStart = TimeSystem.DateTime.UtcNow;
FileSystem.File.WriteAllBytes(path, bytes);
DateTime creationTimeEnd = TimeSystem.DateTime.UtcNow;
TimeSystem.Thread.Sleep(FileTestHelper.AdjustTimesDelay);
DateTime updateTime = TimeSystem.DateTime.UtcNow;
using FileSystemStream stream = FileSystem.File.OpenRead(path);
_ = stream.Read(buffer.AsSpan());
DateTime lastAccessTime = WaitToBeUpdatedToAfter(
() => FileSystem.File.GetLastAccessTimeUtc(path), updateTime);
DateTime creationTime = FileSystem.File.GetCreationTimeUtc(path);
DateTime lastWriteTime = FileSystem.File.GetLastWriteTimeUtc(path);
if (Test.RunsOnWindows)
{
await That(creationTime).IsBetween(creationTimeStart).And(creationTimeEnd).Within(TimeComparison.Tolerance);
await That(lastAccessTime).IsBetween(creationTimeStart).And(creationTimeEnd).Within(TimeComparison.Tolerance);
}
else
{
await That(lastAccessTime).IsOnOrAfter(updateTime.ApplySystemClockTolerance());
}
await That(lastWriteTime).IsBetween(creationTimeStart).And(creationTimeEnd).Within(TimeComparison.Tolerance);
}
#endif
[Theory]
[AutoData]
public async Task Read_ShouldAdjustTimes(string path, byte[] bytes)
{
Skip.If(Test.IsNetFramework && FileSystem is RealFileSystem,
"Works unreliable on .NET Framework");
SkipIfLongRunningTestsShouldBeSkipped();
byte[] buffer = new byte[2];
DateTime creationTimeStart = TimeSystem.DateTime.UtcNow;
FileSystem.File.WriteAllBytes(path, bytes);
DateTime creationTimeEnd = TimeSystem.DateTime.UtcNow;
TimeSystem.Thread.Sleep(FileTestHelper.AdjustTimesDelay);
DateTime updateTime = TimeSystem.DateTime.UtcNow;
using FileSystemStream stream = FileSystem.File.OpenRead(path);
_ = stream.Read(buffer, 0, 2);
DateTime lastAccessTime = WaitToBeUpdatedToAfter(
() => FileSystem.File.GetLastAccessTimeUtc(path), updateTime);
DateTime creationTime = FileSystem.File.GetCreationTimeUtc(path);
DateTime lastWriteTime = FileSystem.File.GetLastWriteTimeUtc(path);
if (Test.RunsOnWindows)
{
await That(creationTime).IsBetween(creationTimeStart).And(creationTimeEnd)
.Within(TimeComparison.Tolerance);
await That(lastAccessTime).IsBetween(creationTimeStart).And(creationTimeEnd)
.Within(TimeComparison.Tolerance);
}
else
{
await That(lastAccessTime).IsOnOrAfter(updateTime.ApplySystemClockTolerance());
}
await That(lastWriteTime).IsBetween(creationTimeStart).And(creationTimeEnd)
.Within(TimeComparison.Tolerance);
}
#if FEATURE_SPAN
[Theory]
[AutoData]
public async Task ReadAsync_AsMemory_ShouldAdjustTimes(string path, byte[] bytes)
{
SkipIfLongRunningTestsShouldBeSkipped();
byte[] buffer = new byte[2];
DateTime creationTimeStart = TimeSystem.DateTime.UtcNow;
await FileSystem.File.WriteAllBytesAsync(path, bytes, TestContext.Current.CancellationToken);
DateTime creationTimeEnd = TimeSystem.DateTime.UtcNow;
await TimeSystem.Task.Delay(FileTestHelper.AdjustTimesDelay, TestContext.Current.CancellationToken);
DateTime updateTime = TimeSystem.DateTime.UtcNow;
await using FileSystemStream stream = FileSystem.File.OpenRead(path);
_ = await stream.ReadAsync(buffer.AsMemory(), TestContext.Current.CancellationToken);
DateTime lastAccessTime = WaitToBeUpdatedToAfter(
() => FileSystem.File.GetLastAccessTimeUtc(path), updateTime);
DateTime creationTime = FileSystem.File.GetCreationTimeUtc(path);
DateTime lastWriteTime = FileSystem.File.GetLastWriteTimeUtc(path);
if (Test.RunsOnWindows)
{
await That(creationTime).IsBetween(creationTimeStart).And(creationTimeEnd).Within(TimeComparison.Tolerance);
await That(lastAccessTime).IsBetween(creationTimeStart).And(creationTimeEnd).Within(TimeComparison.Tolerance);
}
else
{
await That(lastAccessTime).IsOnOrAfter(updateTime.ApplySystemClockTolerance());
}
await That(lastWriteTime).IsBetween(creationTimeStart).And(creationTimeEnd).Within(TimeComparison.Tolerance);
}
#endif
#if FEATURE_FILESYSTEM_ASYNC
[Theory]
[AutoData]
public async Task ReadAsync_ShouldAdjustTimes(string path, byte[] bytes)
{
Skip.If(Test.IsNetFramework && FileSystem is RealFileSystem,
"Works unreliable on .NET Framework");
SkipIfLongRunningTestsShouldBeSkipped();
byte[] buffer = new byte[2];
DateTime creationTimeStart = TimeSystem.DateTime.UtcNow;
await FileSystem.File.WriteAllBytesAsync(path, bytes, TestContext.Current.CancellationToken);
DateTime creationTimeEnd = TimeSystem.DateTime.UtcNow;
await TimeSystem.Task.Delay(FileTestHelper.AdjustTimesDelay, TestContext.Current.CancellationToken);
DateTime updateTime = TimeSystem.DateTime.UtcNow;
await using FileSystemStream stream = FileSystem.File.OpenRead(path);
#pragma warning disable CA1835
_ = await stream.ReadAsync(buffer, 0, 2, TestContext.Current.CancellationToken);
#pragma warning restore CA1835
DateTime lastAccessTime = WaitToBeUpdatedToAfter(
() => FileSystem.File.GetLastAccessTimeUtc(path), updateTime);
DateTime creationTime = FileSystem.File.GetCreationTimeUtc(path);
DateTime lastWriteTime = FileSystem.File.GetLastWriteTimeUtc(path);
if (Test.RunsOnWindows)
{
await That(creationTime).IsBetween(creationTimeStart).And(creationTimeEnd).Within(TimeComparison.Tolerance);
await That(lastAccessTime).IsBetween(creationTimeStart).And(creationTimeEnd).Within(TimeComparison.Tolerance);
}
else
{
await That(lastAccessTime).IsOnOrAfter(updateTime.ApplySystemClockTolerance());
}
await That(lastWriteTime).IsBetween(creationTimeStart).And(creationTimeEnd).Within(TimeComparison.Tolerance);
}
#endif
[Theory]
[AutoData]
public async Task ReadByte_ShouldAdjustTimes(string path, byte[] bytes)
{
Skip.If(Test.IsNetFramework && FileSystem is RealFileSystem,
"Works unreliable on .NET Framework");
SkipIfLongRunningTestsShouldBeSkipped();
DateTime creationTimeStart = TimeSystem.DateTime.UtcNow;
FileSystem.File.WriteAllBytes(path, bytes);
DateTime creationTimeEnd = TimeSystem.DateTime.UtcNow;
TimeSystem.Thread.Sleep(FileTestHelper.AdjustTimesDelay);
DateTime updateTime = TimeSystem.DateTime.UtcNow;
using FileSystemStream stream = FileSystem.File.OpenRead(path);
stream.ReadByte();
DateTime lastAccessTime = WaitToBeUpdatedToAfter(
() => FileSystem.File.GetLastAccessTimeUtc(path), updateTime);
DateTime creationTime = FileSystem.File.GetCreationTimeUtc(path);
DateTime lastWriteTime = FileSystem.File.GetLastWriteTimeUtc(path);
if (Test.RunsOnWindows)
{
await That(creationTime).IsBetween(creationTimeStart).And(creationTimeEnd)
.Within(TimeComparison.Tolerance);
await That(lastAccessTime).IsBetween(creationTimeStart).And(creationTimeEnd)
.Within(TimeComparison.Tolerance);
}
else
{
await That(lastAccessTime).IsOnOrAfter(updateTime.ApplySystemClockTolerance());
}
await That(lastWriteTime).IsBetween(creationTimeStart).And(creationTimeEnd)
.Within(TimeComparison.Tolerance);
}
[Theory]
[AutoData]
public async Task Seek_ShouldNotAdjustTimes(string path, byte[] bytes)
{
Skip.If(Test.IsNetFramework && FileSystem is RealFileSystem,
"Works unreliable on .NET Framework");
SkipIfLongRunningTestsShouldBeSkipped();
DateTime creationTimeStart = TimeSystem.DateTime.UtcNow;
FileSystem.File.WriteAllBytes(path, bytes);
DateTime creationTimeEnd = TimeSystem.DateTime.UtcNow;
TimeSystem.Thread.Sleep(FileTestHelper.AdjustTimesDelay);
using FileSystemStream stream = FileSystem.File.OpenWrite(path);
stream.Seek(2, SeekOrigin.Current);
DateTime creationTime = FileSystem.File.GetCreationTimeUtc(path);
DateTime lastAccessTime = FileSystem.File.GetLastAccessTimeUtc(path);
DateTime lastWriteTime = FileSystem.File.GetLastWriteTimeUtc(path);
if (Test.RunsOnWindows)
{
await That(creationTime).IsBetween(creationTimeStart).And(creationTimeEnd)
.Within(TimeComparison.Tolerance);
}
await That(lastAccessTime).IsBetween(creationTimeStart).And(creationTimeEnd)
.Within(TimeComparison.Tolerance);
await That(lastWriteTime).IsBetween(creationTimeStart).And(creationTimeEnd)
.Within(TimeComparison.Tolerance);
}
#if FEATURE_SPAN
[Theory]
[AutoData]
public async Task Write_AsSpan_ShouldAdjustTimes(string path, byte[] bytes)
{
SkipIfLongRunningTestsShouldBeSkipped();
DateTime creationTimeStart = TimeSystem.DateTime.UtcNow;
FileSystem.File.WriteAllBytes(path, Array.Empty<byte>());
DateTime creationTimeEnd = TimeSystem.DateTime.UtcNow;
TimeSystem.Thread.Sleep(FileTestHelper.AdjustTimesDelay);
DateTime updateTime = TimeSystem.DateTime.UtcNow;
using (FileSystemStream stream = FileSystem.File.OpenWrite(path))
{
stream.Write(bytes.AsSpan());
}
DateTime lastWriteTime = WaitToBeUpdatedToAfter(
() => FileSystem.File.GetLastWriteTimeUtc(path), updateTime);
DateTime creationTime = FileSystem.File.GetCreationTimeUtc(path);
DateTime lastAccessTime = FileSystem.File.GetLastAccessTimeUtc(path);
if (Test.RunsOnWindows)
{
await That(creationTime).IsBetween(creationTimeStart).And(creationTimeEnd).Within(TimeComparison.Tolerance);
await That(lastAccessTime).IsOnOrAfter(updateTime.ApplySystemClockTolerance());
}
else
{
await That(lastAccessTime).IsBetween(creationTimeStart).And(creationTimeEnd).Within(TimeComparison.Tolerance);
}
await That(lastWriteTime).IsOnOrAfter(updateTime.ApplySystemClockTolerance());
}
#endif
[Theory]
[AutoData]
public async Task Write_ShouldAdjustTimes(string path, byte[] bytes)
{
Skip.If(Test.IsNetFramework && FileSystem is RealFileSystem,
"Works unreliable on .NET Framework");
SkipIfLongRunningTestsShouldBeSkipped();
DateTime creationTimeStart = TimeSystem.DateTime.UtcNow;
FileSystem.File.WriteAllBytes(path, Array.Empty<byte>());
DateTime creationTimeEnd = TimeSystem.DateTime.UtcNow;
TimeSystem.Thread.Sleep(FileTestHelper.AdjustTimesDelay);
DateTime updateTime = TimeSystem.DateTime.UtcNow;
using (FileSystemStream stream = FileSystem.File.OpenWrite(path))
{
stream.Write(bytes, 0, 2);
}
DateTime lastWriteTime = WaitToBeUpdatedToAfter(
() => FileSystem.File.GetLastWriteTimeUtc(path), updateTime);
DateTime creationTime = FileSystem.File.GetCreationTimeUtc(path);
DateTime lastAccessTime = FileSystem.File.GetLastAccessTimeUtc(path);
if (Test.RunsOnWindows)
{
await That(creationTime).IsBetween(creationTimeStart).And(creationTimeEnd)
.Within(TimeComparison.Tolerance);
await That(lastAccessTime).IsOnOrAfter(updateTime.ApplySystemClockTolerance());
}
else
{
await That(lastAccessTime).IsBetween(creationTimeStart).And(creationTimeEnd)
.Within(TimeComparison.Tolerance);
}
await That(lastWriteTime).IsOnOrAfter(updateTime.ApplySystemClockTolerance());
}
#if FEATURE_SPAN
[Theory]
[AutoData]
public async Task WriteAsync_AsMemory_ShouldAdjustTimes(string path, byte[] bytes)
{
SkipIfLongRunningTestsShouldBeSkipped();
DateTime creationTimeStart = TimeSystem.DateTime.UtcNow;
await FileSystem.File.WriteAllBytesAsync(path, Array.Empty<byte>(), TestContext.Current.CancellationToken);
DateTime creationTimeEnd = TimeSystem.DateTime.UtcNow;
await TimeSystem.Task.Delay(FileTestHelper.AdjustTimesDelay, TestContext.Current.CancellationToken);
DateTime updateTime = TimeSystem.DateTime.UtcNow;
await using (FileSystemStream stream = FileSystem.File.OpenWrite(path))
{
await stream.WriteAsync(bytes.AsMemory(), TestContext.Current.CancellationToken);
}
DateTime lastWriteTime = WaitToBeUpdatedToAfter(
() => FileSystem.File.GetLastWriteTimeUtc(path), updateTime);
DateTime creationTime = FileSystem.File.GetCreationTimeUtc(path);
DateTime lastAccessTime = FileSystem.File.GetLastAccessTimeUtc(path);
if (Test.RunsOnWindows)
{
await That(creationTime).IsBetween(creationTimeStart).And( creationTimeEnd).Within(TimeComparison.Tolerance);
await That(lastAccessTime).IsOnOrAfter(updateTime.ApplySystemClockTolerance());
}
else
{
await That(lastAccessTime).IsBetween(creationTimeStart).And(creationTimeEnd).Within(TimeComparison.Tolerance);
}
await That(lastWriteTime).IsOnOrAfter(updateTime.ApplySystemClockTolerance());
}
#endif
#if FEATURE_FILESYSTEM_ASYNC
[Theory]
[AutoData]
public async Task WriteAsync_ShouldAdjustTimes(string path, byte[] bytes)
{
Skip.If(Test.IsNetFramework && FileSystem is RealFileSystem,
"Works unreliable on .NET Framework");
SkipIfLongRunningTestsShouldBeSkipped();
DateTime creationTimeStart = TimeSystem.DateTime.UtcNow;
await FileSystem.File.WriteAllBytesAsync(path, Array.Empty<byte>(), TestContext.Current.CancellationToken);
DateTime creationTimeEnd = TimeSystem.DateTime.UtcNow;
await TimeSystem.Task.Delay(FileTestHelper.AdjustTimesDelay, TestContext.Current.CancellationToken);
DateTime updateTime = TimeSystem.DateTime.UtcNow;
await using (FileSystemStream stream = FileSystem.File.OpenWrite(path))
{
#pragma warning disable CA1835
await stream.WriteAsync(bytes, 0, 2, TestContext.Current.CancellationToken);
#pragma warning restore CA1835
}
DateTime lastWriteTime = WaitToBeUpdatedToAfter(
() => FileSystem.File.GetLastWriteTimeUtc(path), updateTime);
DateTime creationTime = FileSystem.File.GetCreationTimeUtc(path);
DateTime lastAccessTime = FileSystem.File.GetLastAccessTimeUtc(path);
if (Test.RunsOnWindows)
{
await That(creationTime).IsBetween(creationTimeStart).And(creationTimeEnd).Within(TimeComparison.Tolerance);
await That(lastAccessTime).IsOnOrAfter(updateTime.ApplySystemClockTolerance());
}
else
{
await That(lastAccessTime).IsBetween(creationTimeStart).And(creationTimeEnd).Within(TimeComparison.Tolerance);
}
await That(lastWriteTime).IsOnOrAfter(updateTime.ApplySystemClockTolerance());
}
#endif
[Theory]
[AutoData]
public async Task WriteByte_ShouldAdjustTimes(string path, byte[] bytes, byte singleByte)
{
Skip.If(Test.IsNetFramework && FileSystem is RealFileSystem,
"Works unreliable on .NET Framework");
SkipIfLongRunningTestsShouldBeSkipped();
DateTime creationTimeStart = TimeSystem.DateTime.UtcNow;
FileSystem.File.WriteAllBytes(path, bytes);
DateTime creationTimeEnd = TimeSystem.DateTime.UtcNow;
TimeSystem.Thread.Sleep(FileTestHelper.AdjustTimesDelay);
DateTime updateTime = TimeSystem.DateTime.UtcNow;
using (FileSystemStream stream = FileSystem.File.OpenWrite(path))
{
stream.WriteByte(singleByte);
}
DateTime lastWriteTime = WaitToBeUpdatedToAfter(
() => FileSystem.File.GetLastWriteTimeUtc(path), updateTime);
DateTime creationTime = FileSystem.File.GetCreationTimeUtc(path);
DateTime lastAccessTime = FileSystem.File.GetLastAccessTimeUtc(path);
if (Test.RunsOnWindows)
{
await That(creationTime).IsBetween(creationTimeStart).And(creationTimeEnd)
.Within(TimeComparison.Tolerance);
await That(lastAccessTime).IsOnOrAfter(updateTime.ApplySystemClockTolerance());
}
else
{
await That(lastAccessTime).IsBetween(creationTimeStart).And(creationTimeEnd)
.Within(TimeComparison.Tolerance);
}
await That(lastWriteTime).IsOnOrAfter(updateTime.ApplySystemClockTolerance());
}
#region Helpers
private DateTime WaitToBeUpdatedToAfter(Func<DateTime> callback,
DateTime expectedAfter)
{
for (int i = 0; i < 20; i++)
{
DateTime time = callback();
if (time >= expectedAfter.ApplySystemClockTolerance())
{
return time;
}
TimeSystem.Thread.Sleep(100);
}
return callback();
}
#endregion
}
| AdjustTimesTests |
csharp | nopSolutions__nopCommerce | src/Presentation/Nop.Web.Framework/TagHelpers/Admin/NopTabContextItem.cs | {
"start": 98,
"end": 424
} | public partial class ____
{
/// <summary>
/// Title
/// </summary>
public string Title { set; get; }
/// <summary>
/// Content
/// </summary>
public string Content { set; get; }
/// <summary>
/// Is default tab
/// </summary>
public bool IsDefault { set; get; }
} | NopTabContextItem |
csharp | kgrzybek__modular-monolith-with-ddd | src/Modules/UserAccess/Infrastructure/IdentityServer/ResourceOwnerPasswordValidator.cs | {
"start": 314,
"end": 1368
} | internal class ____ : IResourceOwnerPasswordValidator
{
private readonly IUserAccessModule _userAccessModule;
public ResourceOwnerPasswordValidator(IUserAccessModule userAccessModule)
{
_userAccessModule = userAccessModule;
}
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
var authenticationResult = await _userAccessModule.ExecuteCommandAsync(
new AuthenticateCommand(context.UserName, context.Password));
if (!authenticationResult.IsAuthenticated)
{
context.Result = new GrantValidationResult(
TokenRequestErrors.InvalidGrant,
authenticationResult.AuthenticationError);
return;
}
context.Result = new GrantValidationResult(
authenticationResult.User.Id.ToString(),
"forms",
authenticationResult.User.Claims);
}
}
} | ResourceOwnerPasswordValidator |
csharp | dotnet__maui | src/Controls/tests/TestCases.HostApp/Issues/Issue30818.cs | {
"start": 288,
"end": 389
} | public class ____ : NavigationPage
{
public Issue30818() : base(new MainPage())
{
}
| Issue30818 |
csharp | kgrzybek__modular-monolith-with-ddd | src/Modules/Payments/Infrastructure/InternalCommands/InternalCommandEntityTypeConfiguration.cs | {
"start": 259,
"end": 628
} | internal class ____ : IEntityTypeConfiguration<InternalCommand>
{
public void Configure(EntityTypeBuilder<InternalCommand> builder)
{
builder.ToTable("InternalCommands", "payments");
builder.HasKey(b => b.Id);
builder.Property(b => b.Id).ValueGeneratedNever();
}
}
} | InternalCommandEntityTypeConfiguration |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/AutoQueryTests.cs | {
"start": 28567,
"end": 28785
} | public class ____
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[CustomSelect("Age * 2")]
public int? Age { get; set; }
}
| CustomSelectRockstar |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Language/test/Language.SyntaxTree.Tests/Utilities/SchemaSyntaxPrinterTests.cs | {
"start": 55,
"end": 4937
} | public class ____
{
[Fact]
public void Serialize_ObjectTypeDefNoIndent_InOutShouldBeTheSame()
{
// arrange
const string schema = "type Foo { bar: String baz: [Int] }";
var document = Utf8GraphQLParser.Parse(schema);
// act
var result = document.ToString(false);
// assert
Assert.Equal(schema, result);
}
[Fact]
public void Serialize_ObjectTypeDefWithIndent_OutHasIndentation()
{
// arrange
const string schema = "type Foo { bar: String baz: [Int] }";
var document = Utf8GraphQLParser.Parse(schema);
// act
var result = document.ToString();
// assert
result.MatchSnapshot();
}
[Fact]
public void Serialize_ObjectTypeDefWithArgsNoIndent_InOutShouldBeTheSame()
{
// arrange
const string schema = "type Foo { bar(a: Int = 1 b: Int): String }";
var document = Utf8GraphQLParser.Parse(schema);
// act
var result = document.ToString(false);
// assert
Assert.Equal(schema, result);
}
[Fact]
public void Serialize_ObjectTypeDefWithArgsWithIndent_OutHasIndentation()
{
// arrange
const string schema = "type Foo { bar(a: Int = 1 b: Int): String }";
var document = Utf8GraphQLParser.Parse(schema);
// act
var result = document.ToString();
// assert
result.MatchSnapshot();
}
[Fact]
public void Serialize_ObjectTypeDefWithDirectivesNoIndent_InOutShouldBeTheSame()
{
// arrange
const string schema = "type Foo @a(x: \"y\") { bar: String baz: [Int] } "
+ "type Foo @a @b { bar: String @foo "
+ "baz(a: String = \"abc\"): [Int] @foo @bar }";
var document = Utf8GraphQLParser.Parse(schema);
// act
var result = document.ToString(false);
// assert
Assert.Equal(schema, result);
}
[Fact]
public void Serialize_ObjectTypeDefWithDirectivesWithIndent_OutHasIndentation()
{
// arrange
const string schema = "type Foo @a(x: \"y\") { bar: String baz: [Int] } "
+ "type Foo @a @b { bar: String @foo "
+ "baz(a: String = \"abc\"): [Int] @foo @bar }";
var document = Utf8GraphQLParser.Parse(schema);
// act
var result = document.ToString();
// assert
result.MatchSnapshot();
}
[Fact]
public void Serialize_ObjectTypeDefWithDescriptionNoIndent_InOutShouldBeTheSame()
{
// arrange
const string schema = "\"abc\" type Foo @a { \"abc\" bar: String "
+ "\"abc\" baz: [Int] } "
+ "\"abc\" type Foo @a @b { \"abc\" bar: String @foo "
+ "\"abc\" baz(\"abc\" a: String = \"abc\"): [Int] @foo @bar }";
var document = Utf8GraphQLParser.Parse(schema);
// act
var result = document.ToString(false);
// assert
Assert.Equal(schema, result);
}
[Fact]
public void Serialize_ObjectTypeDefWithDescriptionWithIndent_OutHasIndentation()
{
// arrange
const string schema = "\"abc\" type Foo @a { \"abc\" bar: String "
+ "\"abc\" baz: [Int] } "
+ "\"abc\" type Foo @a @b { \"abc\" bar: String @foo "
+ "\"abc\" baz(\"abc\" a: String = \"abc\"): [Int] @foo @bar }";
var document = Utf8GraphQLParser.Parse(schema);
// act
var result = document.ToString();
// assert
result.MatchSnapshot();
}
[Fact]
public void Serialize_ObjectTypeImplementsXYZ_InOutShouldBeTheSame()
{
// arrange
const string schema = "type Foo implements X & Y & Z "
+ "{ bar: String baz: [Int] }";
var document = Utf8GraphQLParser.Parse(schema);
// act
var result = document.ToString(false);
// assert
Assert.Equal(schema, result);
}
[Fact]
public void Serialize_ObjectTypeImplementsXYZWithIndent_OutHasIndentation()
{
// arrange
const string schema = "type Foo implements X & Y & Z "
+ "{ bar: String baz: [Int] }";
var document = Utf8GraphQLParser.Parse(schema);
// act
var result = document.ToString();
// assert
result.MatchSnapshot();
}
[Fact]
public void Serialize_ObjectTypeExtensionDef_InOutShouldBeTheSame()
{
// arrange
const string schema = "extend type Foo { bar: String baz: [Int] }";
var document = Utf8GraphQLParser.Parse(schema);
// act
var result = document.ToString(false);
// assert
Assert.Equal(schema, result);
}
[Fact]
public void Serialize_InterfaceTypeDefNoIndent_InOutShouldBeTheSame()
{
// arrange
const string schema = " | SchemaSyntaxPrinterTests |
csharp | MonoGame__MonoGame | MonoGame.Framework/Platform/SDL/SDL2.cs | {
"start": 32233,
"end": 32551
} | struct ____
{
public EventType Type;
public uint Timestamp;
public uint WindowId;
public fixed byte Text[32];
public int Start;
public int Length;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe | TextEditingEvent |
csharp | icsharpcode__ILSpy | ILSpy.ReadyToRun/ReadyToRunOptionPage.xaml.cs | {
"start": 1385,
"end": 1539
} | partial class ____
{
public ReadyToRunOptionPage()
{
InitializeComponent();
}
}
[ExportOptionPage(Order = 40)]
[NonShared]
| ReadyToRunOptionPage |
csharp | duplicati__duplicati | Duplicati/Library/Logging/LambdaSupport.cs | {
"start": 2275,
"end": 3228
} | internal class ____ : ILogFilter
{
/// <summary>
/// The method to call for filtering
/// </summary>
private readonly Func<LogEntry, bool> m_handler;
/// <summary>
/// Initializes a new instance of the <see cref="T:Duplicati.Library.Logging.FunctionFilter"/> class.
/// </summary>
/// <param name="handler">The method to call for filtering.</param>
public FunctionFilter(Func<LogEntry, bool> handler)
{
m_handler = handler ?? throw new ArgumentNullException(nameof(handler));
}
/// <summary>
/// Determines if the element is accepted or nor
/// </summary>
/// <returns>A value indicating if the value is accepted or not.</returns>
/// <param name="entry">The log entry to filter.</param>
public bool Accepts(LogEntry entry)
{
return m_handler(entry);
}
}
}
| FunctionFilter |
csharp | dotnetcore__Util | test/Util.Ui.NgZorro.Tests/Segments/SegmentedTagHelperTest.cs | {
"start": 414,
"end": 5097
} | public partial class ____ : IDisposable {
/// <summary>
/// 输出工具
/// </summary>
private readonly ITestOutputHelper _output;
/// <summary>
/// TagHelper包装器
/// </summary>
private readonly TagHelperWrapper<Customer> _wrapper;
/// <summary>
/// 测试初始化
/// </summary>
public SegmentedTagHelperTest( ITestOutputHelper output ) {
_output = output;
_wrapper = new SegmentedTagHelper().ToWrapper<Customer>();
Id.SetId( "id" );
}
/// <summary>
/// 测试清理
/// </summary>
public void Dispose() {
NgZorroOptionsService.ClearOptions();
}
/// <summary>
/// 获取结果
/// </summary>
private string GetResult() {
var result = _wrapper.GetResult();
_output.WriteLine( result );
return result;
}
/// <summary>
/// 测试默认输出
/// </summary>
[Fact]
public void TestDefault() {
var result = new StringBuilder();
result.Append( "<nz-segmented></nz-segmented>" );
Assert.Equal( result.ToString(), GetResult() );
}
/// <summary>
/// 测试模型绑定
/// </summary>
[Fact]
public void TestNgModel() {
_wrapper.SetContextAttribute( AngularConst.NgModel, "a" );
var result = new StringBuilder();
result.Append( "<nz-segmented [(ngModel)]=\"a\"></nz-segmented>" );
Assert.Equal( result.ToString(), GetResult() );
}
/// <summary>
/// 测试禁用
/// </summary>
[Fact]
public void TestDisabled() {
_wrapper.SetContextAttribute( UiConst.Disabled, "true" );
var result = new StringBuilder();
result.Append( "<nz-segmented [nzDisabled]=\"true\"></nz-segmented>" );
Assert.Equal( result.ToString(), GetResult() );
}
/// <summary>
/// 测试大小
/// </summary>
[Fact]
public void TestSize() {
_wrapper.SetContextAttribute( UiConst.Size, InputSize.Large );
var result = new StringBuilder();
result.Append( "<nz-segmented nzSize=\"large\"></nz-segmented>" );
Assert.Equal( result.ToString(), GetResult() );
}
/// <summary>
/// 测试大小
/// </summary>
[Fact]
public void TestBindSize() {
_wrapper.SetContextAttribute( AngularConst.BindSize, "a" );
var result = new StringBuilder();
result.Append( "<nz-segmented [nzSize]=\"a\"></nz-segmented>" );
Assert.Equal( result.ToString(), GetResult() );
}
/// <summary>
/// 测试选项列表
/// </summary>
[Fact]
public void TestOptions() {
_wrapper.SetContextAttribute( UiConst.Options, "a" );
var result = new StringBuilder();
result.Append( "<nz-segmented [nzOptions]=\"a\"></nz-segmented>" );
Assert.Equal( result.ToString(), GetResult() );
}
/// <summary>
/// 测试将宽度调整为父元素宽度
/// </summary>
[Fact]
public void TestBlock() {
_wrapper.SetContextAttribute( UiConst.Block, "true" );
var result = new StringBuilder();
result.Append( "<nz-segmented [nzBlock]=\"true\"></nz-segmented>" );
Assert.Equal( result.ToString(), GetResult() );
}
/// <summary>
/// 测试自定义渲染选项
/// </summary>
[Fact]
public void TestLabelTemplate() {
_wrapper.SetContextAttribute( UiConst.LabelTemplate, "a" );
var result = new StringBuilder();
result.Append( "<nz-segmented [nzLabelTemplate]=\"a\"></nz-segmented>" );
Assert.Equal( result.ToString(), GetResult() );
}
/// <summary>
/// 测试内容
/// </summary>
[Fact]
public void TestContent() {
_wrapper.AppendContent( "a" );
var result = new StringBuilder();
result.Append( "<nz-segmented>a</nz-segmented>" );
Assert.Equal( result.ToString(), GetResult() );
}
/// <summary>
/// 测试模型变更事件
/// </summary>
[Fact]
public void TestOnModelChange() {
_wrapper.SetContextAttribute( UiConst.OnModelChange, "a" );
var result = new StringBuilder();
result.Append( "<nz-segmented (ngModelChange)=\"a\"></nz-segmented>" );
Assert.Equal( result.ToString(), GetResult() );
}
}
} | SegmentedTagHelperTest |
csharp | nunit__nunit | src/NUnitFramework/tests/Constraints/DictionaryContainsKeyConstraintTests.cs | {
"start": 327,
"end": 7608
} | public class ____
{
[Test]
public void SucceedsWhenKeyIsPresent()
{
var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } };
Assert.That(dictionary, new DictionaryContainsKeyConstraint("Hello"));
}
[Test]
public void SucceedsWhenKeyIsPresentUsingContainKey()
{
var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } };
Assert.That(dictionary, Does.ContainKey("Hola"));
}
[Test]
public void SucceedsWhenKeyIsNotPresentUsingContainKey()
{
var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } };
Assert.That(dictionary, Does.Not.ContainKey("NotKey"));
}
[Test]
public void FailsWhenKeyIsMissing()
{
var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } };
TestDelegate act = () => Assert.That(dictionary, new DictionaryContainsKeyConstraint("Hallo"));
Assert.That(act, Throws.Exception.TypeOf<AssertionException>());
}
[Test]
public void FailsWhenNotUsedAgainstADictionary()
{
List<KeyValuePair<string, string>> keyValuePairs = new List<KeyValuePair<string, string>>(
new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } });
TestDelegate act = () => Assert.That(keyValuePairs, new DictionaryContainsKeyConstraint("Hallo"));
Assert.That(act, Throws.ArgumentException.With.Message.Contains("ContainsKey"));
}
[Test]
public void WorksWithNonGenericDictionary()
{
var dictionary = new Hashtable { { "Hello", "World" }, { "Hola", "Mundo" } };
Assert.That(dictionary, new DictionaryContainsKeyConstraint("Hello"));
}
[Test]
public void SucceedsWhenKeyIsPresentWhenDictionaryUsingCustomComparer()
{
var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "Hello", "World" }, { "Hola", "Mundo" } };
Assert.That(dictionary, new DictionaryContainsKeyConstraint("hello"));
}
[Test]
public void SucceedsWhenKeyIsPresentUsingContainsKeyWhenDictionaryUsingCustomComparer()
{
var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "Hello", "World" }, { "Hola", "Mundo" } };
Assert.That(dictionary, Does.ContainKey("hola"));
}
[Test]
public void SucceedsWhenKeyIsPresentUsingContainsKeyWhenUsingLookupCustomComparer()
{
var list = new List<string> { "ALICE", "BOB", "CATHERINE" };
ILookup<string, string> lookup = list.ToLookup(x => x, StringComparer.OrdinalIgnoreCase);
Assert.That(lookup, Does.ContainKey("catherine"));
}
[Test]
public void SucceedsWhenKeyIsNotPresentUsingContainsKeyUsingLookupDefaultComparer()
{
var list = new List<string> { "ALICE", "BOB", "CATHERINE" };
ILookup<string, string> lookup = list.ToLookup(x => x);
Assert.That(lookup, !Does.ContainKey("alice"));
}
[Test]
public void SucceedsWhenKeyIsPresentUsingContainsKeyWhenUsingKeyedCollectionCustomComparer()
{
var list = new TestKeyedCollection(StringComparer.OrdinalIgnoreCase) { "ALICE", "BOB", "CALUM" };
Assert.That(list, Does.ContainKey("calum"));
}
[Test]
public void KeyIsNotPresentUsingContainsKeyUsingKeyedCollectionDefaultComparer()
{
var list = new TestKeyedCollection { "ALICE", "BOB", "CALUM" };
Assert.That(list, !Does.ContainKey("alice"));
}
[Test]
public void SucceedsWhenKeyIsPresentUsingContainsKeyUsingHashtableCustomComparer()
{
var table = new Hashtable(StringComparer.OrdinalIgnoreCase) { { "ALICE", "BOB" }, { "CALUM", "DENNIS" } };
Assert.That(table, Does.ContainKey("alice"));
}
[Test]
public void SucceedsWhenKeyIsPresentUsingContainsKeyUsingHashtableDefaultComparer()
{
var table = new Hashtable { { "ALICE", "BOB" }, { "CALUM", "DENNIS" } };
Assert.That(table, !Does.ContainKey("calum"));
}
[Test]
public void ShouldCallContainsKeysMethodWithTKeyParameterOnNewMethod()
{
var dictionary = new TestDictionaryGeneric<string, string> { { "ALICE", "BOB" }, { "CALUM", "DENNIS" } };
Assert.That(dictionary, Does.ContainKey("BOB"));
}
[Test]
public void FailsWhenKeyIsNull()
{
Assert.That(() => Assert.That(new Dictionary<string, string>(), Does.ContainKey(null!)),
Throws.TargetInvocationException.With.InnerException.InstanceOf<ArgumentNullException>());
}
[Test]
public void ShouldCallContainsKeysMethodOnDictionary()
{
var dictionary = new TestDictionary(20);
Assert.That(dictionary, Does.ContainKey(20));
Assert.That(dictionary, !Does.ContainKey(10));
}
[Test]
public void ShouldCallContainsKeysMethodOnPlainDictionary()
{
var dictionary = new TestNonGenericDictionary(99);
Assert.That(dictionary, Does.ContainKey(99));
Assert.That(dictionary, !Does.ContainKey(35));
}
[Test]
public void ShouldCallContainsKeysMethodOnObject()
{
var poco = new TestPlainContainsKey("David");
Assert.DoesNotThrow(() => Assert.That(poco, Does.ContainKey("David")));
}
[Test]
public void ShouldThrowWhenUsedOnObjectWithNonGenericContains()
{
var poco = new TestPlainObjectContainsNonGeneric("Peter");
Assert.Catch<ArgumentException>(() => Assert.That(poco, Does.ContainKey("Peter")));
}
[Test]
public void ShouldCallContainsWhenUsedOnObjectWithGenericContains()
{
var poco = new TestPlainObjectContainsGeneric<string>("Peter");
Assert.DoesNotThrow(() => Assert.That(poco, Does.ContainKey("Peter")));
}
[Test]
public void ShouldCallContainsKeysMethodOnReadOnlyInterface()
{
var dictionary = new TestReadOnlyDictionary("BOB");
Assert.That(dictionary, Does.ContainKey("BOB"));
Assert.That(dictionary, !Does.ContainKey("ALICE"));
}
[Test]
public void ShouldThrowWhenUsedWithISet()
{
var set = new TestSet();
Assert.Catch<ArgumentException>(() => Assert.That(set, Does.ContainKey("NotHappening")));
}
[Test]
public void ShouldCallContainsKeysMethodOnLookupInterface()
{
var dictionary = new TestLookup(20);
Assert.That(dictionary, Does.ContainKey(20));
Assert.That(dictionary, !Does.ContainKey(43));
}
#region Test Assets
| DictionaryContainsKeyConstraintTests |
csharp | dotnet__aspnetcore | src/Middleware/Diagnostics/test/UnitTests/ExceptionDetailsProviderTest.cs | {
"start": 11756,
"end": 13234
} | private class ____ : IFileInfo
{
private readonly MemoryStream _stream;
public TestFileInfo(IEnumerable<string> sourceCodeLines)
{
_stream = new MemoryStream();
using (var writer = new StreamWriter(_stream, Encoding.UTF8, 1024, leaveOpen: true))
{
foreach (var line in sourceCodeLines)
{
writer.WriteLine(line);
}
}
_stream.Seek(0, SeekOrigin.Begin);
}
public bool Exists
{
get
{
return true;
}
}
public bool IsDirectory
{
get
{
throw new NotImplementedException();
}
}
public DateTimeOffset LastModified
{
get
{
throw new NotImplementedException();
}
}
public long Length
{
get
{
throw new NotImplementedException();
}
}
public string Name
{
get
{
throw new NotImplementedException();
}
}
public string PhysicalPath
{
get
{
return null;
}
}
public Stream CreateReadStream()
{
return _stream;
}
}
| TestFileInfo |
csharp | RicoSuter__NSwag | src/NSwag.Sample.Common/FileType.cs | {
"start": 37,
"end": 132
} | public enum ____
{
Document = 0,
Audio = 1,
Video = 2
}
} | FileType |
csharp | smartstore__Smartstore | src/Smartstore.Web/Models/Customers/CustomerDownloadableProductsModel.cs | {
"start": 1164,
"end": 1437
} | public class ____
{
public int DownloadId { get; set; }
public string FileName { get; set; }
public Guid DownloadGuid { get; set; }
public string FileVersion { get; set; }
public string Changelog { get; set; }
}
}
| DownloadVersion |
csharp | dotnet__aspnetcore | src/Http/Authentication.Abstractions/src/AuthenticationToken.cs | {
"start": 252,
"end": 492
} | public class ____
{
/// <summary>
/// Name.
/// </summary>
public string Name { get; set; } = default!;
/// <summary>
/// Value.
/// </summary>
public string Value { get; set; } = default!;
}
| AuthenticationToken |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomJsonConverterGeneric.cs | {
"start": 1579,
"end": 2120
} | public class ____ : JsonConverter<Version>
{
public override void WriteJson(JsonWriter writer, Version value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
public override Version ReadJson(JsonReader reader, Type objectType, Version existingValue, bool hasExistingValue, JsonSerializer serializer)
{
string s = (string)reader.Value;
return new Version(s);
}
}
| VersionConverter |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack.Skia/SkiaImageProvider.cs | {
"start": 49,
"end": 1936
} | public class ____ : ImageProvider
{
public override Stream Resize(Stream stream, int newWidth, int newHeight)
{
using var img = SKBitmap.Decode(stream);
return ResizeToPng(img, newWidth, newHeight);
}
public Stream ResizeToPng(SKBitmap img, int newWidth, int newHeight)
{
if (newWidth != img.Width || newHeight != img.Height)
{
var ratioX = (double)newWidth / img.Width;
var ratioY = (double)newHeight / img.Height;
var ratio = Math.Max(ratioX, ratioY);
var width = (int)(img.Width * ratio);
var height = (int)(img.Height * ratio);
img = img.Resize(new SKImageInfo(width, height), SKFilterQuality.Medium);
if (img.Width != newWidth || img.Height != newHeight)
{
img = Crop(img, newWidth, newHeight); // resized + clipped
}
}
var pngStream = img.Encode(SKEncodedImageFormat.Png, 75).AsStream();
return pngStream;
}
public static SKBitmap Crop(SKBitmap img, int newWidth, int newHeight)
{
if (img.Width < newWidth)
newWidth = img.Width;
if (img.Height < newHeight)
newHeight = img.Height;
var startX = (Math.Max(img.Width, newWidth) - Math.Min(img.Width, newWidth)) / 2;
var startY = (Math.Max(img.Height, newHeight) - Math.Min(img.Height, newHeight)) / 2;
var croppedBitmap = new SKBitmap(newWidth, newHeight);
var source = new SKRect(startX, startY, newWidth + startX, newHeight + startY);
var dest = new SKRect(0, 0, newWidth, newHeight);
using var canvas = new SKCanvas(croppedBitmap);
canvas.Clear(SKColors.Transparent);
canvas.DrawBitmap(img, source, dest);
img.Dispose();
return croppedBitmap;
}
} | SkiaImageProvider |
csharp | dotnet__efcore | src/EFCore.Relational/Query/Internal/RelationalShapedQueryCompilingExpressionVisitorFactory.cs | {
"start": 644,
"end": 2750
} | public class ____ : IShapedQueryCompilingExpressionVisitorFactory
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public RelationalShapedQueryCompilingExpressionVisitorFactory(
ShapedQueryCompilingExpressionVisitorDependencies dependencies,
RelationalShapedQueryCompilingExpressionVisitorDependencies relationalDependencies)
{
Dependencies = dependencies;
RelationalDependencies = relationalDependencies;
}
/// <summary>
/// Dependencies for this service.
/// </summary>
protected virtual ShapedQueryCompilingExpressionVisitorDependencies Dependencies { get; }
/// <summary>
/// Relational provider-specific dependencies for this service.
/// </summary>
protected virtual RelationalShapedQueryCompilingExpressionVisitorDependencies RelationalDependencies { get; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[DebuggerStepThrough]
public virtual ShapedQueryCompilingExpressionVisitor Create(QueryCompilationContext queryCompilationContext)
=> new RelationalShapedQueryCompilingExpressionVisitor(
Dependencies,
RelationalDependencies,
queryCompilationContext);
}
| RelationalShapedQueryCompilingExpressionVisitorFactory |
csharp | dotnetcore__Util | src/Util.Data.Sql/Builders/Params/IGetParameter.cs | {
"start": 85,
"end": 292
} | public interface ____ {
/// <summary>
/// 获取Sql参数值
/// </summary>
/// <typeparam name="T">参数值类型</typeparam>
/// <param name="name">参数名</param>
T GetParam<T>( string name );
} | IGetParameter |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.Extensions.Tests/Protoc/Services.cs | {
"start": 251838,
"end": 258426
} | partial class ____ : pb::IMessage<AuditBase>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<AuditBase> _parser = new pb::MessageParser<AuditBase>(() => new AuditBase());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<AuditBase> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::ServiceStack.Extensions.Tests.Protoc.ServicesReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public AuditBase() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public AuditBase(AuditBase other) : this() {
createdDate_ = other.createdDate_ != null ? other.createdDate_.Clone() : null;
createdBy_ = other.createdBy_;
modifiedDate_ = other.modifiedDate_ != null ? other.modifiedDate_.Clone() : null;
modifiedBy_ = other.modifiedBy_;
deletedDate_ = other.deletedDate_ != null ? other.deletedDate_.Clone() : null;
deletedBy_ = other.deletedBy_;
switch (other.SubtypeCase) {
case SubtypeOneofCase.Booking:
Booking = other.Booking.Clone();
break;
case SubtypeOneofCase.RockstarAuditTenant:
RockstarAuditTenant = other.RockstarAuditTenant.Clone();
break;
}
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public AuditBase Clone() {
return new AuditBase(this);
}
/// <summary>Field number for the "CreatedDate" field.</summary>
public const int CreatedDateFieldNumber = 1;
private global::Google.Protobuf.WellKnownTypes.Timestamp createdDate_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Protobuf.WellKnownTypes.Timestamp CreatedDate {
get { return createdDate_; }
set {
createdDate_ = value;
}
}
/// <summary>Field number for the "CreatedBy" field.</summary>
public const int CreatedByFieldNumber = 2;
private string createdBy_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string CreatedBy {
get { return createdBy_; }
set {
createdBy_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "ModifiedDate" field.</summary>
public const int ModifiedDateFieldNumber = 3;
private global::Google.Protobuf.WellKnownTypes.Timestamp modifiedDate_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Protobuf.WellKnownTypes.Timestamp ModifiedDate {
get { return modifiedDate_; }
set {
modifiedDate_ = value;
}
}
/// <summary>Field number for the "ModifiedBy" field.</summary>
public const int ModifiedByFieldNumber = 4;
private string modifiedBy_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string ModifiedBy {
get { return modifiedBy_; }
set {
modifiedBy_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "DeletedDate" field.</summary>
public const int DeletedDateFieldNumber = 5;
private global::Google.Protobuf.WellKnownTypes.Timestamp deletedDate_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Protobuf.WellKnownTypes.Timestamp DeletedDate {
get { return deletedDate_; }
set {
deletedDate_ = value;
}
}
/// <summary>Field number for the "DeletedBy" field.</summary>
public const int DeletedByFieldNumber = 6;
private string deletedBy_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string DeletedBy {
get { return deletedBy_; }
set {
deletedBy_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "Booking" field.</summary>
public const int BookingFieldNumber = 64344587;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::ServiceStack.Extensions.Tests.Protoc.Booking Booking {
get { return subtypeCase_ == SubtypeOneofCase.Booking ? (global::ServiceStack.Extensions.Tests.Protoc.Booking) subtype_ : null; }
set {
subtype_ = value;
subtypeCase_ = value == null ? SubtypeOneofCase.None : SubtypeOneofCase.Booking;
}
}
/// <summary>Field number for the "RockstarAuditTenant" field.</summary>
public const int RockstarAuditTenantFieldNumber = 252248706;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::ServiceStack.Extensions.Tests.Protoc.RockstarAuditTenant RockstarAuditTenant {
get { return subtypeCase_ == SubtypeOneofCase.RockstarAuditTenant ? (global::ServiceStack.Extensions.Tests.Protoc.RockstarAuditTenant) subtype_ : null; }
set {
subtype_ = value;
subtypeCase_ = value == null ? SubtypeOneofCase.None : SubtypeOneofCase.RockstarAuditTenant;
}
}
private object subtype_;
/// <summary>Enum of possible cases for the "subtype" oneof.</summary>
| AuditBase |
csharp | dotnet__efcore | test/EFCore.Design.Tests/Scaffolding/Internal/CSharpEntityTypeGeneratorTest.cs | {
"start": 41563,
"end": 43318
} | public partial class ____
{
[Key]
public int Id { get; set; }
[Precision(10)]
public decimal A { get; set; }
[Precision(14, 3)]
public decimal B { get; set; }
[Precision(5)]
public DateTime C { get; set; }
[Precision(3)]
public DateTimeOffset D { get; set; }
}
""",
code.AdditionalFiles.Single(f => f.Path == "Entity.cs"));
},
model =>
{
var entitType = model.FindEntityType("TestNamespace.Entity");
Assert.Equal(10, entitType.GetProperty("A").GetPrecision());
Assert.Equal(14, entitType.GetProperty("B").GetPrecision());
Assert.Equal(3, entitType.GetProperty("B").GetScale());
Assert.Equal(5, entitType.GetProperty("C").GetPrecision());
Assert.Equal(3, entitType.GetProperty("D").GetPrecision());
});
[ConditionalFact]
public Task Comments_are_generated()
=> TestAsync(
modelBuilder => modelBuilder
.Entity(
"Entity",
x =>
{
x.ToTable(tb => tb.HasComment("Entity Comment"));
x.Property<int>("Id").HasComment("Property Comment");
})
,
new ModelCodeGenerationOptions { UseDataAnnotations = true },
code =>
{
AssertFileContents(
"""
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
namespace TestNamespace;
/// <summary>
/// Entity Comment
/// </summary>
| Entity |
csharp | SixLabors__Fonts | src/SixLabors.Fonts/Unicode/BidiData.cs | {
"start": 260,
"end": 6422
} | internal class ____
{
private ArrayBuilder<BidiCharacterType> types;
private ArrayBuilder<BidiPairedBracketType> pairedBracketTypes;
private ArrayBuilder<int> pairedBracketValues;
private ArrayBuilder<BidiCharacterType> savedTypes;
private ArrayBuilder<BidiPairedBracketType> savedPairedBracketTypes;
private ArrayBuilder<sbyte> tempLevelBuffer;
private readonly List<int> paragraphPositions = new();
public sbyte ParagraphEmbeddingLevel { get; private set; }
public bool HasBrackets { get; private set; }
public bool HasEmbeddings { get; private set; }
public bool HasIsolates { get; private set; }
/// <summary>
/// Gets the length of the data held by the BidiData
/// </summary>
public int Length => this.types.Length;
/// <summary>
/// Gets the bidi character type of each code point
/// </summary>
public ArraySlice<BidiCharacterType> Types { get; private set; }
/// <summary>
/// Gets the paired bracket type for each code point
/// </summary>
public ArraySlice<BidiPairedBracketType> PairedBracketTypes { get; private set; }
/// <summary>
/// Gets the paired bracket value for code point
/// </summary>
/// <remarks>
/// The paired bracket values are the code points
/// of each character where the opening code point
/// is replaced with the closing code point for easier
/// matching. Also, bracket code points are mapped
/// to their canonical equivalents
/// </remarks>
public ArraySlice<int> PairedBracketValues { get; private set; }
/// <summary>
/// Initialize with a text value.
/// </summary>
/// <param name="text">The text to process.</param>
/// <param name="paragraphEmbeddingLevel">The paragraph embedding level</param>
public void Init(ReadOnlySpan<char> text, sbyte paragraphEmbeddingLevel)
{
// Set working buffer sizes
// TODO: This allocates more than it should for some arrays.
int length = CodePoint.GetCodePointCount(text);
this.types.Length = length;
this.pairedBracketTypes.Length = length;
this.pairedBracketValues.Length = length;
this.paragraphPositions.Clear();
this.ParagraphEmbeddingLevel = paragraphEmbeddingLevel;
// Resolve the BidiCharacterType, paired bracket type and paired
// bracket values for all code points
this.HasBrackets = false;
this.HasEmbeddings = false;
this.HasIsolates = false;
int i = 0;
var codePointEnumerator = new SpanCodePointEnumerator(text);
while (codePointEnumerator.MoveNext())
{
CodePoint codePoint = codePointEnumerator.Current;
BidiClass bidi = CodePoint.GetBidiClass(codePoint);
// Look up BidiCharacterType
BidiCharacterType dir = bidi.CharacterType;
this.types[i] = dir;
switch (dir)
{
case BidiCharacterType.LeftToRightEmbedding:
case BidiCharacterType.LeftToRightOverride:
case BidiCharacterType.RightToLeftEmbedding:
case BidiCharacterType.RightToLeftOverride:
case BidiCharacterType.PopDirectionalFormat:
this.HasEmbeddings = true;
break;
case BidiCharacterType.LeftToRightIsolate:
case BidiCharacterType.RightToLeftIsolate:
case BidiCharacterType.FirstStrongIsolate:
case BidiCharacterType.PopDirectionalIsolate:
this.HasIsolates = true;
break;
}
// Lookup paired bracket types
BidiPairedBracketType pbt = bidi.PairedBracketType;
this.pairedBracketTypes[i] = pbt;
if (pbt == BidiPairedBracketType.Open)
{
// Opening bracket types can never have a null pairing.
bidi.TryGetPairedBracket(out CodePoint paired);
this.pairedBracketValues[i] = CodePoint.GetCanonicalType(paired).Value;
this.HasBrackets = true;
}
else if (pbt == BidiPairedBracketType.Close)
{
this.pairedBracketValues[i] = CodePoint.GetCanonicalType(codePoint).Value;
this.HasBrackets = true;
}
i++;
}
// Create slices on work buffers
this.Types = this.types.AsSlice();
this.PairedBracketTypes = this.pairedBracketTypes.AsSlice();
this.PairedBracketValues = this.pairedBracketValues.AsSlice();
}
/// <summary>
/// Save the Types and PairedBracketTypes of this bididata
/// </summary>
/// <remarks>
/// This is used when processing embedded style runs with
/// BidiCharacterType overrides. TextLayout saves the data,
/// overrides the style runs to neutral, processes the bidi
/// data for the entire paragraph and then restores this data
/// before processing the embedded runs.
/// </remarks>
public void SaveTypes()
{
// Capture the types data
this.savedTypes.Clear();
this.savedTypes.Add(this.types.AsSlice());
this.savedPairedBracketTypes.Clear();
this.savedPairedBracketTypes.Add(this.pairedBracketTypes.AsSlice());
}
/// <summary>
/// Restore the data saved by SaveTypes
/// </summary>
public void RestoreTypes()
{
this.types.Clear();
this.types.Add(this.savedTypes.AsSlice());
this.pairedBracketTypes.Clear();
this.pairedBracketTypes.Add(this.savedPairedBracketTypes.AsSlice());
}
/// <summary>
/// Gets a temporary level buffer. Used by TextLayout when
/// resolving style runs with different BidiCharacterType.
/// </summary>
/// <param name="length">Length of the required ExpandableBuffer</param>
/// <returns>An uninitialized level ExpandableBuffer</returns>
public ArraySlice<sbyte> GetTempLevelBuffer(int length)
{
this.tempLevelBuffer.Clear();
return this.tempLevelBuffer.Add(length, false);
}
}
| BidiData |
csharp | scriban__scriban | src/Scriban/Runtime/CustomFunction.Generated.cs | {
"start": 53017,
"end": 53802
} | private partial class ____ : DynamicCustomFunction
{
private delegate int InternalDelegate(object arg0);
private readonly InternalDelegate _delegate;
public Functionint_object(MethodInfo method) : base(method)
{
_delegate = (InternalDelegate)method.CreateDelegate(typeof(InternalDelegate));
}
public override object Invoke(TemplateContext context, ScriptNode callerContext, ScriptArray arguments, ScriptBlockStatement blockStatement)
{
var arg0 = (object)arguments[0];
return _delegate(arg0);
}
}
/// <summary>
/// Optimized custom function for: int (string)
/// </summary>
| Functionint_object |
csharp | dotnet__aspnetcore | src/Http/Authentication.Abstractions/src/IAuthenticationSchemeProvider.cs | {
"start": 320,
"end": 5263
} | public interface ____
{
/// <summary>
/// Returns all currently registered <see cref="AuthenticationScheme"/>s.
/// </summary>
/// <returns>All currently registered <see cref="AuthenticationScheme"/>s.</returns>
Task<IEnumerable<AuthenticationScheme>> GetAllSchemesAsync();
/// <summary>
/// Returns the <see cref="AuthenticationScheme"/> matching the name, or null.
/// </summary>
/// <param name="name">The name of the authenticationScheme.</param>
/// <returns>The scheme or null if not found.</returns>
Task<AuthenticationScheme?> GetSchemeAsync(string name);
/// <summary>
/// Returns the scheme that will be used by default for <see cref="IAuthenticationService.AuthenticateAsync(HttpContext, string)"/>.
/// This is typically specified via <see cref="AuthenticationOptions.DefaultAuthenticateScheme"/>.
/// Otherwise, this will fallback to <see cref="AuthenticationOptions.DefaultScheme"/>.
/// </summary>
/// <returns>The scheme that will be used by default for <see cref="IAuthenticationService.AuthenticateAsync(HttpContext, string)"/>.</returns>
Task<AuthenticationScheme?> GetDefaultAuthenticateSchemeAsync();
/// <summary>
/// Returns the scheme that will be used by default for <see cref="IAuthenticationService.ChallengeAsync(HttpContext, string, AuthenticationProperties)"/>.
/// This is typically specified via <see cref="AuthenticationOptions.DefaultChallengeScheme"/>.
/// Otherwise, this will fallback to <see cref="AuthenticationOptions.DefaultScheme"/>.
/// </summary>
/// <returns>The scheme that will be used by default for <see cref="IAuthenticationService.ChallengeAsync(HttpContext, string, AuthenticationProperties)"/>.</returns>
Task<AuthenticationScheme?> GetDefaultChallengeSchemeAsync();
/// <summary>
/// Returns the scheme that will be used by default for <see cref="IAuthenticationService.ForbidAsync(HttpContext, string, AuthenticationProperties)"/>.
/// This is typically specified via <see cref="AuthenticationOptions.DefaultForbidScheme"/>.
/// Otherwise, this will fallback to <see cref="GetDefaultChallengeSchemeAsync"/> .
/// </summary>
/// <returns>The scheme that will be used by default for <see cref="IAuthenticationService.ForbidAsync(HttpContext, string, AuthenticationProperties)"/>.</returns>
Task<AuthenticationScheme?> GetDefaultForbidSchemeAsync();
/// <summary>
/// Returns the scheme that will be used by default for <see cref="IAuthenticationService.SignInAsync(HttpContext, string, System.Security.Claims.ClaimsPrincipal, AuthenticationProperties)"/>.
/// This is typically specified via <see cref="AuthenticationOptions.DefaultSignInScheme"/>.
/// Otherwise, this will fallback to <see cref="AuthenticationOptions.DefaultScheme"/>.
/// </summary>
/// <returns>The scheme that will be used by default for <see cref="IAuthenticationService.SignInAsync(HttpContext, string, System.Security.Claims.ClaimsPrincipal, AuthenticationProperties)"/>.</returns>
Task<AuthenticationScheme?> GetDefaultSignInSchemeAsync();
/// <summary>
/// Returns the scheme that will be used by default for <see cref="IAuthenticationService.SignOutAsync(HttpContext, string, AuthenticationProperties)"/>.
/// This is typically specified via <see cref="AuthenticationOptions.DefaultSignOutScheme"/>.
/// Otherwise, this will fallback to <see cref="GetDefaultSignInSchemeAsync"/> .
/// </summary>
/// <returns>The scheme that will be used by default for <see cref="IAuthenticationService.SignOutAsync(HttpContext, string, AuthenticationProperties)"/>.</returns>
Task<AuthenticationScheme?> GetDefaultSignOutSchemeAsync();
/// <summary>
/// Registers a scheme for use by <see cref="IAuthenticationService"/>.
/// </summary>
/// <param name="scheme">The scheme.</param>
void AddScheme(AuthenticationScheme scheme);
/// <summary>
/// Registers a scheme for use by <see cref="IAuthenticationService"/>.
/// </summary>
/// <param name="scheme">The scheme.</param>
/// <returns>true if the scheme was added successfully.</returns>
bool TryAddScheme(AuthenticationScheme scheme)
{
try
{
AddScheme(scheme);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Removes a scheme, preventing it from being used by <see cref="IAuthenticationService"/>.
/// </summary>
/// <param name="name">The name of the authenticationScheme being removed.</param>
void RemoveScheme(string name);
/// <summary>
/// Returns the schemes in priority order for request handling.
/// </summary>
/// <returns>The schemes in priority order for request handling</returns>
Task<IEnumerable<AuthenticationScheme>> GetRequestHandlerSchemesAsync();
}
| IAuthenticationSchemeProvider |
csharp | dotnet__maui | src/Core/tests/DeviceTests/Handlers/Navigation/NavigationViewHandlerTests.Android.cs | {
"start": 467,
"end": 2065
} | public partial class ____
{
int GetNativeNavigationStackCount(NavigationViewHandler navigationViewHandler)
{
int i = 0;
var navController = navigationViewHandler.StackNavigationManager.NavHost.NavController;
navController.IterateBackStack(_ => i++);
return i;
}
Task CreateNavigationViewHandlerAsync(IStackNavigationView navigationView, Func<NavigationViewHandler, Task> action)
{
return InvokeOnMainThreadAsync(async () =>
{
var context = MauiProgram.DefaultContext;
var rootView = (context as AppCompatActivity).Window.DecorView as ViewGroup;
var linearLayoutCompat = new LinearLayoutCompat(context);
var fragmentManager = MauiContext.GetFragmentManager();
var viewFragment = new NavViewFragment(MauiContext);
try
{
linearLayoutCompat.Id = View.GenerateViewId();
fragmentManager
.BeginTransaction()
.Add(linearLayoutCompat.Id, viewFragment)
.Commit();
rootView.AddView(linearLayoutCompat);
await viewFragment.FinishedLoading;
var handler = CreateHandler<NavigationViewHandler>(navigationView, viewFragment.ScopedMauiContext);
if (navigationView is NavigationViewStub nvs && nvs.NavigationStack?.Count > 0)
{
navigationView.RequestNavigation(new NavigationRequest(nvs.NavigationStack, false));
await nvs.OnNavigationFinished;
}
await action(handler);
}
finally
{
rootView.RemoveView(linearLayoutCompat);
fragmentManager
.BeginTransaction()
.Remove(viewFragment)
.Commit();
}
});
}
| NavigationViewHandlerTests |
csharp | RicoSuter__NSwag | src/NSwag.CodeGeneration.TypeScript.Tests/TypeScriptDiscriminatorTests.cs | {
"start": 755,
"end": 850
} | public class ____ : Base
{
public string A { get; }
}
| OneChild |
csharp | dotnetcore__FreeSql | FreeSql.Tests/FreeSql.Tests/Firebird/Curd/FirebirdInsertOrUpdateTest.cs | {
"start": 151,
"end": 2731
} | public class ____
{
IFreeSql fsql => g.firebird;
[Fact]
public void InsertOrUpdate_OnlyPrimary()
{
fsql.Delete<tbiou01>().Where("1=1").ExecuteAffrows();
var iou = fsql.InsertOrUpdate<tbiou01>().SetSource(new tbiou01 { id = 1 });
var sql = iou.ToSql();
Assert.Equal(@"MERGE INTO ""TBIOU01"" t1
USING (SELECT FIRST 1 1 as ""ID"" FROM rdb$database ) t2 ON (t1.""ID"" = t2.""ID"")
WHEN NOT MATCHED THEN
insert (""ID"")
values (t2.""ID"")", sql);
Assert.Equal(1, iou.ExecuteAffrows());
iou = fsql.InsertOrUpdate<tbiou01>().SetSource(new tbiou01 { id = 1 });
sql = iou.ToSql();
Assert.Equal(@"MERGE INTO ""TBIOU01"" t1
USING (SELECT FIRST 1 1 as ""ID"" FROM rdb$database ) t2 ON (t1.""ID"" = t2.""ID"")
WHEN NOT MATCHED THEN
insert (""ID"")
values (t2.""ID"")", sql);
Assert.Equal(0, iou.ExecuteAffrows());
iou = fsql.InsertOrUpdate<tbiou01>().SetSource(new tbiou01 { id = 2 });
sql = iou.ToSql();
Assert.Equal(@"MERGE INTO ""TBIOU01"" t1
USING (SELECT FIRST 1 2 as ""ID"" FROM rdb$database ) t2 ON (t1.""ID"" = t2.""ID"")
WHEN NOT MATCHED THEN
insert (""ID"")
values (t2.""ID"")", sql);
Assert.Equal(1, iou.ExecuteAffrows());
iou = fsql.InsertOrUpdate<tbiou01>().SetSource(new[] { new tbiou01 { id = 1 }, new tbiou01 { id = 2 }, new tbiou01 { id = 3 }, new tbiou01 { id = 4 } });
sql = iou.ToSql();
Assert.Equal(@"MERGE INTO ""TBIOU01"" t1
USING (SELECT FIRST 1 1 as ""ID"" FROM rdb$database
UNION ALL
SELECT FIRST 1 2 FROM rdb$database
UNION ALL
SELECT FIRST 1 3 FROM rdb$database
UNION ALL
SELECT FIRST 1 4 FROM rdb$database ) t2 ON (t1.""ID"" = t2.""ID"")
WHEN NOT MATCHED THEN
insert (""ID"")
values (t2.""ID"")", sql);
Assert.Equal(2, iou.ExecuteAffrows());
iou = fsql.InsertOrUpdate<tbiou01>().SetSource(new[] { new tbiou01 { id = 1 }, new tbiou01 { id = 2 }, new tbiou01 { id = 3 }, new tbiou01 { id = 4 } });
sql = iou.ToSql();
Assert.Equal(@"MERGE INTO ""TBIOU01"" t1
USING (SELECT FIRST 1 1 as ""ID"" FROM rdb$database
UNION ALL
SELECT FIRST 1 2 FROM rdb$database
UNION ALL
SELECT FIRST 1 3 FROM rdb$database
UNION ALL
SELECT FIRST 1 4 FROM rdb$database ) t2 ON (t1.""ID"" = t2.""ID"")
WHEN NOT MATCHED THEN
insert (""ID"")
values (t2.""ID"")", sql);
Assert.Equal(0, iou.ExecuteAffrows());
}
| FirebirdInsertOrUpdateTest |
csharp | bitwarden__server | util/SqliteMigrations/Migrations/20230106025949_AvatarColor.Designer.cs | {
"start": 445,
"end": 59666
} | partial class ____
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "6.0.12");
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.AuthRequest", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<string>("AccessCode")
.HasMaxLength(25)
.HasColumnType("TEXT");
b.Property<bool?>("Approved")
.HasColumnType("INTEGER");
b.Property<DateTime?>("AuthenticationDate")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<string>("MasterPasswordHash")
.HasColumnType("TEXT");
b.Property<string>("PublicKey")
.HasColumnType("TEXT");
b.Property<string>("RequestDeviceIdentifier")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<byte>("RequestDeviceType")
.HasColumnType("INTEGER");
b.Property<string>("RequestFingerprint")
.HasColumnType("TEXT");
b.Property<string>("RequestIpAddress")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("ResponseDate")
.HasColumnType("TEXT");
b.Property<Guid?>("ResponseDeviceId")
.HasColumnType("TEXT");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("ResponseDeviceId");
b.HasIndex("UserId");
b.ToTable("AuthRequest", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Cipher", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<string>("Attachments")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Data")
.HasColumnType("TEXT");
b.Property<DateTime?>("DeletedDate")
.HasColumnType("TEXT");
b.Property<string>("Favorites")
.HasColumnType("TEXT");
b.Property<string>("Folders")
.HasColumnType("TEXT");
b.Property<Guid?>("OrganizationId")
.HasColumnType("TEXT");
b.Property<byte?>("Reprompt")
.HasColumnType("INTEGER");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("UserId");
b.ToTable("Cipher", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("ExternalId")
.HasMaxLength(300)
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("Collection", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionCipher", b =>
{
b.Property<Guid>("CollectionId")
.HasColumnType("TEXT");
b.Property<Guid>("CipherId")
.HasColumnType("TEXT");
b.HasKey("CollectionId", "CipherId");
b.HasIndex("CipherId");
b.ToTable("CollectionCipher", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionGroup", b =>
{
b.Property<Guid>("CollectionId")
.HasColumnType("TEXT");
b.Property<Guid>("GroupId")
.HasColumnType("TEXT");
b.Property<bool>("HidePasswords")
.HasColumnType("INTEGER");
b.Property<bool>("ReadOnly")
.HasColumnType("INTEGER");
b.HasKey("CollectionId", "GroupId");
b.HasIndex("GroupId");
b.ToTable("CollectionGroups");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionUser", b =>
{
b.Property<Guid>("CollectionId")
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationUserId")
.HasColumnType("TEXT");
b.Property<bool>("HidePasswords")
.HasColumnType("INTEGER");
b.Property<bool>("ReadOnly")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserId")
.HasColumnType("TEXT");
b.HasKey("CollectionId", "OrganizationUserId");
b.HasIndex("OrganizationUserId");
b.HasIndex("UserId");
b.ToTable("CollectionUsers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Device", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Identifier")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("PushToken")
.HasMaxLength(255)
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Device", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.EmergencyAccess", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<Guid?>("GranteeId")
.HasColumnType("TEXT");
b.Property<Guid>("GrantorId")
.HasColumnType("TEXT");
b.Property<string>("KeyEncrypted")
.HasColumnType("TEXT");
b.Property<DateTime?>("LastNotificationDate")
.HasColumnType("TEXT");
b.Property<DateTime?>("RecoveryInitiatedDate")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<byte>("Status")
.HasColumnType("INTEGER");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.Property<int>("WaitTimeDays")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("GranteeId");
b.HasIndex("GrantorId");
b.ToTable("EmergencyAccess", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Event", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<Guid?>("ActingUserId")
.HasColumnType("TEXT");
b.Property<Guid?>("CipherId")
.HasColumnType("TEXT");
b.Property<Guid?>("CollectionId")
.HasColumnType("TEXT");
b.Property<DateTime>("Date")
.HasColumnType("TEXT");
b.Property<byte?>("DeviceType")
.HasColumnType("INTEGER");
b.Property<Guid?>("GroupId")
.HasColumnType("TEXT");
b.Property<Guid?>("InstallationId")
.HasColumnType("TEXT");
b.Property<string>("IpAddress")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<Guid?>("OrganizationId")
.HasColumnType("TEXT");
b.Property<Guid?>("OrganizationUserId")
.HasColumnType("TEXT");
b.Property<Guid?>("PolicyId")
.HasColumnType("TEXT");
b.Property<Guid?>("ProviderId")
.HasColumnType("TEXT");
b.Property<Guid?>("ProviderOrganizationId")
.HasColumnType("TEXT");
b.Property<Guid?>("ProviderUserId")
.HasColumnType("TEXT");
b.Property<byte?>("SystemUser")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Event", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Folder", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<Guid>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Folder", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Grant", b =>
{
b.Property<string>("Key")
.HasMaxLength(200)
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.HasMaxLength(200)
.HasColumnType("TEXT");
b.Property<DateTime?>("ConsumedDate")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Data")
.HasColumnType("TEXT");
b.Property<string>("Description")
.HasMaxLength(200)
.HasColumnType("TEXT");
b.Property<DateTime?>("ExpirationDate")
.HasColumnType("TEXT");
b.Property<string>("SessionId")
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("SubjectId")
.HasMaxLength(200)
.HasColumnType("TEXT");
b.Property<string>("Type")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.HasKey("Key");
b.ToTable("Grant", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<bool>("AccessAll")
.HasColumnType("INTEGER");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("ExternalId")
.HasMaxLength(300)
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("Group", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.GroupUser", b =>
{
b.Property<Guid>("GroupId")
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationUserId")
.HasColumnType("TEXT");
b.Property<Guid?>("UserId")
.HasColumnType("TEXT");
b.HasKey("GroupId", "OrganizationUserId");
b.HasIndex("OrganizationUserId");
b.HasIndex("UserId");
b.ToTable("GroupUser", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Installation", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<string>("Key")
.HasMaxLength(150)
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Installation", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Organization", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<string>("BillingEmail")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("BusinessAddress1")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("BusinessAddress2")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("BusinessAddress3")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("BusinessCountry")
.HasMaxLength(2)
.HasColumnType("TEXT");
b.Property<string>("BusinessName")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("BusinessTaxNumber")
.HasMaxLength(30)
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<DateTime?>("ExpirationDate")
.HasColumnType("TEXT");
b.Property<byte?>("Gateway")
.HasColumnType("INTEGER");
b.Property<string>("GatewayCustomerId")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("GatewaySubscriptionId")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("Identifier")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("LicenseKey")
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<int?>("MaxAutoscaleSeats")
.HasColumnType("INTEGER");
b.Property<short?>("MaxCollections")
.HasColumnType("INTEGER");
b.Property<short?>("MaxStorageGb")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("OwnersNotifiedOfAutoscaling")
.HasColumnType("TEXT");
b.Property<string>("Plan")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<byte>("PlanType")
.HasColumnType("INTEGER");
b.Property<string>("PrivateKey")
.HasColumnType("TEXT");
b.Property<string>("PublicKey")
.HasColumnType("TEXT");
b.Property<string>("ReferenceData")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<int?>("Seats")
.HasColumnType("INTEGER");
b.Property<bool>("SelfHost")
.HasColumnType("INTEGER");
b.Property<long?>("Storage")
.HasColumnType("INTEGER");
b.Property<string>("TwoFactorProviders")
.HasColumnType("TEXT");
b.Property<bool>("Use2fa")
.HasColumnType("INTEGER");
b.Property<bool>("UseApi")
.HasColumnType("INTEGER");
b.Property<bool>("UseCustomPermissions")
.HasColumnType("INTEGER");
b.Property<bool>("UseDirectory")
.HasColumnType("INTEGER");
b.Property<bool>("UseEvents")
.HasColumnType("INTEGER");
b.Property<bool>("UseGroups")
.HasColumnType("INTEGER");
b.Property<bool>("UseKeyConnector")
.HasColumnType("INTEGER");
b.Property<bool>("UsePolicies")
.HasColumnType("INTEGER");
b.Property<bool>("UseResetPassword")
.HasColumnType("INTEGER");
b.Property<bool>("UseScim")
.HasColumnType("INTEGER");
b.Property<bool>("UseSso")
.HasColumnType("INTEGER");
b.Property<bool>("UseTotp")
.HasColumnType("INTEGER");
b.Property<bool>("UsersGetPremium")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("Organization", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationApiKey", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<string>("ApiKey")
.HasMaxLength(30)
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("OrganizationApiKey", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationConnection", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<string>("Config")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("OrganizationConnection", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationSponsorship", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<string>("FriendlyName")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<DateTime?>("LastSyncDate")
.HasColumnType("TEXT");
b.Property<string>("OfferedToEmail")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<byte?>("PlanSponsorshipType")
.HasColumnType("INTEGER");
b.Property<Guid?>("SponsoredOrganizationId")
.HasColumnType("TEXT");
b.Property<Guid?>("SponsoringOrganizationId")
.HasColumnType("TEXT");
b.Property<Guid>("SponsoringOrganizationUserId")
.HasColumnType("TEXT");
b.Property<bool>("ToDelete")
.HasColumnType("INTEGER");
b.Property<DateTime?>("ValidUntil")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("SponsoredOrganizationId");
b.HasIndex("SponsoringOrganizationId");
b.ToTable("OrganizationSponsorship", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<bool>("AccessAll")
.HasColumnType("INTEGER");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("ExternalId")
.HasMaxLength(300)
.HasColumnType("TEXT");
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<string>("Permissions")
.HasColumnType("TEXT");
b.Property<string>("ResetPasswordKey")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<short>("Status")
.HasColumnType("INTEGER");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("UserId");
b.ToTable("OrganizationUser", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Policy", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Data")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("Policy", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Provider", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<string>("BillingEmail")
.HasColumnType("TEXT");
b.Property<string>("BusinessAddress1")
.HasColumnType("TEXT");
b.Property<string>("BusinessAddress2")
.HasColumnType("TEXT");
b.Property<string>("BusinessAddress3")
.HasColumnType("TEXT");
b.Property<string>("BusinessCountry")
.HasColumnType("TEXT");
b.Property<string>("BusinessName")
.HasColumnType("TEXT");
b.Property<string>("BusinessTaxNumber")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<byte>("Status")
.HasColumnType("INTEGER");
b.Property<bool>("UseEvents")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("Provider", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.ProviderOrganization", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<Guid>("ProviderId")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<string>("Settings")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("ProviderId");
b.ToTable("ProviderOrganization", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.ProviderUser", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<string>("Permissions")
.HasColumnType("TEXT");
b.Property<Guid>("ProviderId")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<byte>("Status")
.HasColumnType("INTEGER");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("ProviderId");
b.HasIndex("UserId");
b.ToTable("ProviderUser", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Send", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<int>("AccessCount")
.HasColumnType("INTEGER");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Data")
.HasColumnType("TEXT");
b.Property<DateTime>("DeletionDate")
.HasColumnType("TEXT");
b.Property<bool>("Disabled")
.HasColumnType("INTEGER");
b.Property<DateTime?>("ExpirationDate")
.HasColumnType("TEXT");
b.Property<bool?>("HideEmail")
.HasColumnType("INTEGER");
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<int?>("MaxAccessCount")
.HasColumnType("INTEGER");
b.Property<Guid?>("OrganizationId")
.HasColumnType("TEXT");
b.Property<string>("Password")
.HasMaxLength(300)
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("UserId");
b.ToTable("Send", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.SsoConfig", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Data")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("SsoConfig", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.SsoUser", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("ExternalId")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<Guid?>("OrganizationId")
.HasColumnType("TEXT");
b.Property<Guid>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("UserId");
b.ToTable("SsoUser", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.TaxRate", b =>
{
b.Property<string>("Id")
.HasMaxLength(40)
.HasColumnType("TEXT");
b.Property<bool>("Active")
.HasColumnType("INTEGER");
b.Property<string>("Country")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("PostalCode")
.HasMaxLength(10)
.HasColumnType("TEXT");
b.Property<decimal>("Rate")
.HasColumnType("TEXT");
b.Property<string>("State")
.HasMaxLength(2)
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("TaxRate", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Transaction", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<decimal>("Amount")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Details")
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<byte?>("Gateway")
.HasColumnType("INTEGER");
b.Property<string>("GatewayId")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<Guid?>("OrganizationId")
.HasColumnType("TEXT");
b.Property<byte?>("PaymentMethodType")
.HasColumnType("INTEGER");
b.Property<bool?>("Refunded")
.HasColumnType("INTEGER");
b.Property<decimal?>("RefundedAmount")
.HasColumnType("TEXT");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("UserId");
b.ToTable("Transaction", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.User", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("AccountRevisionDate")
.HasColumnType("TEXT");
b.Property<string>("ApiKey")
.IsRequired()
.HasMaxLength(30)
.HasColumnType("TEXT");
b.Property<string>("AvatarColor")
.HasMaxLength(7)
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Culture")
.HasMaxLength(10)
.HasColumnType("TEXT");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<bool>("EmailVerified")
.HasColumnType("INTEGER");
b.Property<string>("EquivalentDomains")
.HasColumnType("TEXT");
b.Property<string>("ExcludedGlobalEquivalentDomains")
.HasColumnType("TEXT");
b.Property<int>("FailedLoginCount")
.HasColumnType("INTEGER");
b.Property<bool>("ForcePasswordReset")
.HasColumnType("INTEGER");
b.Property<byte?>("Gateway")
.HasColumnType("INTEGER");
b.Property<string>("GatewayCustomerId")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("GatewaySubscriptionId")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<byte>("Kdf")
.HasColumnType("INTEGER");
b.Property<int>("KdfIterations")
.HasColumnType("INTEGER");
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<DateTime?>("LastFailedLoginDate")
.HasColumnType("TEXT");
b.Property<string>("LicenseKey")
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("MasterPassword")
.HasMaxLength(300)
.HasColumnType("TEXT");
b.Property<string>("MasterPasswordHint")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<short?>("MaxStorageGb")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<bool>("Premium")
.HasColumnType("INTEGER");
b.Property<DateTime?>("PremiumExpirationDate")
.HasColumnType("TEXT");
b.Property<string>("PrivateKey")
.HasColumnType("TEXT");
b.Property<string>("PublicKey")
.HasColumnType("TEXT");
b.Property<string>("ReferenceData")
.HasColumnType("TEXT");
b.Property<DateTime?>("RenewalReminderDate")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<string>("SecurityStamp")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<long?>("Storage")
.HasColumnType("INTEGER");
b.Property<string>("TwoFactorProviders")
.HasColumnType("TEXT");
b.Property<string>("TwoFactorRecoveryCode")
.HasMaxLength(32)
.HasColumnType("TEXT");
b.Property<bool>("UnknownDeviceVerificationEnabled")
.HasColumnType("INTEGER");
b.Property<bool>("UsesKeyConnector")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("User", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.AuthRequest", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Device", "ResponseDevice")
.WithMany()
.HasForeignKey("ResponseDeviceId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("ResponseDevice");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Cipher", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("Ciphers")
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("Ciphers")
.HasForeignKey("UserId");
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionCipher", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Cipher", "Cipher")
.WithMany("CollectionCiphers")
.HasForeignKey("CipherId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection")
.WithMany("CollectionCiphers")
.HasForeignKey("CollectionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Cipher");
b.Navigation("Collection");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionGroup", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection")
.WithMany("CollectionGroups")
.HasForeignKey("CollectionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group")
.WithMany()
.HasForeignKey("GroupId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Collection");
b.Navigation("Group");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection")
.WithMany("CollectionUsers")
.HasForeignKey("CollectionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser")
.WithMany("CollectionUsers")
.HasForeignKey("OrganizationUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", null)
.WithMany("CollectionUsers")
.HasForeignKey("UserId");
b.Navigation("Collection");
b.Navigation("OrganizationUser");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Device", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.EmergencyAccess", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "Grantee")
.WithMany()
.HasForeignKey("GranteeId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "Grantor")
.WithMany()
.HasForeignKey("GrantorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Grantee");
b.Navigation("Grantor");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Folder", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("Folders")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("Groups")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.GroupUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group")
.WithMany("GroupUsers")
.HasForeignKey("GroupId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser")
.WithMany()
.HasForeignKey("OrganizationUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", null)
.WithMany("GroupUsers")
.HasForeignKey("UserId");
b.Navigation("Group");
b.Navigation("OrganizationUser");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationApiKey", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("ApiKeys")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationConnection", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("Connections")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationSponsorship", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "SponsoredOrganization")
.WithMany()
.HasForeignKey("SponsoredOrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "SponsoringOrganization")
.WithMany()
.HasForeignKey("SponsoringOrganizationId");
b.Navigation("SponsoredOrganization");
b.Navigation("SponsoringOrganization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("OrganizationUsers")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("OrganizationUsers")
.HasForeignKey("UserId");
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Policy", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("Policies")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.ProviderOrganization", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Provider", "Provider")
.WithMany()
.HasForeignKey("ProviderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
b.Navigation("Provider");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.ProviderUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Provider", "Provider")
.WithMany()
.HasForeignKey("ProviderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany()
.HasForeignKey("UserId");
b.Navigation("Provider");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Send", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany()
.HasForeignKey("UserId");
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.SsoConfig", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("SsoConfigs")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.SsoUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("SsoUsers")
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("SsoUsers")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Transaction", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("Transactions")
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("Transactions")
.HasForeignKey("UserId");
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Cipher", b =>
{
b.Navigation("CollectionCiphers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b =>
{
b.Navigation("CollectionCiphers");
b.Navigation("CollectionGroups");
b.Navigation("CollectionUsers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b =>
{
b.Navigation("GroupUsers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Organization", b =>
{
b.Navigation("ApiKeys");
b.Navigation("Ciphers");
b.Navigation("Connections");
b.Navigation("Groups");
b.Navigation("OrganizationUsers");
b.Navigation("Policies");
b.Navigation("SsoConfigs");
b.Navigation("SsoUsers");
b.Navigation("Transactions");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b =>
{
b.Navigation("CollectionUsers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.User", b =>
{
b.Navigation("Ciphers");
b.Navigation("CollectionUsers");
b.Navigation("Folders");
b.Navigation("GroupUsers");
b.Navigation("OrganizationUsers");
b.Navigation("SsoUsers");
b.Navigation("Transactions");
});
#pragma warning restore 612, 618
}
}
}
| AvatarColor |
csharp | nuke-build__nuke | source/Nuke.Utilities/Text/String.Truncate.cs | {
"start": 204,
"end": 396
} | partial class ____
{
public static string Truncate(this string str, int maxChars)
{
return str.Length <= maxChars ? str : str.Substring(0, maxChars) + "…";
}
}
| StringExtensions |
csharp | dotnet__efcore | src/EFCore/Metadata/IMutableComplexType.cs | {
"start": 754,
"end": 2553
} | public interface ____ : IReadOnlyComplexType, IMutableTypeBase
{
/// <summary>
/// Gets the associated property.
/// </summary>
new IMutableComplexProperty ComplexProperty { get; }
/// <summary>
/// Gets or sets the base type of this complex type. Returns <see langword="null" /> if this is not a derived type in an inheritance
/// hierarchy.
/// </summary>
new IMutableComplexType? BaseType { get; }
/// <summary>
/// Gets the root base type for a given complex type.
/// </summary>
/// <returns>
/// The root base type. If the given complex type is not a derived type, then the same complex type is returned.
/// </returns>
new IMutableComplexType GetRootType()
=> (IMutableComplexType)((IReadOnlyTypeBase)this).GetRootType();
/// <summary>
/// Gets all types in the model that derive from this complex type.
/// </summary>
/// <returns>The derived types.</returns>
new IEnumerable<IMutableComplexType> GetDerivedTypes()
=> ((IReadOnlyTypeBase)this).GetDerivedTypes().Cast<IMutableComplexType>();
/// <summary>
/// Returns all derived types of this complex type, including the type itself.
/// </summary>
/// <returns>Derived types.</returns>
new IEnumerable<IMutableComplexType> GetDerivedTypesInclusive()
=> ((IReadOnlyTypeBase)this).GetDerivedTypesInclusive().Cast<IMutableComplexType>();
/// <summary>
/// Gets all types in the model that directly derive from this complex type.
/// </summary>
/// <returns>The derived types.</returns>
new IEnumerable<IMutableComplexType> GetDirectlyDerivedTypes()
=> ((IReadOnlyTypeBase)this).GetDirectlyDerivedTypes().Cast<IMutableComplexType>();
}
| IMutableComplexType |
csharp | ChilliCream__graphql-platform | src/CookieCrumble/src/CookieCrumble/Snapshot.cs | {
"start": 22425,
"end": 22719
} | struct ____(string? name, object? value, ISnapshotValueFormatter formatter)
: ISnapshotSegment
{
public string? Name { get; } = name;
public object? Value { get; } = value;
public ISnapshotValueFormatter Formatter { get; } = formatter;
}
}
| SnapshotSegment |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/test/Types.Tests/Types/ObjectFieldExpressionTests.cs | {
"start": 1640,
"end": 1758
} | public class ____
{
public string Text { get; } = "Hello";
public int Count { get; } = 1;
}
}
| Bar |
csharp | AutoMapper__AutoMapper | src/UnitTests/AttributeBasedMaps.cs | {
"start": 27085,
"end": 27189
} | public class ____ : Foo { }
[AutoMap(typeof(Foo), IncludeAllDerived = true)]
| FooBar |
csharp | dotnet__orleans | src/Orleans.Runtime/Catalog/ActivationCollector.cs | {
"start": 495,
"end": 27983
} | internal partial class ____ : IActivationWorkingSetObserver, ILifecycleParticipant<ISiloLifecycle>, IDisposable
{
private readonly TimeSpan shortestAgeLimit;
private readonly ConcurrentDictionary<DateTime, Bucket> buckets = new();
private readonly CancellationTokenSource _shutdownCts = new();
private DateTime nextTicket;
private static readonly List<ICollectibleGrainContext> nothing = new(0);
private readonly ILogger logger;
private int collectionNumber;
// internal for testing
internal int _activationCount;
private readonly PeriodicTimer _collectionTimer;
private Task _collectionLoopTask;
private readonly IEnvironmentStatisticsProvider _environmentStatisticsProvider;
private readonly GrainCollectionOptions _grainCollectionOptions;
private readonly PeriodicTimer _memBasedDeactivationTimer;
private Task _memBasedDeactivationLoopTask;
/// <summary>
/// Initializes a new instance of the <see cref="ActivationCollector"/> class.
/// </summary>
/// <param name="timeProvider">The time provider.</param>
/// <param name="options">The options.</param>
/// <param name="logger">The logger.</param>
public ActivationCollector(
TimeProvider timeProvider,
IOptions<GrainCollectionOptions> options,
ILogger<ActivationCollector> logger,
IEnvironmentStatisticsProvider environmentStatisticsProvider)
{
_grainCollectionOptions = options.Value;
shortestAgeLimit = new(_grainCollectionOptions.ClassSpecificCollectionAge.Values.Aggregate(_grainCollectionOptions.CollectionAge.Ticks, (a, v) => Math.Min(a, v.Ticks)));
nextTicket = MakeTicketFromDateTime(timeProvider.GetUtcNow().UtcDateTime);
this.logger = logger;
_collectionTimer = new PeriodicTimer(_grainCollectionOptions.CollectionQuantum);
_environmentStatisticsProvider = environmentStatisticsProvider;
if (_grainCollectionOptions.EnableActivationSheddingOnMemoryPressure)
{
_memBasedDeactivationTimer = new PeriodicTimer(_grainCollectionOptions.MemoryUsagePollingPeriod);
}
}
// Return the number of activations that were used (touched) in the last recencyPeriod.
public int GetNumRecentlyUsed(TimeSpan recencyPeriod)
{
var now = DateTime.UtcNow;
int sum = 0;
foreach (var bucket in buckets)
{
// Ticket is the date time when this bucket should be collected (last touched time plus age limit)
// For now we take the shortest age limit as an approximation of the per-type age limit.
DateTime ticket = bucket.Key;
var timeTillCollection = ticket - now;
var timeSinceLastUsed = shortestAgeLimit - timeTillCollection;
if (timeSinceLastUsed <= recencyPeriod)
{
sum += bucket.Value.Items.Count;
}
}
return sum;
}
/// <summary>
/// Collects all eligible grain activations which have been idle for at least <paramref name="ageLimit"/>.
/// </summary>
/// <param name="ageLimit">The age limit.</param>
/// <returns>A <see cref="Task"/> representing the work performed.</returns>
public Task CollectActivations(TimeSpan ageLimit, CancellationToken cancellationToken) => CollectActivationsImpl(false, ageLimit, cancellationToken);
/// <summary>
/// Schedules the provided grain context for collection if it becomes idle for the specified duration.
/// </summary>
/// <param name="item">
/// The grain context.
/// </param>
/// <param name="timeout">
/// The current idle collection time for the grain.
/// </param>
public void ScheduleCollection(ICollectibleGrainContext item, TimeSpan timeout, DateTime now)
{
lock (item)
{
if (item.IsExemptFromCollection)
{
return;
}
DateTime ticket = MakeTicketFromTimeSpan(timeout, now);
if (default != item.CollectionTicket)
{
throw new InvalidOperationException("Call CancelCollection before calling ScheduleCollection.");
}
Add(item, ticket);
}
}
/// <summary>
/// Tries the cancel idle activation collection.
/// </summary>
/// <param name="item">The grain context.</param>
/// <returns><see langword="true"/> if collection was canceled, <see langword="false"/> otherwise.</returns>
public bool TryCancelCollection(ICollectibleGrainContext item)
{
if (item is null) return false;
if (item.IsExemptFromCollection) return false;
lock (item)
{
DateTime ticket = item.CollectionTicket;
if (default == ticket) return false;
if (IsExpired(ticket)) return false;
// first, we attempt to remove the ticket.
Bucket bucket;
if (!buckets.TryGetValue(ticket, out bucket) || !bucket.TryRemove(item)) return false;
}
return true;
}
/// <summary>
/// Tries the reschedule collection.
/// </summary>
/// <param name="item">The grain context.</param>
/// <returns><see langword="true"/> if collection was canceled, <see langword="false"/> otherwise.</returns>
public bool TryRescheduleCollection(ICollectibleGrainContext item)
{
if (item.IsExemptFromCollection) return false;
lock (item)
{
if (TryRescheduleCollection_Impl(item, item.CollectionAgeLimit)) return true;
item.CollectionTicket = default;
return false;
}
}
private bool TryRescheduleCollection_Impl(ICollectibleGrainContext item, TimeSpan timeout)
{
// note: we expect the activation lock to be held.
if (default == item.CollectionTicket) return false;
ThrowIfTicketIsInvalid(item.CollectionTicket);
if (IsExpired(item.CollectionTicket)) return false;
DateTime oldTicket = item.CollectionTicket;
DateTime newTicket = MakeTicketFromTimeSpan(timeout, DateTime.UtcNow);
// if the ticket value doesn't change, then the source and destination bucket are the same and there's nothing to do.
if (newTicket.Equals(oldTicket)) return true;
Bucket bucket;
if (!buckets.TryGetValue(oldTicket, out bucket) || !bucket.TryRemove(item))
{
// fail: item is not associated with currentKey.
return false;
}
// it shouldn't be possible for Add to throw an exception here, as only one concurrent competitor should be able to reach to this point in the method.
Add(item, newTicket);
return true;
}
private bool DequeueQuantum(out List<ICollectibleGrainContext> items, DateTime now)
{
DateTime key;
lock (buckets)
{
if (nextTicket > now)
{
items = null;
return false;
}
key = nextTicket;
nextTicket += _grainCollectionOptions.CollectionQuantum;
}
Bucket bucket;
if (!buckets.TryRemove(key, out bucket))
{
items = nothing;
return true;
}
items = bucket.CancelAll();
return true;
}
/// <inheritdoc/>
public override string ToString()
{
var now = DateTime.UtcNow;
var all = buckets.ToList();
var bucketsText = Utils.EnumerableToString(all.OrderBy(bucket => bucket.Key), bucket => $"{Utils.TimeSpanToString(bucket.Key - now)}->{bucket.Value.Items.Count} items");
return $"<#Activations={all.Sum(b => b.Value.Items.Count)}, #Buckets={all.Count}, buckets={bucketsText}>";
}
/// <summary>
/// Scans for activations that are due for collection.
/// </summary>
/// <returns>A list of activations that are due for collection.</returns>
public List<ICollectibleGrainContext> ScanStale()
{
var now = DateTime.UtcNow;
List<ICollectibleGrainContext> condemned = null;
while (DequeueQuantum(out var activations, now))
{
// At this point, all tickets associated with activations are cancelled and any attempts to reschedule will fail silently.
// If the activation is to be reactivated, it's our job to clear the activation's copy of the ticket.
foreach (var activation in activations)
{
lock (activation)
{
activation.CollectionTicket = default;
if (!activation.IsValid)
{
// This is not an error scenario because the activation may have become invalid between the time
// we captured a snapshot in 'DequeueQuantum' and now. We are not be able to observe such changes.
// Do nothing: don't collect, don't reschedule.
}
else if (activation.KeepAliveUntil > now)
{
var keepAliveDuration = activation.KeepAliveUntil - now;
var timeout = TimeSpan.FromTicks(Math.Max(keepAliveDuration.Ticks, activation.CollectionAgeLimit.Ticks));
ScheduleCollection(activation, timeout, now);
}
else if (!activation.IsInactive || !activation.IsStale())
{
ScheduleCollection(activation, activation.CollectionAgeLimit, now);
}
else
{
// Atomically set Deactivating state, to disallow any new requests or new timer ticks to be dispatched on this activation.
condemned ??= [];
condemned.Add(activation);
}
}
}
}
return condemned ?? nothing;
}
/// <summary>
/// Scans for activations that have been idle for the specified age limit.
/// </summary>
/// <param name="ageLimit">The age limit.</param>
/// <returns>The grain activations which have been idle for at least the specified age limit.</returns>
public List<ICollectibleGrainContext> ScanAll(TimeSpan ageLimit)
{
List<ICollectibleGrainContext> condemned = null;
var now = DateTime.UtcNow;
foreach (var kv in buckets)
{
var bucket = kv.Value;
foreach (var kvp in bucket.Items)
{
var activation = kvp.Value;
lock (activation)
{
if (!activation.IsValid)
{
// Do nothing: don't collect, don't reschedule.
}
else if (activation.KeepAliveUntil > now)
{
// do nothing
}
else if (!activation.IsInactive)
{
// do nothing
}
else
{
if (activation.GetIdleness() >= ageLimit)
{
if (bucket.TryRemove(activation))
{
condemned ??= [];
condemned.Add(activation);
}
// someone else has already deactivated the activation, so there's nothing to do.
}
else
{
// activation is not idle long enough for collection. do nothing.
}
}
}
}
}
return condemned ?? nothing;
}
// Internal for testing. It's expected that when this returns true, activation shedding will occur.
internal bool IsMemoryOverloaded(out int surplusActivationCount)
{
var stats = _environmentStatisticsProvider.GetEnvironmentStatistics();
var limit = _grainCollectionOptions.MemoryUsageLimitPercentage / 100f;
var usage = stats.NormalizedMemoryUsage;
if (usage <= limit)
{
// High memory pressure is not detected, so we do not need to deactivate any activations.
surplusActivationCount = 0;
return false;
}
// Calculate the surplus activations based the memory usage target.
var activationCount = _activationCount;
var target = _grainCollectionOptions.MemoryUsageTargetPercentage / 100f;
surplusActivationCount = (int)Math.Max(0, activationCount - Math.Floor(activationCount * target / usage));
if (surplusActivationCount <= 0)
{
surplusActivationCount = 0;
return false;
}
var surplusActivationPercentage = 100 * (1 - target / usage);
LogCurrentHighMemoryPressureStats(stats.MemoryUsagePercentage, _grainCollectionOptions.MemoryUsageLimitPercentage, deactivationTarget: surplusActivationCount, activationCount, surplusActivationPercentage);
return true;
}
/// <summary>
/// Deactivates <param name="count" /> activations in due time order
/// <remarks>internal for testing</remarks>
/// </summary>
internal async Task DeactivateInDueTimeOrder(int count, CancellationToken cancellationToken)
{
var watch = ValueStopwatch.StartNew();
var number = Interlocked.Increment(ref collectionNumber);
long memBefore = GC.GetTotalMemory(false) / (1024 * 1024); // MB
LogBeforeCollection(number, memBefore, _activationCount, this);
var candidates = new List<ICollectibleGrainContext>(count);
// snapshot to avoid concurrency collection modification issues
var bucketSnapshot = buckets.ToArray();
foreach (var bucket in bucketSnapshot.OrderBy(b => b.Key))
{
foreach (var item in bucket.Value.Items)
{
if (candidates.Count >= count)
{
break;
}
var activation = item.Value;
candidates.Add(activation);
}
if (candidates.Count >= count)
{
break;
}
}
CatalogInstruments.ActivationCollections.Add(1);
if (candidates.Count > 0)
{
LogCollectActivations(new(candidates));
var reason = new DeactivationReason(
DeactivationReasonCode.HighMemoryPressure,
$"Process memory utilization exceeded the configured limit of '{_grainCollectionOptions.MemoryUsageLimitPercentage}'. Detected memory usage is {memBefore} MB.");
await DeactivateActivationsFromCollector(candidates, cancellationToken, reason);
}
long memAfter = GC.GetTotalMemory(false) / (1024 * 1024);
watch.Stop();
LogAfterCollection(number, memAfter, _activationCount, candidates.Count, this, watch.Elapsed);
}
private static DeactivationReason GetDeactivationReason()
{
var reasonText = "This activation has become idle.";
var reason = new DeactivationReason(DeactivationReasonCode.ActivationIdle, reasonText);
return reason;
}
private void ThrowIfTicketIsInvalid(DateTime ticket)
{
if (ticket.Ticks == 0) throw new ArgumentException("Empty ticket is not allowed in this context.");
if (0 != ticket.Ticks % _grainCollectionOptions.CollectionQuantum.Ticks)
{
throw new ArgumentException(string.Format("invalid ticket ({0})", ticket));
}
}
private bool IsExpired(DateTime ticket)
{
return ticket < nextTicket;
}
public DateTime MakeTicketFromDateTime(DateTime timestamp)
{
// Round the timestamp to the next _grainCollectionOptions.CollectionQuantum. e.g. if the _grainCollectionOptions.CollectionQuantum is 1 minute and the timestamp is 3:45:22, then the ticket will be 3:46.
// Note that TimeStamp.Ticks and DateTime.Ticks both return a long.
var ticketTicks = ((timestamp.Ticks - 1) / _grainCollectionOptions.CollectionQuantum.Ticks + 1) * _grainCollectionOptions.CollectionQuantum.Ticks;
if (ticketTicks > DateTime.MaxValue.Ticks)
{
return DateTime.MaxValue;
}
var ticket = new DateTime(ticketTicks, DateTimeKind.Utc);
if (ticket < nextTicket)
{
throw new ArgumentException(string.Format("The earliest collection that can be scheduled from now is for {0}", new DateTime(nextTicket.Ticks - _grainCollectionOptions.CollectionQuantum.Ticks + 1, DateTimeKind.Utc)));
}
return ticket;
}
private DateTime MakeTicketFromTimeSpan(TimeSpan timeout, DateTime now)
{
if (timeout < _grainCollectionOptions.CollectionQuantum)
{
throw new ArgumentException(string.Format("timeout must be at least {0}, but it is {1}", _grainCollectionOptions.CollectionQuantum, timeout), nameof(timeout));
}
return MakeTicketFromDateTime(now + timeout);
}
private void Add(ICollectibleGrainContext item, DateTime ticket)
{
// note: we expect the activation lock to be held.
item.CollectionTicket = ticket;
var bucket = buckets.GetOrAdd(ticket, _ => new Bucket());
bucket.Add(item);
}
void IActivationWorkingSetObserver.OnAdded(IActivationWorkingSetMember member)
{
if (member is ICollectibleGrainContext activation)
{
Interlocked.Increment(ref _activationCount);
if (activation.CollectionTicket == default)
{
ScheduleCollection(activation, activation.CollectionAgeLimit, DateTime.UtcNow);
}
else
{
TryRescheduleCollection(activation);
}
}
}
void IActivationWorkingSetObserver.OnActive(IActivationWorkingSetMember member)
{
// We do not need to do anything when a grain becomes active, since we can lazily handle it when scanning its bucket instead.
// This reduces the amount of unnecessary work performed.
}
void IActivationWorkingSetObserver.OnEvicted(IActivationWorkingSetMember member)
{
if (member is ICollectibleGrainContext activation && activation.CollectionTicket == default)
{
TryRescheduleCollection(activation);
}
}
void IActivationWorkingSetObserver.OnDeactivating(IActivationWorkingSetMember member)
{
if (member is ICollectibleGrainContext activation)
{
TryCancelCollection(activation);
}
}
void IActivationWorkingSetObserver.OnDeactivated(IActivationWorkingSetMember member)
{
Interlocked.Decrement(ref _activationCount);
_ = TryCancelCollection(member as ICollectibleGrainContext);
}
private Task Start(CancellationToken cancellationToken)
{
using var _ = new ExecutionContextSuppressor();
_collectionLoopTask = RunActivationCollectionLoop();
if (_grainCollectionOptions.EnableActivationSheddingOnMemoryPressure)
{
_memBasedDeactivationLoopTask = RunMemoryBasedDeactivationLoop();
}
return Task.CompletedTask;
}
private async Task Stop(CancellationToken cancellationToken)
{
using var registration = cancellationToken.Register(() => _shutdownCts.Cancel());
_collectionTimer.Dispose();
_memBasedDeactivationTimer?.Dispose();
if (_collectionLoopTask is Task task)
{
await task.WaitAsync(cancellationToken);
}
if (_memBasedDeactivationLoopTask is Task deactivationLoopTask)
{
await deactivationLoopTask.WaitAsync(cancellationToken);
}
}
void ILifecycleParticipant<ISiloLifecycle>.Participate(ISiloLifecycle lifecycle)
{
lifecycle.Subscribe(
nameof(ActivationCollector),
ServiceLifecycleStage.RuntimeServices,
Start,
Stop);
}
private async Task RunActivationCollectionLoop()
{
await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding);
var cancellationToken = _shutdownCts.Token;
while (await _collectionTimer.WaitForNextTickAsync())
{
try
{
await this.CollectActivationsImpl(true, ageLimit: default, cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// most probably shutdown
}
catch (Exception exception)
{
LogErrorWhileCollectingActivations(exception);
}
}
}
private async Task RunMemoryBasedDeactivationLoop()
{
await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding);
var cancellationToken = _shutdownCts.Token;
int lastGen2GcCount = 0;
try
{
while (await _memBasedDeactivationTimer.WaitForNextTickAsync(cancellationToken))
{
try
{
var currentGen2GcCount = GC.CollectionCount(2);
// note: GC.CollectionCount(2) will return 0 if no gen2 gc happened yet and we rely on this behavior:
// high memory pressure situation cannot occur until gen2 occurred at least once
if (currentGen2GcCount <= lastGen2GcCount)
{
// No Gen2 GC since last deactivation cycle.
// Wait for Gen2 GC between cycles to be sure that
continue;
}
if (!IsMemoryOverloaded(out var surplusActivationCount))
{
continue;
}
lastGen2GcCount = currentGen2GcCount;
await DeactivateInDueTimeOrder(surplusActivationCount, cancellationToken);
}
catch (Exception exception)
{
// Ignore cancellation exceptions during shutdown.
if (exception is OperationCanceledException && cancellationToken.IsCancellationRequested)
{
break;
}
LogErrorWhileCollectingActivations(exception);
}
}
}
catch (Exception exception)
{
if (exception is OperationCanceledException && cancellationToken.IsCancellationRequested)
{
// Ignore cancellation exceptions during shutdown.
}
else
{
throw;
}
}
}
private async Task CollectActivationsImpl(bool scanStale, TimeSpan ageLimit, CancellationToken cancellationToken)
{
var watch = ValueStopwatch.StartNew();
var number = Interlocked.Increment(ref collectionNumber);
long memBefore = GC.GetTotalMemory(false) / (1024 * 1024);
LogBeforeCollection(number, memBefore, _activationCount, this);
List<ICollectibleGrainContext> list = scanStale ? ScanStale() : ScanAll(ageLimit);
CatalogInstruments.ActivationCollections.Add(1);
if (list is { Count: > 0 })
{
LogCollectActivations(new(list));
await DeactivateActivationsFromCollector(list, cancellationToken);
}
long memAfter = GC.GetTotalMemory(false) / (1024 * 1024);
watch.Stop();
LogAfterCollection(number, memAfter, _activationCount, list?.Count ?? 0, this, watch.Elapsed);
}
private async Task DeactivateActivationsFromCollector(List<ICollectibleGrainContext> list, CancellationToken cancellationToken, DeactivationReason? deactivationReason = null)
{
LogDeactivateActivationsFromCollector(list.Count);
CatalogInstruments.ActivationShutdownViaCollection();
deactivationReason ??= GetDeactivationReason();
var options = new ParallelOptions
{
// Avoid passing the cancellation token, since we want all of these activations to be deactivated, even if cancellation is triggered.
CancellationToken = CancellationToken.None,
MaxDegreeOfParallelism = Environment.ProcessorCount * 512
};
await Parallel.ForEachAsync(list, options, async (activationData, token) =>
{
// Continue deactivation when ready.
activationData.Deactivate(deactivationReason.Value, cancellationToken);
await activationData.Deactivated.ConfigureAwait(false);
}).WaitAsync(cancellationToken);
}
public void Dispose()
{
_collectionTimer.Dispose();
_shutdownCts.Dispose();
_memBasedDeactivationTimer?.Dispose();
}
| ActivationCollector |
csharp | abpframework__abp | framework/src/Volo.Abp.AspNetCore.Mvc.UI.Bundling.Abstractions/Volo/Abp/AspNetCore/Mvc/UI/Bundling/BundlingMode.cs | {
"start": 48,
"end": 548
} | public enum ____
{
/// <summary>
/// No bundling or minification.
/// </summary>
None,
/// <summary>
/// Automatically determine the mode.
/// - Uses <see cref="None"/> for development time.
/// - Uses <see cref="BundleAndMinify"/> for other environments.
/// </summary>
Auto,
/// <summary>
/// Bundled but not minified.
/// </summary>
Bundle,
/// <summary>
/// Bundled and minified.
/// </summary>
BundleAndMinify
}
| BundlingMode |
csharp | mongodb__mongo-csharp-driver | src/MongoDB.Bson/Serialization/BsonClassMap.cs | {
"start": 15581,
"end": 16156
} | class ____ was already registered.</returns>
public static bool TryRegisterClassMap<TClass>(Action<BsonClassMap<TClass>> classMapInitializer)
{
if (classMapInitializer == null)
{
throw new ArgumentNullException(nameof(classMapInitializer));
}
return TryRegisterClassMap(ClassMapFactory);
BsonClassMap<TClass> ClassMapFactory()
{
return new BsonClassMap<TClass>(classMapInitializer);
}
}
/// <summary>
/// Registers a | map |
csharp | dotnet__aspnetcore | src/Security/samples/StaticFilesAuth/Startup.cs | {
"start": 302,
"end": 5739
} | public class ____
{
public Startup(IConfiguration configuration, IWebHostEnvironment hostingEnvironment)
{
Configuration = configuration;
HostingEnvironment = hostingEnvironment;
}
public IConfiguration Configuration { get; }
public IWebHostEnvironment HostingEnvironment { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
services.AddAuthorization(options =>
{
var basePath = Path.Combine(HostingEnvironment.ContentRootPath, "PrivateFiles");
var usersPath = Path.Combine(basePath, "Users");
// When using this policy users are only authorized to access the base directory, the Users directory,
// and their own directory under Users.
options.AddPolicy("files", builder =>
{
builder.RequireAuthenticatedUser().RequireAssertion(context =>
{
var userName = context.User.Identity.Name;
userName = userName?.Split('@').FirstOrDefault();
if (userName == null)
{
return false;
}
if (context.Resource is HttpContext httpContext && httpContext.GetEndpoint() is Endpoint endpoint)
{
var userPath = Path.Combine(usersPath, userName);
var directory = endpoint.Metadata.GetMetadata<DirectoryInfo>();
if (directory != null)
{
return string.Equals(directory.FullName, basePath, StringComparison.OrdinalIgnoreCase)
|| string.Equals(directory.FullName, usersPath, StringComparison.OrdinalIgnoreCase)
|| string.Equals(directory.FullName, userPath, StringComparison.OrdinalIgnoreCase)
|| directory.FullName.StartsWith(userPath + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase);
}
throw new InvalidOperationException($"Missing file system metadata.");
}
throw new InvalidOperationException($"Unknown resource type '{context.Resource.GetType()}'");
});
});
});
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAuthorizationService authorizationService)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
// Serve files from wwwroot without authentication or authorization.
app.UseStaticFiles();
app.UseAuthentication();
var files = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "PrivateFiles"));
app.Map("/MapAuthenticatedFiles", branch =>
{
branch.Use((context, next) => { SetFileEndpoint(context, files, null); return next(context); });
branch.UseAuthorization();
SetupFileServer(branch, files);
});
app.Map("/MapImperativeFiles", branch =>
{
branch.Use((context, next) => { SetFileEndpoint(context, files, "files"); return next(context); });
branch.UseAuthorization();
SetupFileServer(branch, files);
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
private void SetupFileServer(IApplicationBuilder builder, IFileProvider files)
{
builder.UseFileServer(new FileServerOptions()
{
EnableDirectoryBrowsing = true,
FileProvider = files
});
}
private static void SetFileEndpoint(HttpContext context, PhysicalFileProvider files, string policy)
{
var fileSystemPath = GetFileSystemPath(files, context.Request.Path);
if (fileSystemPath != null)
{
var metadata = new List<object>
{
new DirectoryInfo(Path.GetDirectoryName(fileSystemPath)),
new AuthorizeAttribute(policy)
};
var endpoint = new Endpoint(
requestDelegate: null,
new EndpointMetadataCollection(metadata),
context.Request.Path);
context.SetEndpoint(endpoint);
}
}
private static string GetFileSystemPath(PhysicalFileProvider files, string path)
{
var fileInfo = files.GetFileInfo(path);
if (fileInfo.Exists)
{
return Path.Join(files.Root, path);
}
else
{
// https://github.com/aspnet/Home/issues/2537
var dir = files.GetDirectoryContents(path);
if (dir.Exists)
{
return Path.Join(files.Root, path);
}
}
return null;
}
}
| Startup |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.Extensions.Tests/Protoc/Services.cs | {
"start": 984923,
"end": 993219
} | partial class ____ : pb::IMessage<IdResponse>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<IdResponse> _parser = new pb::MessageParser<IdResponse>(() => new IdResponse());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<IdResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::ServiceStack.Extensions.Tests.Protoc.ServicesReflection.Descriptor.MessageTypes[74]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public IdResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public IdResponse(IdResponse other) : this() {
id_ = other.id_;
responseStatus_ = other.responseStatus_ != null ? other.responseStatus_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public IdResponse Clone() {
return new IdResponse(this);
}
/// <summary>Field number for the "Id" field.</summary>
public const int IdFieldNumber = 1;
private string id_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Id {
get { return id_; }
set {
id_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "ResponseStatus" field.</summary>
public const int ResponseStatusFieldNumber = 2;
private global::ServiceStack.Extensions.Tests.Protoc.ResponseStatus responseStatus_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::ServiceStack.Extensions.Tests.Protoc.ResponseStatus ResponseStatus {
get { return responseStatus_; }
set {
responseStatus_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as IdResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(IdResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Id != other.Id) return false;
if (!object.Equals(ResponseStatus, other.ResponseStatus)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Id.Length != 0) hash ^= Id.GetHashCode();
if (responseStatus_ != null) hash ^= ResponseStatus.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Id.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Id);
}
if (responseStatus_ != null) {
output.WriteRawTag(18);
output.WriteMessage(ResponseStatus);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Id.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Id);
}
if (responseStatus_ != null) {
output.WriteRawTag(18);
output.WriteMessage(ResponseStatus);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Id.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Id);
}
if (responseStatus_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ResponseStatus);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(IdResponse other) {
if (other == null) {
return;
}
if (other.Id.Length != 0) {
Id = other.Id;
}
if (other.responseStatus_ != null) {
if (responseStatus_ == null) {
ResponseStatus = new global::ServiceStack.Extensions.Tests.Protoc.ResponseStatus();
}
ResponseStatus.MergeFrom(other.ResponseStatus);
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Id = input.ReadString();
break;
}
case 18: {
if (responseStatus_ == null) {
ResponseStatus = new global::ServiceStack.Extensions.Tests.Protoc.ResponseStatus();
}
input.ReadMessage(ResponseStatus);
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Id = input.ReadString();
break;
}
case 18: {
if (responseStatus_ == null) {
ResponseStatus = new global::ServiceStack.Extensions.Tests.Protoc.ResponseStatus();
}
input.ReadMessage(ResponseStatus);
break;
}
}
}
}
#endif
}
public sealed | IdResponse |
csharp | microsoft__PowerToys | src/modules/AdvancedPaste/AdvancedPaste/Services/EnhancedVaultCredentialsProvider.cs | {
"start": 576,
"end": 660
} | public sealed class ____ : IAICredentialsProvider
{
| EnhancedVaultCredentialsProvider |
csharp | dotnet__orleans | src/Orleans.Serialization/Serializers/ICodecSelector.cs | {
"start": 687,
"end": 1137
} | public interface ____
{
/// <summary>
/// The well-known copier name, used to match an instance with a copier.
/// </summary>
public string CopierName { get; }
/// <summary>
/// Returns true if the specified copier should be used for this type.
/// </summary>
public bool IsSupportedType(Type type);
}
/// <summary>
/// Implementation of <see cref="ICodecSelector"/> which uses a delegate.
/// </summary>
| ICopierSelector |
csharp | abpframework__abp | modules/feature-management/src/Volo.Abp.FeatureManagement.EntityFrameworkCore/Volo/Abp/FeatureManagement/EntityFrameworkCore/FeatureManagementDbContext.cs | {
"start": 283,
"end": 895
} | public class ____ : AbpDbContext<FeatureManagementDbContext>, IFeatureManagementDbContext
{
public DbSet<FeatureGroupDefinitionRecord> FeatureGroups { get; set; }
public DbSet<FeatureDefinitionRecord> Features { get; set; }
public DbSet<FeatureValue> FeatureValues { get; set; }
public FeatureManagementDbContext(DbContextOptions<FeatureManagementDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.ConfigureFeatureManagement();
}
}
| FeatureManagementDbContext |
csharp | dotnet__reactive | Rx.NET/Source/tests/Tests.System.Reactive/Tests/Concurrency/VirtualSchedulerTest.cs | {
"start": 614,
"end": 7433
} | private class ____ : VirtualTimeScheduler<string, char>
{
public VirtualSchedulerTestScheduler()
{
}
public VirtualSchedulerTestScheduler(string initialClock, IComparer<string> comparer)
: base(initialClock, comparer)
{
}
protected override string Add(string absolute, char relative)
{
return (absolute ?? string.Empty) + relative;
}
protected override DateTimeOffset ToDateTimeOffset(string absolute)
{
return new DateTimeOffset((absolute ?? string.Empty).Length, TimeSpan.Zero);
}
protected override char ToRelative(TimeSpan timeSpan)
{
return (char)(timeSpan.Ticks % char.MaxValue);
}
}
[TestMethod]
public void Virtual_Now()
{
var res = new VirtualSchedulerTestScheduler().Now - DateTime.Now;
Assert.True(res.Seconds < 1);
}
[TestMethod]
public void Virtual_ScheduleAction()
{
var id = Environment.CurrentManagedThreadId;
var ran = false;
var scheduler = new VirtualSchedulerTestScheduler();
scheduler.Schedule(() => { Assert.Equal(id, Environment.CurrentManagedThreadId); ran = true; });
scheduler.Start();
Assert.True(ran);
}
[TestMethod]
public void Virtual_ScheduleActionError()
{
var ex = new Exception();
try
{
var scheduler = new VirtualSchedulerTestScheduler();
scheduler.Schedule(() => { throw ex; });
scheduler.Start();
Assert.True(false);
}
catch (Exception e)
{
Assert.Same(e, ex);
}
}
[TestMethod]
public void Virtual_InitialAndComparer_Now()
{
var s = new VirtualSchedulerTestScheduler("Bar", Comparer<string>.Default);
Assert.Equal(3, s.Now.Ticks);
}
[TestMethod]
public void Virtual_ArgumentChecking()
{
#pragma warning disable CA1806 // (Unused new instance.) We expect the constructor to throw.
ReactiveAssert.Throws<ArgumentNullException>(() => new VirtualSchedulerTestScheduler("", null));
ReactiveAssert.Throws<ArgumentNullException>(() => new VirtualSchedulerTestScheduler().ScheduleRelative(0, 'a', null));
ReactiveAssert.Throws<ArgumentNullException>(() => new VirtualSchedulerTestScheduler().ScheduleAbsolute(0, "", null));
ReactiveAssert.Throws<ArgumentNullException>(() => new VirtualSchedulerTestScheduler().Schedule(0, default));
ReactiveAssert.Throws<ArgumentNullException>(() => new VirtualSchedulerTestScheduler().Schedule(0, TimeSpan.Zero, default));
ReactiveAssert.Throws<ArgumentNullException>(() => new VirtualSchedulerTestScheduler().Schedule(0, DateTimeOffset.UtcNow, default));
#pragma warning restore CA1806
ReactiveAssert.Throws<ArgumentNullException>(() => VirtualTimeSchedulerExtensions.ScheduleAbsolute(default(VirtualSchedulerTestScheduler), "", () => { }));
ReactiveAssert.Throws<ArgumentNullException>(() => VirtualTimeSchedulerExtensions.ScheduleAbsolute(new VirtualSchedulerTestScheduler(), "", default));
ReactiveAssert.Throws<ArgumentNullException>(() => VirtualTimeSchedulerExtensions.ScheduleRelative(default(VirtualSchedulerTestScheduler), 'a', () => { }));
ReactiveAssert.Throws<ArgumentNullException>(() => VirtualTimeSchedulerExtensions.ScheduleRelative(new VirtualSchedulerTestScheduler(), 'a', default));
}
[TestMethod]
public void Historical_ArgumentChecking()
{
#pragma warning disable CA1806 // (Unused new instance.) We expect the constructor to throw.
ReactiveAssert.Throws<ArgumentNullException>(() => new HistoricalScheduler(DateTime.Now, default));
#pragma warning restore CA1806
ReactiveAssert.Throws<ArgumentNullException>(() => new HistoricalScheduler().ScheduleAbsolute(42, DateTime.Now, default));
ReactiveAssert.Throws<ArgumentNullException>(() => new HistoricalScheduler().ScheduleRelative(42, TimeSpan.FromSeconds(1), default));
}
[TestMethod]
public void Virtual_ScheduleActionDue()
{
var id = Environment.CurrentManagedThreadId;
var ran = false;
var scheduler = new VirtualSchedulerTestScheduler();
scheduler.Schedule(TimeSpan.FromSeconds(0.2), () => { Assert.Equal(id, Environment.CurrentManagedThreadId); ran = true; });
scheduler.Start();
Assert.True(ran, "ran");
}
[TestMethod]
[TestCategory("SkipCI")]
public void Virtual_ThreadSafety()
{
for (var i = 0; i < 10; i++)
{
var scheduler = new TestScheduler();
var seq = Observable.Never<string>();
var disposable = default(IDisposable);
var sync = 2;
Task.Run(() =>
{
if (Interlocked.Decrement(ref sync) != 0)
{
while (Volatile.Read(ref sync) != 0)
{
;
}
}
Task.Delay(10).Wait();
disposable = seq.Timeout(TimeSpan.FromSeconds(5), scheduler).Subscribe(s => { });
});
var watch = scheduler.StartStopwatch();
try
{
if (Interlocked.Decrement(ref sync) != 0)
{
while (Volatile.Read(ref sync) != 0)
{
;
}
}
var d = default(IDisposable);
while (watch.Elapsed < TimeSpan.FromSeconds(100))
{
d = Volatile.Read(ref disposable);
scheduler.AdvanceBy(50);
}
if (d != null)
{
throw new Exception("Should have thrown!");
}
}
catch (TimeoutException)
{
}
catch (Exception ex)
{
Assert.True(false, string.Format("Virtual time {0}, exception {1}", watch.Elapsed, ex));
}
disposable?.Dispose();
}
}
}
}
| VirtualSchedulerTestScheduler |
csharp | dotnet__maui | src/Compatibility/Core/src/WPF/Controls/FormsAppBar.cs | {
"start": 336,
"end": 1602
} | public class ____ : ContentControl
{
ToggleButton btnMore;
public static readonly DependencyProperty PrimaryCommandsProperty = DependencyProperty.Register("PrimaryCommands", typeof(IEnumerable<FrameworkElement>), typeof(FormsAppBar), new PropertyMetadata(new List<FrameworkElement>()));
public static readonly DependencyProperty SecondaryCommandsProperty = DependencyProperty.Register("SecondaryCommands", typeof(IEnumerable<FrameworkElement>), typeof(FormsAppBar), new PropertyMetadata(new List<FrameworkElement>()));
public IEnumerable<FrameworkElement> PrimaryCommands
{
get { return (IEnumerable<FrameworkElement>)GetValue(PrimaryCommandsProperty); }
set { SetValue(PrimaryCommandsProperty, value); }
}
public IEnumerable<FrameworkElement> SecondaryCommands
{
get { return (IEnumerable<FrameworkElement>)GetValue(SecondaryCommandsProperty); }
set { SetValue(SecondaryCommandsProperty, value); }
}
public FormsAppBar()
{
this.DefaultStyleKey = typeof(FormsAppBar);
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
btnMore = Template.FindName("PART_More", this) as ToggleButton;
}
public void Reset()
{
if (btnMore != null)
{
btnMore.IsChecked = false;
}
}
}
}
| FormsAppBar |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Adapters/src/Adapters.Mcp.Core/Handlers/ReadResourceHandler.cs | {
"start": 267,
"end": 1421
} | internal static class ____
{
public static ReadResourceResult Handle(RequestContext<ReadResourceRequestParams> context)
{
var toolRegistry = context.Services!.GetRequiredService<ToolRegistry>();
if (!toolRegistry.TryGetToolByOpenAiComponentResourceUri(context.Params!.Uri, out var tool))
{
// TODO: See https://github.com/modelcontextprotocol/csharp-sdk/issues/1025.
throw new McpProtocolException(
string.Format(ReadResourceHandler_ResourceWithUriNotFound, context.Params.Uri),
// TODO: See https://github.com/modelcontextprotocol/csharp-sdk/issues/863.
(McpErrorCode)(-32002));
}
return new ReadResourceResult
{
Contents =
[
new TextResourceContents
{
Uri = tool.OpenAiComponentResource!.Uri,
MimeType = tool.OpenAiComponentResource!.MimeType,
Text = tool.OpenAiComponentHtml!,
Meta = tool.OpenAiComponentResource!.Meta
}
]
};
}
}
| ReadResourceHandler |
csharp | NLog__NLog | src/NLog/Targets/FileTarget.cs | {
"start": 2429,
"end": 22691
} | public class ____ : TargetWithLayoutHeaderAndFooter
{
/// <summary>
/// Gets or sets the name of the file to write to.
/// </summary>
/// <remarks>
/// <b>[Required]</b> Default: <see cref="Layout.Empty"/> .
/// When not absolute path then relative path will be resolved against <see cref="AppDomain.BaseDirectory"/>.
/// The FileName Layout supports layout-renderers, where a single FileTarget can write to multiple files.
/// </remarks>
/// <example>
/// The following value makes NLog write logging events to files based on the log level in the directory where
/// the application runs.
/// <code>${basedir}/${level}.log</code>
/// All <c>Debug</c> messages will go to <c>Debug.log</c>, all <c>Info</c> messages will go to <c>Info.log</c> and so on.
/// You can combine as many of the layout renderers as you want to produce an arbitrary log file name.
/// </example>
/// <docgen category='General Options' order='2' />
public Layout FileName
{
get => _fileName;
set
{
_fileName = value;
_fixedFileName = (value is SimpleLayout simpleLayout && simpleLayout.IsFixedText) ? simpleLayout.FixedText : null;
}
}
private Layout _fileName = Layout.Empty;
private string? _fixedFileName;
/// <summary>
/// Gets or sets a value indicating whether to create directories if they do not exist.
/// </summary>
/// <remarks>
/// Default: <see langword="true"/> .
/// Setting this to <see langword="false"/> may improve performance a bit, but will always fail
/// when attempt writing to a non-existing directory.
/// </remarks>
/// <docgen category='Output Options' order='50' />
public bool CreateDirs { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether to delete old log file on startup.
/// </summary>
/// <remarks>
/// Default: <see langword="false"/> .
/// When current log-file exists, then it is deleted (and resetting sequence number)
/// </remarks>
/// <docgen category='Output Options' order='50' />
public bool DeleteOldFileOnStartup { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to replace file contents on each write instead of appending log message at the end.
/// </summary>
/// <remarks>Default: <see langword="false"/></remarks>
/// <docgen category='Output Options' order='100' />
public bool ReplaceFileContentsOnEachWrite { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to keep log file open instead of opening and closing it on each logging event.
/// </summary>
/// <remarks>
/// Default: <see langword="true"/> .
/// KeepFileOpen = <see langword="true"/> gives the best performance, and ensure the file-lock is not lost to other applications.<br/>
/// KeepFileOpen = <see langword="false"/> gives the best compatibility, but slow performance and lead to file-locking issues with other applications.
/// </remarks>
/// <docgen category='Performance Tuning Options' order='10' />
public bool KeepFileOpen { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether to enable log file(s) to be deleted.
/// </summary>
/// <remarks>Default: <see langword="true"/></remarks>
/// <docgen category='Output Options' order='50' />
public bool EnableFileDelete { get; set; } = true;
/// <summary>
/// Gets or sets the line ending mode.
/// </summary>
/// <remarks>Default: <see cref="LineEndingMode.Default"/></remarks>
/// <docgen category='Output Options' order='100' />
public LineEndingMode LineEnding { get; set; } = LineEndingMode.Default;
/// <summary>
/// Gets or sets a value indicating whether to automatically flush the file buffers after each log message.
/// </summary>
/// <remarks>Default: <see langword="true"/></remarks>
/// <docgen category='Performance Tuning Options' order='50' />
public bool AutoFlush { get; set; } = true;
/// <summary>
/// Gets or sets the maximum number of files to be kept open.
/// </summary>
/// <remarks>
/// Default: <see langword="5"/> . Higher number might improve performance when single FileTarget
/// is writing to many files (such as splitting by loglevel or by logger-name).
/// Files are closed in LRU (least recently used) ordering, so files unused
/// for longest period are closed first. Careful with number higher than 10-15,
/// because a large number of open files consumes system resources.
/// </remarks>
/// <docgen category='Performance Tuning Options' order='10' />
public int OpenFileCacheSize { get; set; } = 5;
/// <summary>
/// Gets or sets the maximum number of seconds that files are kept open. Zero or negative means disabled.
/// </summary>
/// <remarks>Default: <see langword="0"/></remarks>
/// <docgen category='Performance Tuning Options' order='50' />
public int OpenFileCacheTimeout { get; set; }
/// <summary>
/// Gets or sets the maximum number of seconds before open files are flushed. Zero or negative means disabled.
/// </summary>
/// <remarks>Default: <see langword="0"/></remarks>
/// <docgen category='Performance Tuning Options' order='50' />
public int OpenFileFlushTimeout { get; set; }
/// <summary>
/// Gets or sets the log file buffer size in bytes.
/// </summary>
/// <remarks>Default: <see langword="32768"/></remarks>
/// <docgen category='Performance Tuning Options' order='50' />
public int BufferSize { get; set; } = 32768;
/// <summary>
/// Gets or sets the file encoding.
/// </summary>
/// <remarks>Default: <see cref="Encoding.UTF8"/></remarks>
/// <docgen category='Output Options' order='10' />
public Encoding Encoding
{
get => _encoding;
set
{
_encoding = value;
if (!_writeBom.HasValue && InitialValueBom(value))
_writeBom = true;
}
}
private Encoding _encoding = Encoding.UTF8;
/// <summary>
/// Gets or sets whether or not this target should just discard all data that its asked to write.
/// Mostly used for when testing NLog Stack except final write
/// </summary>
/// <remarks>Default: <see langword="false"/></remarks>
/// <docgen category='Output Options' order='100' />
public bool DiscardAll { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to write BOM (byte order mark) in created files.
/// </summary>
/// <remarks>Default: <see langword="false"/> (Unless UTF16 / UTF32)</remarks>
/// <docgen category='Output Options' order='50' />
public bool WriteBom
{
get => _writeBom ?? false;
set => _writeBom = value;
}
private bool? _writeBom;
/// <summary>
/// Gets or sets a value indicating whether any existing log-file should be archived on startup.
/// </summary>
/// <remarks>Default: <see langword="false"/></remarks>
/// <docgen category='Archival Options' order='50' />
public bool ArchiveOldFileOnStartup { get; set; }
/// <summary>
/// Gets or sets whether to write the Header on initial creation of file appender, even if the file is not empty.
/// Default value is <see langword="false"/>, which means only write header when initial file is empty (Ex. ensures valid CSV files)
/// </summary>
/// <remarks>
/// Default: <see langword="false"/> .
/// Alternative use <see cref="ArchiveOldFileOnStartup"/> to ensure each application session gets individual log-file.
/// </remarks>
/// <docgen category='Archival Options' order='50' />
public bool WriteHeaderWhenInitialFileNotEmpty { get; set; }
/// <summary>
/// Gets or sets a value specifying the date format when using <see cref="ArchiveFileName"/>.
/// Obsolete and only here for Legacy reasons, instead use <see cref="ArchiveSuffixFormat"/>.
/// </summary>
/// <remarks>Default: <see langword="null"/></remarks>
/// <docgen category='Archival Options' order='50' />
[Obsolete("Instead use ArchiveSuffixFormat. Marked obsolete with NLog 6.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
public string? ArchiveDateFormat
{
get => _archiveDateFormat;
set
{
if (string.Equals(value, _archiveDateFormat))
return;
if (!string.IsNullOrEmpty(value))
ArchiveSuffixFormat = @"_{1:" + value + @"}_{0:00}";
_archiveDateFormat = value;
}
}
private string? _archiveDateFormat;
/// <summary>
/// Gets or sets the size in bytes above which log files will be automatically archived. Zero or negative means disabled.
/// </summary>
/// <remarks>Default: <see langword="0"/></remarks>
/// <docgen category='Archival Options' order='50' />
public long ArchiveAboveSize
{
get => _archiveAboveSize;
set
{
_archiveAboveSize = value > 0 ? value : 0;
_fileArchiveHandler = null;
}
}
private long _archiveAboveSize;
/// <summary>
/// Gets or sets a value indicating whether to trigger archive operation based on time-period, by moving active-file to file-path specified by <see cref="ArchiveFileName"/>
/// </summary>
/// <remarks>
/// Default: <see cref="FileArchivePeriod.None"/> .
/// Archive move operation only works if <see cref="FileName"/> is static in nature, and not rolling automatically because of ${date} or ${shortdate}
///
/// NLog FileTarget probes the file-birthtime to recognize when time-period has passed, but file-birthtime is not supported by all filesystems.
/// </remarks>
/// <docgen category='Archival Options' order='50' />
public FileArchivePeriod ArchiveEvery
{
get => _archiveEvery;
set
{
_archiveEvery = value;
_fileArchiveHandler = null;
}
}
FileArchivePeriod _archiveEvery;
/// <summary>
/// Legacy archive logic where file-archive-logic moves active file to path specified by <see cref="ArchiveFileName"/>, and then recreates the active file.
///
/// Use <see cref="ArchiveSuffixFormat"/> to control suffix format, instead of now obsolete token {#}
/// </summary>
/// <remarks>
/// Default: <see langword="null"/> .
/// Archive file-move operation only works if <see cref="FileName"/> is static in nature, and not rolling automatically because of ${date} or ${shortdate} .
///
/// Legacy archive file-move operation can fail because of file-locks, so file-archiving can stop working because of environment issues (Other applications locking files).
///
/// Avoid using <see cref="ArchiveFileName"/> when possible, and instead rely on only using <see cref="FileName"/> and <see cref="ArchiveSuffixFormat"/>.
/// </remarks>
/// <docgen category='Archival Options' order='50' />
public Layout? ArchiveFileName
{
get => _archiveFileName ?? (_archiveSuffixFormatLegacy ? FileName : null);
set
{
var archiveSuffixFormat = _archiveSuffixFormat;
if (value is SimpleLayout simpleLayout)
{
if (simpleLayout.OriginalText.IndexOf("${date", StringComparison.OrdinalIgnoreCase) >= 0 || simpleLayout.OriginalText.IndexOf("${shortdate", StringComparison.OrdinalIgnoreCase) >= 0)
{
if (_archiveSuffixFormat is null || ReferenceEquals(_legacySequenceArchiveSuffixFormat, _archiveSuffixFormat) || ReferenceEquals(_legacyDateArchiveSuffixFormat, _archiveSuffixFormat))
{
archiveSuffixFormat = "_{0}";
}
}
if (simpleLayout.OriginalText.Contains('#'))
{
var repairLegacyLayout = simpleLayout.OriginalText.Replace(".{#}", string.Empty).Replace("_{#}", "").Replace("-{#}", "").Replace("{#}", "").Replace(".{#", "").Replace("_{#", "").Replace("-{#", "").Replace("{#", "").Replace("#}", "").Replace("#", "");
archiveSuffixFormat = _archiveSuffixFormat ?? _legacySequenceArchiveSuffixFormat;
value = new SimpleLayout(repairLegacyLayout);
}
}
_archiveFileName = value;
if (!ReferenceEquals(_archiveSuffixFormat, archiveSuffixFormat) && archiveSuffixFormat != null)
{
ArchiveSuffixFormat = archiveSuffixFormat;
}
_fileArchiveHandler = null;
}
}
private Layout? _archiveFileName;
private static readonly string _legacyDateArchiveSuffixFormat = "_{1:yyyyMMdd}_{0:00}"; // Cater for ArchiveNumbering.DateAndSequence
private static readonly string _legacySequenceArchiveSuffixFormat = "_{0:00}"; // Cater for ArchiveNumbering.Sequence
/// <summary>
/// Gets or sets the maximum number of archive files that should be kept. Negative means disabled.
/// </summary>
/// <remarks>Default: <see langword="-1"/></remarks>
/// <docgen category='Archival Options' order='50' />
public int MaxArchiveFiles
{
get => _maxArchiveFiles;
set
{
_maxArchiveFiles = value;
_fileArchiveHandler = null;
}
}
private int _maxArchiveFiles = -1;
/// <summary>
/// Gets or sets the maximum days of archive files that should be kept. Zero or negative means disabled.
/// </summary>
/// <remarks>Default: <see langword="0"/></remarks>
/// <docgen category='Archival Options' order='50' />
public int MaxArchiveDays
{
get => _maxArchiveDays;
set
{
_maxArchiveDays = value > 0 ? value : 0;
_fileArchiveHandler = null;
}
}
private int _maxArchiveDays;
/// <summary>
/// Gets or sets the way file archives are numbered.
/// Obsolete and only here for Legacy reasons, instead use <see cref="ArchiveSuffixFormat"/>.
/// </summary>
/// <remarks>Default: <c>Sequence</c></remarks>
/// <docgen category='Archival Options' order='50' />
[Obsolete("Instead use ArchiveSuffixFormat. Marked obsolete with NLog 6.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
public string ArchiveNumbering
{
get => _archiveNumbering ?? "Sequence";
set
{
if (string.Equals(value, _archiveNumbering))
return;
_archiveNumbering = string.IsNullOrEmpty(value) ? null : value.Trim();
if (_archiveNumbering is null || string.IsNullOrEmpty(_archiveNumbering))
return;
if (_archiveSuffixFormat is null || ReferenceEquals(_archiveSuffixFormat, _legacyDateArchiveSuffixFormat) || ReferenceEquals(_archiveSuffixFormat, _legacySequenceArchiveSuffixFormat))
{
ArchiveSuffixFormat = _archiveNumbering.IndexOf("date", StringComparison.OrdinalIgnoreCase) >= 0 ? _legacyDateArchiveSuffixFormat : _legacySequenceArchiveSuffixFormat;
}
}
}
private string? _archiveNumbering;
/// <summary>
/// Gets or sets the format-string to convert archive sequence-number by using string.Format
/// </summary>
/// <remarks>
/// Default: <c>_{0:00}</c> .
/// Ex. to prefix archive sequence number with leading zero's then one can use _{0:000} .
///
/// Legacy archive-logic with <see cref="ArchiveFileName"/> can use suffix _{1:yyyyMMdd}_{0:00} .
/// </remarks>
/// <docgen category='Archival Options' order='50' />
public string ArchiveSuffixFormat
{
get
{
if (ArchiveEvery != FileArchivePeriod.None && (_archiveSuffixFormat is null || ReferenceEquals(_legacyDateArchiveSuffixFormat, _archiveSuffixFormat) || ReferenceEquals(_legacySequenceArchiveSuffixFormat, _archiveSuffixFormat)) && ArchiveFileName != null)
{
switch (ArchiveEvery)
{
case FileArchivePeriod.Year:
return "_{1:yyyy}_{0:00}";
case FileArchivePeriod.Month:
return "_{1:yyyyMM}_{0:00}";
case FileArchivePeriod.Hour:
return "_{1:yyyyMMddHH}_{0:00}";
case FileArchivePeriod.Minute:
return "_{1:yyyyMMddHHmm}_{0:00}";
default:
return _legacyDateArchiveSuffixFormat; // Also for weekdays
}
}
return _archiveSuffixFormat ?? _legacySequenceArchiveSuffixFormat;
}
set
{
if (!string.IsNullOrEmpty(value) && ArchiveFileName is SimpleLayout simpleLayout)
{
// When legacy ArchiveFileName only contains file-extension, then strip away leading underscore from suffix
var fileName = Path.GetFileNameWithoutExtension(simpleLayout.OriginalText);
if (StringHelpers.IsNullOrWhiteSpace(fileName) && value.IndexOf('_') == 0)
{
value = value.Substring(1);
}
}
_archiveSuffixFormat = value;
_archiveSuffixFormatLegacy = _archiveSuffixFormat?.IndexOf("{1", StringComparison.Ordinal) >= 0;
}
}
private string? _archiveSuffixFormat;
private bool _archiveSuffixFormatLegacy;
/// <summary>
/// Gets or sets a value indicating whether the footer should be written only when the file is archived.
/// </summary>
/// <remarks>Default: <see langword="false"/></remarks>
/// <docgen category='Archival Options' order='50' />
public bool WriteFooterOnArchivingOnly { get; set; }
private int OpenFileMonitorTimerInterval
{
get
{
if (OpenFileFlushTimeout <= 0 || AutoFlush || !KeepFileOpen)
return (OpenFileCacheTimeout > 500 && OpenFileCacheTimeout < 3600) ? 300 : OpenFileCacheTimeout;
else if (OpenFileCacheTimeout <= 0)
return OpenFileFlushTimeout;
else
return Math.Min(OpenFileFlushTimeout, OpenFileCacheTimeout);
}
}
private IFileArchiveHandler FileAchiveHandler => _fileArchiveHandler ?? (_fileArchiveHandler = CreateFileArchiveHandler());
private IFileArchiveHandler? _fileArchiveHandler;
private
#if !NETFRAMEWORK
readonly
#endif | FileTarget |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler.Tests/TestCases/Pretty/Loops.cs | {
"start": 1323,
"end": 1365
} | public class ____
{
#region foreach
| Loops |
csharp | abpframework__abp | framework/src/Volo.Abp.Caching/Volo/Abp/Caching/DistributedCache.cs | {
"start": 6358,
"end": 51452
} | class
____ TCacheKey : notnull
{
public const string UowCacheName = "AbpDistributedCache";
public ILogger<DistributedCache<TCacheItem, TCacheKey>> Logger { get; set; }
protected string CacheName { get; set; } = default!;
protected bool IgnoreMultiTenancy { get; set; }
protected IDistributedCache Cache { get; }
protected ICancellationTokenProvider CancellationTokenProvider { get; }
protected IDistributedCacheSerializer Serializer { get; }
protected IDistributedCacheKeyNormalizer KeyNormalizer { get; }
protected IServiceScopeFactory ServiceScopeFactory { get; }
protected IUnitOfWorkManager UnitOfWorkManager { get; }
protected SemaphoreSlim SyncSemaphore { get; }
protected DistributedCacheEntryOptions DefaultCacheOptions = default!;
private readonly AbpDistributedCacheOptions _distributedCacheOption;
public DistributedCache(
IOptions<AbpDistributedCacheOptions> distributedCacheOption,
IDistributedCache cache,
ICancellationTokenProvider cancellationTokenProvider,
IDistributedCacheSerializer serializer,
IDistributedCacheKeyNormalizer keyNormalizer,
IServiceScopeFactory serviceScopeFactory,
IUnitOfWorkManager unitOfWorkManager)
{
_distributedCacheOption = distributedCacheOption.Value;
Cache = cache;
CancellationTokenProvider = cancellationTokenProvider;
Logger = NullLogger<DistributedCache<TCacheItem, TCacheKey>>.Instance;
Serializer = serializer;
KeyNormalizer = keyNormalizer;
ServiceScopeFactory = serviceScopeFactory;
UnitOfWorkManager = unitOfWorkManager;
SyncSemaphore = new SemaphoreSlim(1, 1);
SetDefaultOptions();
}
protected virtual string NormalizeKey(TCacheKey key)
{
return KeyNormalizer.NormalizeKey(
new DistributedCacheKeyNormalizeArgs(
key.ToString()!,
CacheName,
IgnoreMultiTenancy
)
);
}
protected virtual DistributedCacheEntryOptions GetDefaultCacheEntryOptions()
{
foreach (var configure in _distributedCacheOption.CacheConfigurators)
{
var options = configure.Invoke(CacheName);
if (options != null)
{
return options;
}
}
return _distributedCacheOption.GlobalCacheEntryOptions;
}
protected virtual void SetDefaultOptions()
{
CacheName = CacheNameAttribute.GetCacheName(typeof(TCacheItem));
//IgnoreMultiTenancy
IgnoreMultiTenancy = typeof(TCacheItem).IsDefined(typeof(IgnoreMultiTenancyAttribute), true);
//Configure default cache entry options
DefaultCacheOptions = GetDefaultCacheEntryOptions();
}
/// <summary>
/// Gets a cache item with the given key. If no cache item is found for the given key then returns null.
/// </summary>
/// <param name="key">The key of cached item to be retrieved from the cache.</param>
/// <param name="hideErrors">Indicates to throw or hide the exceptions for the distributed cache.</param>
/// <param name="considerUow">This will store the cache in the current unit of work until the end of the current unit of work does not really affect the cache.</param>
/// <returns>The cache item, or null.</returns>
public virtual TCacheItem? Get(
TCacheKey key,
bool? hideErrors = null,
bool considerUow = false)
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
if (ShouldConsiderUow(considerUow))
{
var value = GetUnitOfWorkCache().GetOrDefault(key)?.GetUnRemovedValueOrNull();
if (value != null)
{
return value;
}
}
byte[]? cachedBytes;
try
{
cachedBytes = Cache.Get(NormalizeKey(key));
}
catch (Exception ex)
{
if (hideErrors == true)
{
HandleException(ex);
return null;
}
throw;
}
return ToCacheItem(cachedBytes);
}
public virtual KeyValuePair<TCacheKey, TCacheItem?>[] GetMany(
IEnumerable<TCacheKey> keys,
bool? hideErrors = null,
bool considerUow = false)
{
var keyArray = keys.ToArray();
var cacheSupportsMultipleItems = Cache as ICacheSupportsMultipleItems;
if (cacheSupportsMultipleItems == null)
{
return GetManyFallback(
keyArray,
hideErrors,
considerUow
);
}
var notCachedKeys = new List<TCacheKey>();
var cachedValues = new List<KeyValuePair<TCacheKey, TCacheItem?>>();
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
foreach (var key in keyArray)
{
var value = uowCache.GetOrDefault(key)?.GetUnRemovedValueOrNull();
if (value != null)
{
cachedValues.Add(new KeyValuePair<TCacheKey, TCacheItem?>(key, value));
}
}
notCachedKeys = keyArray.Except(cachedValues.Select(x => x.Key)).ToList();
if (!notCachedKeys.Any())
{
return cachedValues.ToArray();
}
}
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
byte[]?[] cachedBytes;
var readKeys = notCachedKeys.Any() ? notCachedKeys.ToArray() : keyArray;
try
{
cachedBytes = cacheSupportsMultipleItems.GetMany(readKeys.Select(NormalizeKey));
}
catch (Exception ex)
{
if (hideErrors == true)
{
HandleException(ex);
return ToCacheItemsWithDefaultValues(keyArray);
}
throw;
}
return cachedValues.Concat(ToCacheItems(cachedBytes, readKeys)).ToArray();
}
protected virtual KeyValuePair<TCacheKey, TCacheItem?>[] GetManyFallback(
TCacheKey[] keys,
bool? hideErrors = null,
bool considerUow = false)
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
return keys
.Select(key => new KeyValuePair<TCacheKey, TCacheItem?>(
key,
Get(key, false, considerUow)
)
).ToArray();
}
catch (Exception ex)
{
if (hideErrors == true)
{
HandleException(ex);
return ToCacheItemsWithDefaultValues(keys);
}
throw;
}
}
public virtual async Task<KeyValuePair<TCacheKey, TCacheItem?>[]> GetManyAsync(
IEnumerable<TCacheKey> keys,
bool? hideErrors = null,
bool considerUow = false,
CancellationToken token = default)
{
var keyArray = keys.ToArray();
var cacheSupportsMultipleItems = Cache as ICacheSupportsMultipleItems;
if (cacheSupportsMultipleItems == null)
{
return await GetManyFallbackAsync(
keyArray,
hideErrors,
considerUow,
token
);
}
var notCachedKeys = new List<TCacheKey>();
var cachedValues = new List<KeyValuePair<TCacheKey, TCacheItem?>>();
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
foreach (var key in keyArray)
{
var value = uowCache.GetOrDefault(key)?.GetUnRemovedValueOrNull();
if (value != null)
{
cachedValues.Add(new KeyValuePair<TCacheKey, TCacheItem?>(key, value));
}
}
notCachedKeys = keyArray.Except(cachedValues.Select(x => x.Key)).ToList();
if (!notCachedKeys.Any())
{
return cachedValues.ToArray();
}
}
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
byte[]?[] cachedBytes;
var readKeys = notCachedKeys.Any() ? notCachedKeys.ToArray() : keyArray;
try
{
cachedBytes = await cacheSupportsMultipleItems.GetManyAsync(
readKeys.Select(NormalizeKey),
CancellationTokenProvider.FallbackToProvider(token)
);
}
catch (Exception ex)
{
if (hideErrors == true)
{
await HandleExceptionAsync(ex);
return ToCacheItemsWithDefaultValues(keyArray);
}
throw;
}
return cachedValues.Concat(ToCacheItems(cachedBytes, readKeys)).ToArray();
}
protected virtual async Task<KeyValuePair<TCacheKey, TCacheItem?>[]> GetManyFallbackAsync(
TCacheKey[] keys,
bool? hideErrors = null,
bool considerUow = false,
CancellationToken token = default)
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
var result = new List<KeyValuePair<TCacheKey, TCacheItem?>>();
foreach (var key in keys)
{
result.Add(new KeyValuePair<TCacheKey, TCacheItem?>(
key,
await GetAsync(key, false, considerUow, token: token))
);
}
return result.ToArray();
}
catch (Exception ex)
{
if (hideErrors == true)
{
await HandleExceptionAsync(ex);
return ToCacheItemsWithDefaultValues(keys);
}
throw;
}
}
/// <summary>
/// Gets a cache item with the given key. If no cache item is found for the given key then returns null.
/// </summary>
/// <param name="key">The key of cached item to be retrieved from the cache.</param>
/// <param name="hideErrors">Indicates to throw or hide the exceptions for the distributed cache.</param>
/// <param name="considerUow">This will store the cache in the current unit of work until the end of the current unit of work does not really affect the cache.</param>
/// <param name="token">The <see cref="T:System.Threading.CancellationToken" /> for the task.</param>
/// <returns>The cache item, or null.</returns>
public virtual async Task<TCacheItem?> GetAsync(
TCacheKey key,
bool? hideErrors = null,
bool considerUow = false,
CancellationToken token = default)
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
if (ShouldConsiderUow(considerUow))
{
var value = GetUnitOfWorkCache().GetOrDefault(key)?.GetUnRemovedValueOrNull();
if (value != null)
{
return value;
}
}
byte[]? cachedBytes;
try
{
cachedBytes = await Cache.GetAsync(
NormalizeKey(key),
CancellationTokenProvider.FallbackToProvider(token)
);
}
catch (Exception ex)
{
if (hideErrors == true)
{
await HandleExceptionAsync(ex);
return null;
}
throw;
}
if (cachedBytes == null)
{
return null;
}
return Serializer.Deserialize<TCacheItem>(cachedBytes);
}
/// <summary>
/// Gets or Adds a cache item with the given key. If no cache item is found for the given key then adds a cache item
/// provided by <paramref name="factory" /> delegate and returns the provided cache item.
/// </summary>
/// <param name="key">The key of cached item to be retrieved from the cache.</param>
/// <param name="factory">The factory delegate is used to provide the cache item when no cache item is found for the given <paramref name="key" />.</param>
/// <param name="optionsFactory">The cache options for the factory delegate.</param>
/// <param name="hideErrors">Indicates to throw or hide the exceptions for the distributed cache.</param>
/// <param name="considerUow">This will store the cache in the current unit of work until the end of the current unit of work does not really affect the cache.</param>
/// <returns>The cache item.</returns>
public virtual TCacheItem? GetOrAdd(
TCacheKey key,
Func<TCacheItem> factory,
Func<DistributedCacheEntryOptions>? optionsFactory = null,
bool? hideErrors = null,
bool considerUow = false)
{
var value = Get(key, hideErrors, considerUow);
if (value != null)
{
return value;
}
using (SyncSemaphore.Lock())
{
value = Get(key, hideErrors, considerUow);
if (value != null)
{
return value;
}
value = factory();
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
if (uowCache.TryGetValue(key, out var item))
{
item.SetValue(value);
}
else
{
uowCache.Add(key, new UnitOfWorkCacheItem<TCacheItem>(value));
}
}
Set(key, value, optionsFactory?.Invoke(), hideErrors, considerUow);
}
return value;
}
/// <summary>
/// Gets or Adds a cache item with the given key. If no cache item is found for the given key then adds a cache item
/// provided by <paramref name="factory" /> delegate and returns the provided cache item.
/// </summary>
/// <param name="key">The key of cached item to be retrieved from the cache.</param>
/// <param name="factory">The factory delegate is used to provide the cache item when no cache item is found for the given <paramref name="key" />.</param>
/// <param name="optionsFactory">The cache options for the factory delegate.</param>
/// <param name="hideErrors">Indicates to throw or hide the exceptions for the distributed cache.</param>
/// <param name="considerUow">This will store the cache in the current unit of work until the end of the current unit of work does not really affect the cache.</param>
/// <param name="token">The <see cref="T:System.Threading.CancellationToken" /> for the task.</param>
/// <returns>The cache item.</returns>
public virtual async Task<TCacheItem?> GetOrAddAsync(
TCacheKey key,
Func<Task<TCacheItem>> factory,
Func<DistributedCacheEntryOptions>? optionsFactory = null,
bool? hideErrors = null,
bool considerUow = false,
CancellationToken token = default)
{
token = CancellationTokenProvider.FallbackToProvider(token);
var value = await GetAsync(key, hideErrors, considerUow, token);
if (value != null)
{
return value;
}
using (await SyncSemaphore.LockAsync(token))
{
value = await GetAsync(key, hideErrors, considerUow, token);
if (value != null)
{
return value;
}
value = await factory();
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
if (uowCache.TryGetValue(key, out var item))
{
item.SetValue(value);
}
else
{
uowCache.Add(key, new UnitOfWorkCacheItem<TCacheItem>(value));
}
}
await SetAsync(key, value, optionsFactory?.Invoke(), hideErrors, considerUow, token);
}
return value;
}
public KeyValuePair<TCacheKey, TCacheItem?>[] GetOrAddMany(
IEnumerable<TCacheKey> keys,
Func<IEnumerable<TCacheKey>, List<KeyValuePair<TCacheKey, TCacheItem>>> factory,
Func<DistributedCacheEntryOptions>? optionsFactory = null,
bool? hideErrors = null,
bool considerUow = false)
{
KeyValuePair<TCacheKey, TCacheItem?>[] result;
var keyArray = keys.ToArray();
var cacheSupportsMultipleItems = Cache as ICacheSupportsMultipleItems;
if (cacheSupportsMultipleItems == null)
{
result = GetManyFallback(
keyArray,
hideErrors,
considerUow
);
}
else
{
var notCachedKeys = new List<TCacheKey>();
var cachedValues = new List<KeyValuePair<TCacheKey, TCacheItem?>>();
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
foreach (var key in keyArray)
{
var value = uowCache.GetOrDefault(key)?.GetUnRemovedValueOrNull();
if (value != null)
{
cachedValues.Add(new KeyValuePair<TCacheKey, TCacheItem?>(key, value));
}
}
notCachedKeys = keyArray.Except(cachedValues.Select(x => x.Key)).ToList();
if (!notCachedKeys.Any())
{
return cachedValues.ToArray();
}
}
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
byte[]?[] cachedBytes;
var readKeys = notCachedKeys.Any() ? notCachedKeys.ToArray() : keyArray;
try
{
cachedBytes = cacheSupportsMultipleItems.GetMany(readKeys.Select(NormalizeKey));
}
catch (Exception ex)
{
if (hideErrors == true)
{
HandleException(ex);
return ToCacheItemsWithDefaultValues(keyArray);
}
throw;
}
result = cachedValues.Concat(ToCacheItems(cachedBytes, readKeys)).ToArray();
}
if (result.All(x => x.Value != null))
{
return result!;
}
var missingKeys = new List<TCacheKey>();
var missingValuesIndex = new List<int>();
for (var i = 0; i < keyArray.Length; i++)
{
if (result[i].Value != null)
{
continue;
}
missingKeys.Add(keyArray[i]);
missingValuesIndex.Add(i);
}
var missingValues = factory.Invoke(missingKeys).ToArray();
var valueQueue = new Queue<KeyValuePair<TCacheKey, TCacheItem>>(missingValues);
SetMany(missingValues, optionsFactory?.Invoke(), hideErrors, considerUow);
foreach (var index in missingValuesIndex)
{
result[index] = valueQueue.Dequeue()!;
}
return result;
}
public async Task<KeyValuePair<TCacheKey, TCacheItem?>[]> GetOrAddManyAsync(
IEnumerable<TCacheKey> keys,
Func<IEnumerable<TCacheKey>, Task<List<KeyValuePair<TCacheKey, TCacheItem>>>> factory,
Func<DistributedCacheEntryOptions>? optionsFactory = null,
bool? hideErrors = null,
bool considerUow = false,
CancellationToken token = default)
{
KeyValuePair<TCacheKey, TCacheItem?>[] result;
var keyArray = keys.ToArray();
var cacheSupportsMultipleItems = Cache as ICacheSupportsMultipleItems;
if (cacheSupportsMultipleItems == null)
{
result = await GetManyFallbackAsync(
keyArray,
hideErrors,
considerUow, token);
}
else
{
var notCachedKeys = new List<TCacheKey>();
var cachedValues = new List<KeyValuePair<TCacheKey, TCacheItem?>>();
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
foreach (var key in keyArray)
{
var value = uowCache.GetOrDefault(key)?.GetUnRemovedValueOrNull();
if (value != null)
{
cachedValues.Add(new KeyValuePair<TCacheKey, TCacheItem?>(key, value));
}
}
notCachedKeys = keyArray.Except(cachedValues.Select(x => x.Key)).ToList();
if (!notCachedKeys.Any())
{
return cachedValues.ToArray();
}
}
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
byte[]?[] cachedBytes;
var readKeys = notCachedKeys.Any() ? notCachedKeys.ToArray() : keyArray;
try
{
cachedBytes = await cacheSupportsMultipleItems.GetManyAsync(readKeys.Select(NormalizeKey), token);
}
catch (Exception ex)
{
if (hideErrors == true)
{
await HandleExceptionAsync(ex);
return ToCacheItemsWithDefaultValues(keyArray);
}
throw;
}
result = cachedValues.Concat(ToCacheItems(cachedBytes, readKeys)).ToArray();
}
if (result.All(x => x.Value != null))
{
return result;
}
var missingKeys = new List<TCacheKey>();
var missingValuesIndex = new List<int>();
for (var i = 0; i < keyArray.Length; i++)
{
if (result[i].Value != null)
{
continue;
}
missingKeys.Add(keyArray[i]);
missingValuesIndex.Add(i);
}
var missingValues = (await factory.Invoke(missingKeys)).ToArray();
var valueQueue = new Queue<KeyValuePair<TCacheKey, TCacheItem>>(missingValues);
await SetManyAsync(missingValues, optionsFactory?.Invoke(), hideErrors, considerUow, token);
foreach (var index in missingValuesIndex)
{
result[index] = valueQueue.Dequeue()!;
}
return result;
}
/// <summary>
/// Sets the cache item value for the provided key.
/// </summary>
/// <param name="key">The key of cached item to be retrieved from the cache.</param>
/// <param name="value">The cache item value to set in the cache.</param>
/// <param name="options">The cache options for the value.</param>
/// <param name="hideErrors">Indicates to throw or hide the exceptions for the distributed cache.</param>
/// <param name="considerUow">This will store the cache in the current unit of work until the end of the current unit of work does not really affect the cache.</param>
public virtual void Set(
TCacheKey key,
TCacheItem value,
DistributedCacheEntryOptions? options = null,
bool? hideErrors = null,
bool considerUow = false)
{
void SetRealCache()
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
Cache.Set(
NormalizeKey(key),
Serializer.Serialize(value),
options ?? DefaultCacheOptions
);
}
catch (Exception ex)
{
if (hideErrors == true)
{
HandleException(ex);
return;
}
throw;
}
}
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
if (uowCache.TryGetValue(key, out _))
{
uowCache[key].SetValue(value);
}
else
{
uowCache.Add(key, new UnitOfWorkCacheItem<TCacheItem>(value));
}
UnitOfWorkManager.Current?.OnCompleted(() =>
{
SetRealCache();
return Task.CompletedTask;
});
}
else
{
SetRealCache();
}
}
/// <summary>
/// Sets the cache item value for the provided key.
/// </summary>
/// <param name="key">The key of cached item to be retrieved from the cache.</param>
/// <param name="value">The cache item value to set in the cache.</param>
/// <param name="options">The cache options for the value.</param>
/// <param name="hideErrors">Indicates to throw or hide the exceptions for the distributed cache.</param>
/// <param name="considerUow">This will store the cache in the current unit of work until the end of the current unit of work does not really affect the cache.</param>
/// <param name="token">The <see cref="T:System.Threading.CancellationToken" /> for the task.</param>
/// <returns>The <see cref="T:System.Threading.Tasks.Task" /> indicating that the operation is asynchronous.</returns>
public virtual async Task SetAsync(
TCacheKey key,
TCacheItem value,
DistributedCacheEntryOptions? options = null,
bool? hideErrors = null,
bool considerUow = false,
CancellationToken token = default)
{
async Task SetRealCache()
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
await Cache.SetAsync(
NormalizeKey(key),
Serializer.Serialize(value),
options ?? DefaultCacheOptions,
CancellationTokenProvider.FallbackToProvider(token)
);
}
catch (Exception ex)
{
if (hideErrors == true)
{
await HandleExceptionAsync(ex);
return;
}
throw;
}
}
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
if (uowCache.TryGetValue(key, out _))
{
uowCache[key].SetValue(value);
}
else
{
uowCache.Add(key, new UnitOfWorkCacheItem<TCacheItem>(value));
}
UnitOfWorkManager.Current?.OnCompleted(SetRealCache);
}
else
{
await SetRealCache();
}
}
public void SetMany(
IEnumerable<KeyValuePair<TCacheKey, TCacheItem>> items,
DistributedCacheEntryOptions? options = null,
bool? hideErrors = null,
bool considerUow = false)
{
var itemsArray = items.ToArray();
var cacheSupportsMultipleItems = Cache as ICacheSupportsMultipleItems;
if (cacheSupportsMultipleItems == null)
{
SetManyFallback(
itemsArray,
options,
hideErrors,
considerUow
);
return;
}
void SetRealCache()
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
cacheSupportsMultipleItems.SetMany(
ToRawCacheItems(itemsArray),
options ?? DefaultCacheOptions
);
}
catch (Exception ex)
{
if (hideErrors == true)
{
HandleException(ex);
return;
}
throw;
}
}
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
foreach (var pair in itemsArray)
{
if (uowCache.TryGetValue(pair.Key, out _))
{
uowCache[pair.Key].SetValue(pair.Value);
}
else
{
uowCache.Add(pair.Key, new UnitOfWorkCacheItem<TCacheItem>(pair.Value));
}
}
UnitOfWorkManager.Current?.OnCompleted(() =>
{
SetRealCache();
return Task.CompletedTask;
});
}
else
{
SetRealCache();
}
}
protected virtual void SetManyFallback(
KeyValuePair<TCacheKey, TCacheItem>[] items,
DistributedCacheEntryOptions? options = null,
bool? hideErrors = null,
bool considerUow = false)
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
foreach (var item in items)
{
Set(
item.Key,
item.Value,
options,
false,
considerUow
);
}
}
catch (Exception ex)
{
if (hideErrors == true)
{
HandleException(ex);
return;
}
throw;
}
}
public virtual async Task SetManyAsync(
IEnumerable<KeyValuePair<TCacheKey, TCacheItem>> items,
DistributedCacheEntryOptions? options = null,
bool? hideErrors = null,
bool considerUow = false,
CancellationToken token = default)
{
var itemsArray = items.ToArray();
var cacheSupportsMultipleItems = Cache as ICacheSupportsMultipleItems;
if (cacheSupportsMultipleItems == null)
{
await SetManyFallbackAsync(
itemsArray,
options,
hideErrors,
considerUow,
token
);
return;
}
async Task SetRealCache()
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
await cacheSupportsMultipleItems.SetManyAsync(
ToRawCacheItems(itemsArray),
options ?? DefaultCacheOptions,
CancellationTokenProvider.FallbackToProvider(token)
);
}
catch (Exception ex)
{
if (hideErrors == true)
{
await HandleExceptionAsync(ex);
return;
}
throw;
}
}
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
foreach (var pair in itemsArray)
{
if (uowCache.TryGetValue(pair.Key, out _))
{
uowCache[pair.Key].SetValue(pair.Value);
}
else
{
uowCache.Add(pair.Key, new UnitOfWorkCacheItem<TCacheItem>(pair.Value));
}
}
UnitOfWorkManager.Current?.OnCompleted(SetRealCache);
}
else
{
await SetRealCache();
}
}
protected virtual async Task SetManyFallbackAsync(
KeyValuePair<TCacheKey, TCacheItem>[] items,
DistributedCacheEntryOptions? options = null,
bool? hideErrors = null,
bool considerUow = false,
CancellationToken token = default)
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
foreach (var item in items)
{
await SetAsync(
item.Key,
item.Value,
options,
false,
considerUow,
token: token
);
}
}
catch (Exception ex)
{
if (hideErrors == true)
{
await HandleExceptionAsync(ex);
return;
}
throw;
}
}
/// <summary>
/// Refreshes the cache value of the given key, and resets its sliding expiration timeout.
/// </summary>
/// <param name="key">The key of cached item to be retrieved from the cache.</param>
/// <param name="hideErrors">Indicates to throw or hide the exceptions for the distributed cache.</param>
public virtual void Refresh(
TCacheKey key,
bool? hideErrors = null)
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
Cache.Refresh(NormalizeKey(key));
}
catch (Exception ex)
{
if (hideErrors == true)
{
HandleException(ex);
return;
}
throw;
}
}
/// <summary>
/// Refreshes the cache value of the given key, and resets its sliding expiration timeout.
/// </summary>
/// <param name="key">The key of cached item to be retrieved from the cache.</param>
/// <param name="hideErrors">Indicates to throw or hide the exceptions for the distributed cache.</param>
/// <param name="token">The <see cref="T:System.Threading.CancellationToken" /> for the task.</param>
/// <returns>The <see cref="T:System.Threading.Tasks.Task" /> indicating that the operation is asynchronous.</returns>
public virtual async Task RefreshAsync(
TCacheKey key,
bool? hideErrors = null,
CancellationToken token = default)
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
await Cache.RefreshAsync(NormalizeKey(key), CancellationTokenProvider.FallbackToProvider(token));
}
catch (Exception ex)
{
if (hideErrors == true)
{
await HandleExceptionAsync(ex);
return;
}
throw;
}
}
public virtual void RefreshMany(
IEnumerable<TCacheKey> keys,
bool? hideErrors = null)
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
if (Cache is ICacheSupportsMultipleItems cacheSupportsMultipleItems)
{
cacheSupportsMultipleItems.RefreshMany(keys.Select(NormalizeKey));
}
else
{
foreach (var key in keys)
{
Cache.Refresh(NormalizeKey(key));
}
}
}
catch (Exception ex)
{
if (hideErrors == true)
{
HandleException(ex);
return;
}
throw;
}
}
public virtual async Task RefreshManyAsync(
IEnumerable<TCacheKey> keys,
bool? hideErrors = null,
CancellationToken token = default)
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
if (Cache is ICacheSupportsMultipleItems cacheSupportsMultipleItems)
{
await cacheSupportsMultipleItems.RefreshManyAsync(keys.Select(NormalizeKey), token);
}
else
{
foreach (var key in keys)
{
await Cache.RefreshAsync(NormalizeKey(key), token);
}
}
}
catch (Exception ex)
{
if (hideErrors == true)
{
await HandleExceptionAsync(ex);
return;
}
throw;
}
}
/// <summary>
/// Removes the cache item for given key from cache.
/// </summary>
/// <param name="key">The key of cached item to be retrieved from the cache.</param>
/// <param name="considerUow">This will store the cache in the current unit of work until the end of the current unit of work does not really affect the cache.</param>
/// <param name="hideErrors">Indicates to throw or hide the exceptions for the distributed cache.</param>
public virtual void Remove(
TCacheKey key,
bool? hideErrors = null,
bool considerUow = false)
{
void RemoveRealCache()
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
Cache.Remove(NormalizeKey(key));
}
catch (Exception ex)
{
if (hideErrors == true)
{
HandleException(ex);
return;
}
throw;
}
}
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
if (uowCache.TryGetValue(key, out _))
{
uowCache[key].RemoveValue();
}
UnitOfWorkManager.Current?.OnCompleted(() =>
{
RemoveRealCache();
return Task.CompletedTask;
});
}
else
{
RemoveRealCache();
}
}
/// <summary>
/// Removes the cache item for given key from cache.
/// </summary>
/// <param name="key">The key of cached item to be retrieved from the cache.</param>
/// <param name="hideErrors">Indicates to throw or hide the exceptions for the distributed cache.</param>
/// <param name="considerUow">This will store the cache in the current unit of work until the end of the current unit of work does not really affect the cache.</param>
/// <param name="token">The <see cref="T:System.Threading.CancellationToken" /> for the task.</param>
/// <returns>The <see cref="T:System.Threading.Tasks.Task" /> indicating that the operation is asynchronous.</returns>
public virtual async Task RemoveAsync(
TCacheKey key,
bool? hideErrors = null,
bool considerUow = false,
CancellationToken token = default)
{
async Task RemoveRealCache()
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
await Cache.RemoveAsync(NormalizeKey(key), CancellationTokenProvider.FallbackToProvider(token));
}
catch (Exception ex)
{
if (hideErrors == true)
{
await HandleExceptionAsync(ex);
return;
}
throw;
}
}
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
if (uowCache.TryGetValue(key, out _))
{
uowCache[key].RemoveValue();
}
UnitOfWorkManager.Current?.OnCompleted(RemoveRealCache);
}
else
{
await RemoveRealCache();
}
}
public void RemoveMany(
IEnumerable<TCacheKey> keys,
bool? hideErrors = null,
bool considerUow = false)
{
var keyArray = keys.ToArray();
if (Cache is ICacheSupportsMultipleItems cacheSupportsMultipleItems)
{
void RemoveRealCache()
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
cacheSupportsMultipleItems.RemoveMany(
keyArray.Select(NormalizeKey)
);
}
catch (Exception ex)
{
if (hideErrors == true)
{
HandleException(ex);
return;
}
throw;
}
}
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
foreach (var key in keyArray)
{
if (uowCache.TryGetValue(key, out _))
{
uowCache[key].RemoveValue();
}
}
UnitOfWorkManager.Current?.OnCompleted(() =>
{
RemoveRealCache();
return Task.CompletedTask;
});
}
else
{
RemoveRealCache();
}
}
else
{
foreach (var key in keyArray)
{
Remove(key, hideErrors, considerUow);
}
}
}
public async Task RemoveManyAsync(
IEnumerable<TCacheKey> keys,
bool? hideErrors = null,
bool considerUow = false,
CancellationToken token = default)
{
var keyArray = keys.ToArray();
if (Cache is ICacheSupportsMultipleItems cacheSupportsMultipleItems)
{
async Task RemoveRealCache()
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
await cacheSupportsMultipleItems.RemoveManyAsync(
keyArray.Select(NormalizeKey), token);
}
catch (Exception ex)
{
if (hideErrors == true)
{
await HandleExceptionAsync(ex);
return;
}
throw;
}
}
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
foreach (var key in keyArray)
{
if (uowCache.TryGetValue(key, out _))
{
uowCache[key].RemoveValue();
}
}
UnitOfWorkManager.Current?.OnCompleted(RemoveRealCache);
}
else
{
await RemoveRealCache();
}
}
else
{
foreach (var key in keyArray)
{
await RemoveAsync(key, hideErrors, considerUow, token);
}
}
}
protected virtual void HandleException(Exception ex)
{
_ = HandleExceptionAsync(ex);
}
protected virtual async Task HandleExceptionAsync(Exception ex)
{
Logger.LogException(ex, LogLevel.Warning);
using (var scope = ServiceScopeFactory.CreateScope())
{
await scope.ServiceProvider
.GetRequiredService<IExceptionNotifier>()
.NotifyAsync(new ExceptionNotificationContext(ex, LogLevel.Warning));
}
}
protected virtual KeyValuePair<TCacheKey, TCacheItem?>[] ToCacheItems(byte[]?[] itemBytes, TCacheKey[] itemKeys)
{
if (itemBytes.Length != itemKeys.Length)
{
throw new AbpException("count of the item bytes should be same with the count of the given keys");
}
var result = new List<KeyValuePair<TCacheKey, TCacheItem?>>();
for (var i = 0; i < itemKeys.Length; i++)
{
result.Add(
new KeyValuePair<TCacheKey, TCacheItem?>(
itemKeys[i],
ToCacheItem(itemBytes[i])
)
);
}
return result.ToArray();
}
protected virtual TCacheItem? ToCacheItem(byte[]? bytes)
{
if (bytes == null)
{
return null;
}
return Serializer.Deserialize<TCacheItem>(bytes);
}
protected virtual KeyValuePair<string, byte[]>[] ToRawCacheItems(KeyValuePair<TCacheKey, TCacheItem>[] items)
{
return items
.Select(i => new KeyValuePair<string, byte[]>(
NormalizeKey(i.Key),
Serializer.Serialize(i.Value)
)
).ToArray();
}
private static KeyValuePair<TCacheKey, TCacheItem?>[] ToCacheItemsWithDefaultValues(TCacheKey[] keys)
{
return keys
.Select(key => new KeyValuePair<TCacheKey, TCacheItem?>(key, default))
.ToArray();
}
protected virtual bool ShouldConsiderUow(bool considerUow)
{
return considerUow && UnitOfWorkManager.Current != null;
}
protected virtual string GetUnitOfWorkCacheKey()
{
return UowCacheName + CacheName;
}
protected virtual Dictionary<TCacheKey, UnitOfWorkCacheItem<TCacheItem>> GetUnitOfWorkCache()
{
if (UnitOfWorkManager.Current == null)
{
throw new AbpException($"There is no active UOW.");
}
return UnitOfWorkManager.Current.GetOrAddItem(GetUnitOfWorkCacheKey(),
key => new Dictionary<TCacheKey, UnitOfWorkCacheItem<TCacheItem>>());
}
}
| where |
csharp | SixLabors__ImageSharp | tests/ImageSharp.Tests/TestDataIcc/IccTestDataArray.cs | {
"start": 129,
"end": 3495
} | internal static class ____
{
public static readonly byte[] UInt8 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
public static readonly object[][] UInt8TestData =
[
[UInt8, UInt8]
];
public static readonly ushort[] UInt16Val = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
public static readonly byte[] UInt16Arr = ArrayHelper.Concat(
IccTestDataPrimitives.UInt160,
IccTestDataPrimitives.UInt161,
IccTestDataPrimitives.UInt162,
IccTestDataPrimitives.UInt163,
IccTestDataPrimitives.UInt164,
IccTestDataPrimitives.UInt165,
IccTestDataPrimitives.UInt166,
IccTestDataPrimitives.UInt167,
IccTestDataPrimitives.UInt168,
IccTestDataPrimitives.UInt169);
public static readonly object[][] UInt16TestData =
[
[UInt16Arr, UInt16Val]
];
public static readonly short[] Int16Val = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
public static readonly byte[] Int16Arr = ArrayHelper.Concat(
IccTestDataPrimitives.Int160,
IccTestDataPrimitives.Int161,
IccTestDataPrimitives.Int162,
IccTestDataPrimitives.Int163,
IccTestDataPrimitives.Int164,
IccTestDataPrimitives.Int165,
IccTestDataPrimitives.Int166,
IccTestDataPrimitives.Int167,
IccTestDataPrimitives.Int168,
IccTestDataPrimitives.Int169);
public static readonly object[][] Int16TestData =
[
[Int16Arr, Int16Val]
];
public static readonly uint[] UInt32Val = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
public static readonly byte[] UInt32Arr = ArrayHelper.Concat(
IccTestDataPrimitives.UInt320,
IccTestDataPrimitives.UInt321,
IccTestDataPrimitives.UInt322,
IccTestDataPrimitives.UInt323,
IccTestDataPrimitives.UInt324,
IccTestDataPrimitives.UInt325,
IccTestDataPrimitives.UInt326,
IccTestDataPrimitives.UInt327,
IccTestDataPrimitives.UInt328,
IccTestDataPrimitives.UInt329);
public static readonly object[][] UInt32TestData =
[
[UInt32Arr, UInt32Val]
];
public static readonly int[] Int32Val = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
public static readonly byte[] Int32Arr = ArrayHelper.Concat(
IccTestDataPrimitives.Int320,
IccTestDataPrimitives.Int321,
IccTestDataPrimitives.Int322,
IccTestDataPrimitives.Int323,
IccTestDataPrimitives.Int324,
IccTestDataPrimitives.Int325,
IccTestDataPrimitives.Int326,
IccTestDataPrimitives.Int327,
IccTestDataPrimitives.Int328,
IccTestDataPrimitives.Int329);
public static readonly object[][] Int32TestData =
[
[Int32Arr, Int32Val]
];
public static readonly ulong[] UInt64Val = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
public static readonly byte[] UInt64Arr = ArrayHelper.Concat(
IccTestDataPrimitives.UInt640,
IccTestDataPrimitives.UInt641,
IccTestDataPrimitives.UInt642,
IccTestDataPrimitives.UInt643,
IccTestDataPrimitives.UInt644,
IccTestDataPrimitives.UInt645,
IccTestDataPrimitives.UInt646,
IccTestDataPrimitives.UInt647,
IccTestDataPrimitives.UInt648,
IccTestDataPrimitives.UInt649);
public static readonly object[][] UInt64TestData =
[
[UInt64Arr, UInt64Val]
];
}
| IccTestDataArray |
csharp | ardalis__Specification | tests/Ardalis.Specification.EntityFrameworkCore.Tests/Evaluators/OrderEvaluatorTests.cs | {
"start": 63,
"end": 1114
} | public class ____(TestFactory factory) : IntegrationTest(factory)
{
private static readonly OrderEvaluator _evaluator = OrderEvaluator.Instance;
[Fact]
public void QueriesMatch_GivenOrder()
{
var spec = new Specification<Store>();
spec.Query
.OrderBy(x => x.Id);
var actual = _evaluator.GetQuery(DbContext.Stores, spec)
.ToQueryString();
var expected = DbContext.Stores
.OrderBy(x => x.Id)
.ToQueryString();
actual.Should().Be(expected);
}
[Fact]
public void QueriesMatch_GivenOrderChain()
{
var spec = new Specification<Store>();
spec.Query
.OrderBy(x => x.Id)
.ThenBy(x => x.Name);
var actual = _evaluator.GetQuery(DbContext.Stores, spec)
.ToQueryString();
var expected = DbContext.Stores
.OrderBy(x => x.Id)
.ThenBy(x => x.Name)
.ToQueryString();
actual.Should().Be(expected);
}
}
| OrderEvaluatorTests |
csharp | dotnet__aspnetcore | src/Mvc/test/WebSites/ControllersFromServicesWebSite/Startup.cs | {
"start": 1585,
"end": 2677
} | private class ____ : ApplicationPart, IApplicationPartTypeProvider
{
public TypesPart(params Type[] types)
{
Types = types.Select(t => t.GetTypeInfo());
}
public override string Name => string.Join(", ", Types.Select(t => t.FullName));
public IEnumerable<TypeInfo> Types { get; }
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
public static void Main(string[] args)
{
using var host = CreateHostBuilder(args)
.Build();
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.UseKestrel()
.UseIISIntegration();
});
}
| TypesPart |
csharp | SixLabors__ImageSharp | src/ImageSharp/PixelFormats/PixelBlenders/DefaultPixelBlenders.Generated.cs | {
"start": 202649,
"end": 208113
} | public class ____ : PixelBlender<TPixel>
{
/// <summary>
/// Gets the static instance of this blender.
/// </summary>
public static MultiplySrcOut Instance { get; } = new MultiplySrcOut();
/// <inheritdoc />
public override TPixel Blend(TPixel background, TPixel source, float amount)
{
return TPixel.FromScaledVector4(PorterDuffFunctions.MultiplySrcOut(background.ToScaledVector4(), source.ToScaledVector4(), Numerics.Clamp(amount, 0, 1)));
}
/// <inheritdoc />
protected override void BlendFunction(Span<Vector4> destination, ReadOnlySpan<Vector4> background, ReadOnlySpan<Vector4> source, float amount)
{
amount = Numerics.Clamp(amount, 0, 1);
if (Avx2.IsSupported && destination.Length >= 2)
{
// Divide by 2 as 4 elements per Vector4 and 8 per Vector256<float>
ref Vector256<float> destinationBase = ref Unsafe.As<Vector4, Vector256<float>>(ref MemoryMarshal.GetReference(destination));
ref Vector256<float> destinationLast = ref Unsafe.Add(ref destinationBase, (uint)destination.Length / 2u);
ref Vector256<float> backgroundBase = ref Unsafe.As<Vector4, Vector256<float>>(ref MemoryMarshal.GetReference(background));
ref Vector256<float> sourceBase = ref Unsafe.As<Vector4, Vector256<float>>(ref MemoryMarshal.GetReference(source));
Vector256<float> opacity = Vector256.Create(amount);
while (Unsafe.IsAddressLessThan(ref destinationBase, ref destinationLast))
{
destinationBase = PorterDuffFunctions.MultiplySrcOut(backgroundBase, sourceBase, opacity);
destinationBase = ref Unsafe.Add(ref destinationBase, 1);
backgroundBase = ref Unsafe.Add(ref backgroundBase, 1);
sourceBase = ref Unsafe.Add(ref sourceBase, 1);
}
if (Numerics.Modulo2(destination.Length) != 0)
{
// Vector4 fits neatly in pairs. Any overlap has to be equal to 1.
int i = destination.Length - 1;
destination[i] = PorterDuffFunctions.MultiplySrcOut(background[i], source[i], amount);
}
}
else
{
for (int i = 0; i < destination.Length; i++)
{
destination[i] = PorterDuffFunctions.MultiplySrcOut(background[i], source[i], amount);
}
}
}
/// <inheritdoc />
protected override void BlendFunction(Span<Vector4> destination, ReadOnlySpan<Vector4> background, ReadOnlySpan<Vector4> source, ReadOnlySpan<float> amount)
{
if (Avx2.IsSupported && destination.Length >= 2)
{
// Divide by 2 as 4 elements per Vector4 and 8 per Vector256<float>
ref Vector256<float> destinationBase = ref Unsafe.As<Vector4, Vector256<float>>(ref MemoryMarshal.GetReference(destination));
ref Vector256<float> destinationLast = ref Unsafe.Add(ref destinationBase, (uint)destination.Length / 2u);
ref Vector256<float> backgroundBase = ref Unsafe.As<Vector4, Vector256<float>>(ref MemoryMarshal.GetReference(background));
ref Vector256<float> sourceBase = ref Unsafe.As<Vector4, Vector256<float>>(ref MemoryMarshal.GetReference(source));
ref float amountBase = ref MemoryMarshal.GetReference(amount);
Vector256<float> vOne = Vector256.Create(1F);
while (Unsafe.IsAddressLessThan(ref destinationBase, ref destinationLast))
{
// We need to create a Vector256<float> containing the current and next amount values
// taking up each half of the Vector256<float> and then clamp them.
Vector256<float> opacity = Vector256.Create(
Vector128.Create(amountBase),
Vector128.Create(Unsafe.Add(ref amountBase, 1)));
opacity = Avx.Min(Avx.Max(Vector256<float>.Zero, opacity), vOne);
destinationBase = PorterDuffFunctions.MultiplySrcOut(backgroundBase, sourceBase, opacity);
destinationBase = ref Unsafe.Add(ref destinationBase, 1);
backgroundBase = ref Unsafe.Add(ref backgroundBase, 1);
sourceBase = ref Unsafe.Add(ref sourceBase, 1);
amountBase = ref Unsafe.Add(ref amountBase, 2);
}
if (Numerics.Modulo2(destination.Length) != 0)
{
// Vector4 fits neatly in pairs. Any overlap has to be equal to 1.
int i = destination.Length - 1;
destination[i] = PorterDuffFunctions.MultiplySrcOut(background[i], source[i], Numerics.Clamp(amount[i], 0, 1F));
}
}
else
{
for (int i = 0; i < destination.Length; i++)
{
destination[i] = PorterDuffFunctions.MultiplySrcOut(background[i], source[i], Numerics.Clamp(amount[i], 0, 1F));
}
}
}
}
/// <summary>
/// A pixel blender that implements the "AddSrcOut" composition equation.
/// </summary>
| MultiplySrcOut |
csharp | microsoft__semantic-kernel | dotnet/samples/Concepts/ChatCompletion/Google_GeminiChatCompletionWithThinkingBudget.cs | {
"start": 541,
"end": 2342
} | public sealed class ____(ITestOutputHelper output) : BaseTest(output)
{
[Fact]
public async Task GoogleAIChatCompletionUsingThinkingBudget()
{
Console.WriteLine("============= Google AI - Gemini 2.5 Chat Completion using Thinking Budget =============");
Assert.NotNull(TestConfiguration.GoogleAI.ApiKey);
string geminiModelId = "gemini-2.5-pro-exp-03-25";
Kernel kernel = Kernel.CreateBuilder()
.AddGoogleAIGeminiChatCompletion(
modelId: geminiModelId,
apiKey: TestConfiguration.GoogleAI.ApiKey)
.Build();
var chatHistory = new ChatHistory("You are an expert in the tool shop.");
var chat = kernel.GetRequiredService<IChatCompletionService>();
var executionSettings = new GeminiPromptExecutionSettings
{
// This parameter gives the model how much tokens it can use during the thinking process.
ThinkingConfig = new() { ThinkingBudget = 2000 }
};
// First user message
chatHistory.AddUserMessage("Hi, I'm looking for new power tools, any suggestion?");
await MessageOutputAsync(chatHistory);
// First assistant message
var reply = await chat.GetChatMessageContentAsync(chatHistory, executionSettings);
chatHistory.Add(reply);
await MessageOutputAsync(chatHistory);
}
/// <summary>
/// Outputs the last message of the chat history
/// </summary>
private Task MessageOutputAsync(ChatHistory chatHistory)
{
var message = chatHistory.Last();
Console.WriteLine($"{message.Role}: {message.Content}");
Console.WriteLine("------------------------");
return Task.CompletedTask;
}
}
| Google_GeminiChatCompletionWithThinkingBudget |
csharp | abpframework__abp | modules/docs/src/Volo.Docs.Application/Volo/Docs/Documents/INavigationTreePostProcessor.cs | {
"start": 68,
"end": 198
} | public interface ____
{
Task ProcessAsync(NavigationTreePostProcessorContext context);
}
} | INavigationTreePostProcessor |
csharp | dotnet__aspnetcore | src/StaticAssets/test/StaticAssetsIntegrationTests.cs | {
"start": 40259,
"end": 41049
} | private class ____(TestResource testResource) : IFileInfo
{
public bool Exists => true;
public long Length => testResource.Content.Length;
public string PhysicalPath => null;
public string Name => Path.GetFileName(testResource.Path);
public DateTimeOffset LastModified => new(2023, 03, 03, 0, 0, 0, TimeSpan.Zero);
public bool IsDirectory => false;
public Stream CreateReadStream()
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(testResource.Content);
writer.Flush();
stream.Position = 0;
return stream;
}
}
}
}
| TestFileInfo |
csharp | smartstore__Smartstore | src/Smartstore.Web/Models/Catalog/ProductDetailsModel.cs | {
"start": 423,
"end": 2605
} | public partial class ____
{
public ProductDetailsModelContext()
{
}
/// <summary>
/// Applies the property references of another <see cref="ProductDetailsModelContext"/> instance.
/// Only to be used for child items like associated products or bundle items,
/// otherwise use <see cref="CatalogHelper.CreateModelContext"/>.
/// </summary>
public ProductDetailsModelContext(ProductDetailsModelContext other)
{
Product = other.Product;
BatchContext = other.BatchContext;
VariantQuery = other.VariantQuery;
Customer = other.Customer;
Store = other.Store;
Currency = other.Currency;
DisplayPrices = other.DisplayPrices;
HasInitiallySelectedVariants = false;
AssociatedProducts = other.AssociatedProducts;
GroupedProductConfiguration = other.GroupedProductConfiguration;
}
public Product Product { get; set; }
public ProductBatchContext BatchContext { get; set; }
public ProductVariantQuery VariantQuery { get; set; }
public Customer Customer { get; set; }
public Store Store { get; set; }
public Currency Currency { get; set; }
public bool DisplayPrices { get; set; }
public bool IsAssociatedProduct { get; set; }
public IList<Product> AssociatedProducts { get; set; }
public GroupedProductConfiguration GroupedProductConfiguration { get; set; }
public Product ParentProduct { get; set; }
public ProductBundleItem ProductBundleItem { get; set; }
/// <summary>
/// The selected attributes based on <see cref="VariantQuery"/>. <c>null</c> if none have been selected (then the preselected attributes are used).
/// </summary>
public ProductVariantAttributeSelection SelectedAttributes { get; set; }
/// <summary>
/// Gets a value indicating whether processing was started with initially selected variants.
/// </summary>
public bool HasInitiallySelectedVariants { get; init; }
}
| ProductDetailsModelContext |
csharp | AutoMapper__AutoMapper | src/UnitTests/Internal/ObjectFactoryTests.cs | {
"start": 50,
"end": 678
} | public class ____
{
[Fact]
public void Test_with_create_ctor() => ObjectFactory.CreateInstance(typeof(ObjectFactoryTests)).ShouldBeOfType<ObjectFactoryTests>();
[Fact]
public void Test_with_value_object_create_ctor() => ObjectFactory.CreateInstance(typeof(DateTimeOffset)).ShouldBeOfType<DateTimeOffset>();
[Fact]
public void Create_ctor_should_throw_when_default_constructor_is_missing() =>
new Action(() => ObjectFactory.CreateInstance(typeof(AssemblyLoadEventArgs)))
.ShouldThrow<ArgumentException>().Message.ShouldStartWith(typeof(AssemblyLoadEventArgs).FullName);
} | ObjectFactoryTests |
csharp | microsoft__semantic-kernel | dotnet/src/Connectors/Connectors.Google/Extensions/GoogleAIServiceCollectionExtensions.cs | {
"start": 468,
"end": 3766
} | public static class ____
{
/// <summary>
/// Add Google AI Gemini Chat Completion and Text Generation services to the specified service collection.
/// </summary>
/// <param name="services">The service collection to add the Gemini Text Generation service to.</param>
/// <param name="modelId">The model for text generation.</param>
/// <param name="apiKey">The API key for authentication Gemini API.</param>
/// <param name="apiVersion">The version of the Google API.</param>
/// <param name="serviceId">Optional service ID.</param>
/// <returns>The updated service collection.</returns>
public static IServiceCollection AddGoogleAIGeminiChatCompletion(
this IServiceCollection services,
string modelId,
string apiKey,
GoogleAIVersion apiVersion = GoogleAIVersion.V1_Beta, // todo: change beta to stable when stable version will be available
string? serviceId = null)
{
Verify.NotNull(services);
Verify.NotNull(modelId);
Verify.NotNull(apiKey);
services.AddKeyedSingleton<IChatCompletionService>(serviceId, (serviceProvider, _) =>
new GoogleAIGeminiChatCompletionService(
modelId: modelId,
apiKey: apiKey,
apiVersion: apiVersion,
httpClient: HttpClientProvider.GetHttpClient(serviceProvider),
loggerFactory: serviceProvider.GetService<ILoggerFactory>()));
return services;
}
/// <summary>
/// Add Google AI <see cref="ITextEmbeddingGenerationService"/> to the specified service collection.
/// </summary>
/// <param name="services">The service collection to add the Gemini Embeddings Generation service to.</param>
/// <param name="modelId">The model for embeddings generation.</param>
/// <param name="apiKey">The API key for authentication Gemini API.</param>
/// <param name="apiVersion">The version of the Google API.</param>
/// <param name="serviceId">Optional service ID.</param>
/// <param name="dimensions">The optional number of dimensions that the model should use. If not specified, the default number of dimensions will be used.</param>
/// <returns>The updated service collection.</returns>
[Obsolete("Use AddGoogleAIEmbeddingGenerator instead.")]
public static IServiceCollection AddGoogleAIEmbeddingGeneration(
this IServiceCollection services,
string modelId,
string apiKey,
GoogleAIVersion apiVersion = GoogleAIVersion.V1_Beta, // todo: change beta to stable when stable version will be available
string? serviceId = null,
int? dimensions = null)
{
Verify.NotNull(services);
Verify.NotNull(modelId);
Verify.NotNull(apiKey);
return services.AddKeyedSingleton<ITextEmbeddingGenerationService>(serviceId, (serviceProvider, _) =>
new GoogleAITextEmbeddingGenerationService(
modelId: modelId,
apiKey: apiKey,
apiVersion: apiVersion,
httpClient: HttpClientProvider.GetHttpClient(serviceProvider),
loggerFactory: serviceProvider.GetService<ILoggerFactory>(),
dimensions: dimensions));
}
}
| GoogleAIServiceCollectionExtensions |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.OpenId.Core/YesSql/Models/OpenIdToken.cs | {
"start": 137,
"end": 2568
} | public class ____
{
/// <summary>
/// The name of the collection that is used for this type.
/// </summary>
public const string OpenIdCollection = "OpenId";
/// <summary>
/// Gets or sets the unique identifier associated with the current token.
/// </summary>
public string TokenId { get; set; }
/// <summary>
/// Gets or sets the identifier of the application associated with the current token.
/// </summary>
public string ApplicationId { get; set; }
/// <summary>
/// Gets or sets the identifier of the authorization associated with the current token.
/// </summary>
public string AuthorizationId { get; set; }
/// <summary>
/// Gets or sets the creation date of the current token.
/// </summary>
public DateTime? CreationDate { get; set; }
/// <summary>
/// Gets or sets the expiration date of the current token.
/// </summary>
public DateTime? ExpirationDate { get; set; }
/// <summary>
/// Gets or sets the physical identifier associated with the current token.
/// </summary>
public long Id { get; set; }
/// <summary>
/// Gets or sets the payload of the current token, if applicable.
/// Note: this property is only used for reference tokens
/// and may be encrypted for security reasons.
/// </summary>
public string Payload { get; set; }
/// <summary>
/// Gets or sets the additional properties associated with the current token.
/// </summary>
public JsonObject Properties { get; set; }
/// <summary>
/// Gets or sets the redemption date of the current token.
/// </summary>
public DateTime? RedemptionDate { get; set; }
/// <summary>
/// Gets or sets the reference identifier associated
/// with the current token, if applicable.
/// Note: this property is only used for reference tokens
/// and may be hashed or encrypted for security reasons.
/// </summary>
public string ReferenceId { get; set; }
/// <summary>
/// Gets or sets the status of the current token.
/// </summary>
public string Status { get; set; }
/// <summary>
/// Gets or sets the subject associated with the current token.
/// </summary>
public string Subject { get; set; }
/// <summary>
/// Gets or sets the type of the current token.
/// </summary>
public string Type { get; set; }
}
| OpenIdToken |
csharp | files-community__Files | src/Files.App/Utils/Storage/StorageItems/SystemStorageFile.cs | {
"start": 365,
"end": 7979
} | partial class ____ : BaseStorageFile
{
public StorageFile File { get; }
public override string Path => File?.Path;
public override string Name => File?.Name;
public override string DisplayName => File?.DisplayName;
public override string ContentType => File.ContentType;
public override string DisplayType => File?.DisplayType;
public override string FileType => File.FileType;
public override string FolderRelativeId => File?.FolderRelativeId;
public override DateTimeOffset DateCreated => File.DateCreated;
public override Windows.Storage.FileAttributes Attributes => File.Attributes;
public override IStorageItemExtraProperties Properties => File?.Properties;
public SystemStorageFile(StorageFile file) => File = file;
public static IAsyncOperation<BaseStorageFile> FromPathAsync(string path)
=> AsyncInfo.Run<BaseStorageFile>(async (cancellationToken)
=> new SystemStorageFile(await StorageFile.GetFileFromPathAsync(path))
);
public override IAsyncOperation<StorageFile> ToStorageFileAsync()
=> Task.FromResult(File).AsAsyncOperation();
public override bool IsEqual(IStorageItem item) => File.IsEqual(item);
public override bool IsOfType(StorageItemTypes type) => File.IsOfType(type);
public override IAsyncOperation<BaseStorageFolder> GetParentAsync()
=> AsyncInfo.Run<BaseStorageFolder>(async (cancellationToken)
=> new SystemStorageFolder(await File.GetParentAsync())
);
public override IAsyncOperation<BaseBasicProperties> GetBasicPropertiesAsync()
=> AsyncInfo.Run<BaseBasicProperties>(async (cancellationToken)
=> new SystemFileBasicProperties(await File.GetBasicPropertiesAsync(), DateCreated)
);
public override IAsyncOperation<BaseStorageFile> CopyAsync(IStorageFolder destinationFolder)
=> CopyAsync(destinationFolder, Name, NameCollisionOption.FailIfExists);
public override IAsyncOperation<BaseStorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName)
=> CopyAsync(destinationFolder, desiredNewName, NameCollisionOption.FailIfExists);
public override IAsyncOperation<BaseStorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option)
{
return AsyncInfo.Run(async (cancellationToken) =>
{
var destFolder = destinationFolder.AsBaseStorageFolder(); // Avoid calling IStorageFolder method
try
{
if (destFolder is SystemStorageFolder sysFolder)
{
// File created by CreateFileAsync will get immediately deleted on MTP?! (#7206)
return await File.CopyAsync(sysFolder.Folder, desiredNewName, option);
}
else if (destFolder is ICreateFileWithStream cwsf)
{
await using var inStream = await this.OpenStreamForReadAsync();
return await cwsf.CreateFileAsync(inStream, desiredNewName, option.Convert());
}
else
{
var destFile = await destFolder.CreateFileAsync(desiredNewName, option.Convert());
await using (var inStream = await this.OpenStreamForReadAsync())
await using (var outStream = await destFile.OpenStreamForWriteAsync())
{
await inStream.CopyToAsync(outStream, cancellationToken);
await outStream.FlushAsync(cancellationToken);
}
return destFile;
}
}
catch (UnauthorizedAccessException) // shortcuts & .url
{
if (!string.IsNullOrEmpty(destFolder.Path))
{
var destination = IO.Path.Combine(destFolder.Path, desiredNewName);
var hFile = Win32Helper.CreateFileForWrite(destination,
option == NameCollisionOption.ReplaceExisting);
if (!hFile.IsInvalid)
{
await using (var inStream = await this.OpenStreamForReadAsync())
await using (var outStream = new FileStream(hFile, FileAccess.Write))
{
await inStream.CopyToAsync(outStream, cancellationToken);
await outStream.FlushAsync(cancellationToken);
}
return new NativeStorageFile(destination, desiredNewName, DateTime.Now);
}
}
throw;
}
});
}
public override IAsyncOperation<IRandomAccessStream> OpenAsync(FileAccessMode accessMode) => File.OpenAsync(accessMode);
public override IAsyncOperation<IRandomAccessStream> OpenAsync(FileAccessMode accessMode, StorageOpenOptions options) => File.OpenAsync(accessMode, options);
public override IAsyncOperation<IRandomAccessStreamWithContentType> OpenReadAsync() => File.OpenReadAsync();
public override IAsyncOperation<IInputStream> OpenSequentialReadAsync() => File.OpenSequentialReadAsync();
public override IAsyncOperation<StorageStreamTransaction> OpenTransactedWriteAsync() => File.OpenTransactedWriteAsync();
public override IAsyncOperation<StorageStreamTransaction> OpenTransactedWriteAsync(StorageOpenOptions options) => File.OpenTransactedWriteAsync(options);
public override IAsyncAction MoveAsync(IStorageFolder destinationFolder)
=> MoveAsync(destinationFolder, Name, NameCollisionOption.FailIfExists);
public override IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName)
=> MoveAsync(destinationFolder, desiredNewName, NameCollisionOption.FailIfExists);
public override IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option)
{
return AsyncInfo.Run(async (cancellationToken) =>
{
var destFolder = destinationFolder.AsBaseStorageFolder(); // Avoid calling IStorageFolder method
if (destFolder is SystemStorageFolder sysFolder)
{
// File created by CreateFileAsync will get immediately deleted on MTP?! (#7206)
await File.MoveAsync(sysFolder.Folder, desiredNewName, option);
return;
}
await CopyAsync(destinationFolder, desiredNewName, option);
// Move unsupported, copy but do not delete original
});
}
public override IAsyncAction CopyAndReplaceAsync(IStorageFile fileToReplace)
{
return AsyncInfo.Run(async (cancellationToken) =>
{
await using var inStream = await this.OpenStreamForReadAsync();
await using var outStream = await fileToReplace.OpenStreamForWriteAsync();
await inStream.CopyToAsync(outStream, cancellationToken);
await outStream.FlushAsync(cancellationToken);
});
}
public override IAsyncAction MoveAndReplaceAsync(IStorageFile fileToReplace)
{
return AsyncInfo.Run(async (cancellationToken) =>
{
await using var inStream = await this.OpenStreamForReadAsync();
await using var outStream = await fileToReplace.OpenStreamForWriteAsync();
await inStream.CopyToAsync(outStream, cancellationToken);
await outStream.FlushAsync(cancellationToken);
// Move unsupported, copy but do not delete original
});
}
public override IAsyncAction RenameAsync(string desiredName) => File.RenameAsync(desiredName);
public override IAsyncAction RenameAsync(string desiredName, NameCollisionOption option) => File.RenameAsync(desiredName, option);
public override IAsyncAction DeleteAsync() => File.DeleteAsync();
public override IAsyncAction DeleteAsync(StorageDeleteOption option) => File.DeleteAsync(option);
public override IAsyncOperation<StorageItemThumbnail> GetThumbnailAsync(ThumbnailMode mode)
=> File.GetThumbnailAsync(mode);
public override IAsyncOperation<StorageItemThumbnail> GetThumbnailAsync(ThumbnailMode mode, uint requestedSize)
=> File.GetThumbnailAsync(mode, requestedSize);
public override IAsyncOperation<StorageItemThumbnail> GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions options)
=> File.GetThumbnailAsync(mode, requestedSize, options);
private sealed | SystemStorageFile |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 4326634,
"end": 4327608
} | public partial class ____ : global::StrawberryShake.IOperationResultDataInfo
{
public DeleteApiKeyCommandMutationResultInfo(global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.DeleteApiKeyPayloadData deleteApiKey)
{
DeleteApiKey = deleteApiKey;
}
public global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.DeleteApiKeyPayloadData DeleteApiKey { get; }
public global::System.Collections.Generic.IReadOnlyCollection<global::StrawberryShake.EntityId> EntityIds => global::System.Array.Empty<global::StrawberryShake.EntityId>();
public global::System.UInt64 Version => 0;
public global::StrawberryShake.IOperationResultDataInfo WithVersion(global::System.UInt64 version)
{
return new DeleteApiKeyCommandMutationResultInfo(DeleteApiKey);
}
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| DeleteApiKeyCommandMutationResultInfo |
csharp | cake-build__cake | src/Cake.Common/Tools/DotNet/Reference/Add/DotNetReferenceAdder.cs | {
"start": 457,
"end": 3217
} | public sealed class ____ : DotNetTool<DotNetReferenceAddSettings>
{
private readonly ICakeEnvironment _environment;
/// <summary>
/// Initializes a new instance of the <see cref="DotNetReferenceAdder" /> class.
/// </summary>
/// <param name="fileSystem">The file system.</param>
/// <param name="environment">The environment.</param>
/// <param name="processRunner">The process runner.</param>
/// <param name="tools">The tool locator.</param>
public DotNetReferenceAdder(
IFileSystem fileSystem,
ICakeEnvironment environment,
IProcessRunner processRunner,
IToolLocator tools) : base(fileSystem, environment, processRunner, tools)
{
_environment = environment;
}
/// <summary>
/// Adds project-to-project (P2P) references.
/// </summary>
/// <param name="project">The target project file path. If not specified, the command searches the current directory for one.</param>
/// <param name="projectReferences">One or more project references to add. Glob patterns are supported on Unix/Linux-based systems.</param>
/// <param name="settings">The settings.</param>
public void Add(string project, IEnumerable<FilePath> projectReferences, DotNetReferenceAddSettings settings)
{
if (projectReferences == null || !projectReferences.Any())
{
throw new ArgumentNullException(nameof(projectReferences));
}
ArgumentNullException.ThrowIfNull(settings);
RunCommand(settings, GetArguments(project, projectReferences, settings));
}
private ProcessArgumentBuilder GetArguments(string project, IEnumerable<FilePath> projectReferences, DotNetReferenceAddSettings settings)
{
var builder = CreateArgumentBuilder(settings);
builder.Append("add");
// Project path
if (!string.IsNullOrWhiteSpace(project))
{
builder.AppendQuoted(project);
}
// References
builder.Append("reference");
foreach (var reference in projectReferences)
{
builder.AppendQuoted(reference.MakeAbsolute(_environment).FullPath);
}
// Framework
if (!string.IsNullOrEmpty(settings.Framework))
{
builder.AppendSwitch("--framework", settings.Framework);
}
// Interactive
if (settings.Interactive)
{
builder.Append("--interactive");
}
return builder;
}
}
}
| DotNetReferenceAdder |
csharp | unoplatform__uno | src/SourceGenerators/XamlGenerationTests/PropertiesTest.xaml.cs | {
"start": 109,
"end": 377
} | public partial class ____
{
public PropertiesTest()
{
#elif __APPLE_UIKIT__
iOSUILabel.ToString();
#endif
#if __ANDROID__
AndroidTextView.ToString();
#endif
GradientStopEffect.ToString();
testRun.ToString();
rtbRun.ToString();
}
}
}
| PropertiesTest |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Controls/PullToRefresh/Native/RefreshContainer.native.cs | {
"start": 102,
"end": 349
} | public partial class ____ : ContentControl
{
private void OnNativeRefreshingChanged()
{
if (Visualizer is { } visualizer && visualizer.State != RefreshVisualizerState.Refreshing)
{
visualizer.RequestRefresh();
}
}
}
#endif
| RefreshContainer |
csharp | MassTransit__MassTransit | src/MassTransit/Scheduling/DefaultRecurringSchedule.cs | {
"start": 52,
"end": 895
} | public abstract class ____ :
RecurringSchedule
{
protected DefaultRecurringSchedule()
{
ScheduleId = TypeCache.GetShortName(GetType());
ScheduleGroup = GetType().Assembly.FullName.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[0];
TimeZoneId = TimeZoneInfo.Local.Id;
StartTime = DateTime.Now;
}
public MissedEventPolicy MisfirePolicy { get; protected set; }
public string TimeZoneId { get; protected set; }
public DateTimeOffset StartTime { get; protected set; }
public DateTimeOffset? EndTime { get; protected set; }
public string ScheduleId { get; protected set; }
public string ScheduleGroup { get; protected set; }
public string CronExpression { get; protected set; }
public string Description { get; protected set; }
}
| DefaultRecurringSchedule |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.