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 | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/ServiceGatewayTestsAsync.cs | {
"start": 5876,
"end": 5990
} | public class ____ : IReturn<SGAsyncPostExternal>, IPost
{
public string Value { get; set; }
}
| SGAsyncPostExternal |
csharp | dotnet__aspnetcore | src/JSInterop/Microsoft.JSInterop/test/Infrastructure/ByteArrayJsonConverterTest.cs | {
"start": 210,
"end": 6902
} | public class ____
{
private readonly JSRuntime JSRuntime;
private JsonSerializerOptions JsonSerializerOptions => JSRuntime.JsonSerializerOptions;
public ByteArrayJsonConverterTest()
{
JSRuntime = new TestJSRuntime();
}
[Fact]
public void Read_Throws_IfByteArraysToBeRevivedIsEmpty()
{
// Arrange
var json = "{}";
// Act & Assert
var ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
Assert.Equal("JSON serialization is attempting to deserialize an unexpected byte array.", ex.Message);
}
[Fact]
public void Read_Throws_IfJsonIsMissingByteArraysProperty()
{
// Arrange
JSRuntime.ByteArraysToBeRevived.Append(new byte[] { 1, 2 });
var json = "{}";
// Act & Assert
var ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
Assert.Equal("Unexpected JSON Token EndObject, expected 'PropertyName'.", ex.Message);
}
[Fact]
public void Read_Throws_IfJsonContainsUnknownContent()
{
// Arrange
JSRuntime.ByteArraysToBeRevived.Append(new byte[] { 1, 2 });
var json = "{\"foo\":2}";
// Act & Assert
var ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
Assert.Equal("Unexpected JSON Property foo.", ex.Message);
}
[Fact]
public void Read_Throws_IfJsonIsIncomplete()
{
// Arrange
JSRuntime.ByteArraysToBeRevived.Append(new byte[] { 1, 2 });
var json = $"{{\"__byte[]\":0";
// Act & Assert
var ex = Record.Exception(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
Assert.IsAssignableFrom<JsonException>(ex);
}
[Fact]
public void Read_ReadsBase64EncodedStrings()
{
// Arrange
var expected = new byte[] { 1, 5, 8 };
var json = JsonSerializer.Serialize(expected);
// Act
var deserialized = JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions)!;
// Assert
Assert.Equal(expected, deserialized);
}
[Fact]
public void Read_ThrowsIfTheInputIsNotAValidBase64String()
{
// Arrange
var json = "\"Hello world\"";
// Act
var ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
// Assert
Assert.Equal("JSON serialization is attempting to deserialize an unexpected byte array.", ex.Message);
}
[Fact]
public void Read_ReadsJson()
{
// Arrange
var byteArray = new byte[] { 1, 5, 7 };
JSRuntime.ByteArraysToBeRevived.Append(byteArray);
var json = $"{{\"__byte[]\":0}}";
// Act
var deserialized = JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions)!;
// Assert
Assert.Equal(byteArray, deserialized);
}
[Fact]
public void Read_ByteArraysIdAppearsMultipleTimesThrows()
{
// Arrange
var byteArray = new byte[] { 1, 5, 7 };
JSRuntime.ByteArraysToBeRevived.Append(byteArray);
var json = $"{{\"__byte[]\":9120,\"__byte[]\":0}}";
// Act
var ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
// Assert
Assert.Equal("Unexpected JSON Token PropertyName, expected 'EndObject'.", ex.Message);
}
[Fact]
public void Read_ByteArraysIdValueInvalidStringThrows()
{
// Arrange
var byteArray = new byte[] { 1, 5, 7 };
JSRuntime.ByteArraysToBeRevived.Append(byteArray);
var json = $"{{\"__byte[]\":\"something\"}}";
// Act
var ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
// Assert
Assert.Equal("Unexpected JSON Token String, expected 'Number'.", ex.Message);
}
[Fact]
public void Read_ByteArraysIdValueLargeNumberThrows()
{
// Arrange
var byteArray = new byte[] { 1, 5, 7 };
JSRuntime.ByteArraysToBeRevived.Append(byteArray);
var json = $"{{\"__byte[]\":5000000000}}";
// Act
var ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
// Assert
Assert.Equal("Unexpected number, expected 32-bit integer.", ex.Message);
}
[Fact]
public void Read_ByteArraysIdValueNegativeNumberThrows()
{
// Arrange
var byteArray = new byte[] { 1, 5, 7 };
JSRuntime.ByteArraysToBeRevived.Append(byteArray);
var json = $"{{\"__byte[]\":-5}}";
// Act
var ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
// Assert
Assert.Equal("Byte array -5 not found.", ex.Message);
}
[Fact]
public void Read_ReadsJson_WithFormatting()
{
// Arrange
var byteArray = new byte[] { 1, 5, 7 };
JSRuntime.ByteArraysToBeRevived.Append(byteArray);
var json =
@$"{{
""__byte[]"": 0
}}";
// Act
var deserialized = JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions)!;
// Assert
Assert.Equal(byteArray, deserialized);
}
[Fact]
public void Read_ReturnsTheCorrectInstance()
{
// Arrange
// Track a few arrays and verify that the deserialized value returns the correct value.
var byteArray1 = new byte[] { 1, 5, 7 };
var byteArray2 = new byte[] { 2, 6, 8 };
var byteArray3 = new byte[] { 2, 6, 8 };
JSRuntime.ByteArraysToBeRevived.Append(byteArray1);
JSRuntime.ByteArraysToBeRevived.Append(byteArray2);
JSRuntime.ByteArraysToBeRevived.Append(byteArray3);
var json = $"[{{\"__byte[]\":2}},{{\"__byte[]\":1}}]";
// Act
var deserialized = JsonSerializer.Deserialize<byte[][]>(json, JsonSerializerOptions)!;
// Assert
Assert.Same(byteArray3, deserialized[0]);
Assert.Same(byteArray2, deserialized[1]);
}
[Fact]
public void WriteJsonMultipleTimes_IncrementsByteArrayId()
{
// Arrange
var byteArray = new byte[] { 1, 5, 7 };
// Act & Assert
for (var i = 0; i < 10; i++)
{
var json = JsonSerializer.Serialize(byteArray, JsonSerializerOptions);
Assert.Equal($"{{\"__byte[]\":{i + 1}}}", json);
}
}
}
| ByteArrayJsonConverterTest |
csharp | Cysharp__ZLogger | sandbox/Benchmark/Benchmarks/PostLogEntry.cs | {
"start": 592,
"end": 1238
} | public class ____ : ConsoleFormatterOptions
// {
// }
//
// public MsExtConsoleLoggerFormatter() : base("Benchmark")
// {
// }
//
// public override void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider scopeProvider, TextWriter textWriter)
// {
// var message = logEntry.Formatter.Invoke(logEntry.State, logEntry.Exception);
// var timestamp = DateTime.UtcNow;
// textWriter.Write(timestamp);
// textWriter.Write(" [");
// textWriter.Write(logEntry.LogLevel);
// textWriter.Write("] ");
// textWriter.WriteLine(message);
// }
// }
file | Options |
csharp | dotnet__orleans | src/Azure/Orleans.Streaming.EventHubs/Providers/Streams/EventHub/EventHubPartitionCheckpointEntity.cs | {
"start": 97,
"end": 1360
} | internal class ____ : ITableEntity
{
public string Offset { get; set; }
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public DateTimeOffset? Timestamp { get; set; }
public ETag ETag { get; set; }
public EventHubPartitionCheckpointEntity()
{
Offset = EventHubConstants.StartOfStream;
}
public static EventHubPartitionCheckpointEntity Create(string streamProviderName, string serviceId, string partition)
{
return new EventHubPartitionCheckpointEntity
{
PartitionKey = MakePartitionKey(streamProviderName, serviceId),
RowKey = MakeRowKey(partition)
};
}
public static string MakePartitionKey(string streamProviderName, string checkpointNamespace)
{
string key = $"EventHubCheckpoints_{streamProviderName}_{checkpointNamespace}";
return AzureTableUtils.SanitizeTableProperty(key);
}
public static string MakeRowKey(string partition)
{
string key = $"partition_{partition}";
return AzureTableUtils.SanitizeTableProperty(key);
}
}
}
| EventHubPartitionCheckpointEntity |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 49488,
"end": 52340
} | public partial class ____ : global::System.IEquatable<SetApiSettingsCommandMutation_UpdateApiSettings_UpdateApiSettingsPayload>, ISetApiSettingsCommandMutation_UpdateApiSettings_UpdateApiSettingsPayload
{
public SetApiSettingsCommandMutation_UpdateApiSettings_UpdateApiSettingsPayload(global::ChilliCream.Nitro.CommandLine.Cloud.Client.ISetApiSettingsCommandMutation_UpdateApiSettings_Api? api, global::System.Collections.Generic.IReadOnlyList<global::ChilliCream.Nitro.CommandLine.Cloud.Client.ISetApiSettingsCommandMutation_UpdateApiSettings_Errors>? errors)
{
Api = api;
Errors = errors;
}
public global::ChilliCream.Nitro.CommandLine.Cloud.Client.ISetApiSettingsCommandMutation_UpdateApiSettings_Api? Api { get; }
public global::System.Collections.Generic.IReadOnlyList<global::ChilliCream.Nitro.CommandLine.Cloud.Client.ISetApiSettingsCommandMutation_UpdateApiSettings_Errors>? Errors { get; }
public virtual global::System.Boolean Equals(SetApiSettingsCommandMutation_UpdateApiSettings_UpdateApiSettingsPayload? other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (other.GetType() != GetType())
{
return false;
}
return (((Api is null && other.Api is null) || Api != null && Api.Equals(other.Api))) && global::StrawberryShake.Internal.ComparisonHelper.SequenceEqual(Errors, other.Errors);
}
public override global::System.Boolean Equals(global::System.Object? obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((SetApiSettingsCommandMutation_UpdateApiSettings_UpdateApiSettingsPayload)obj);
}
public override global::System.Int32 GetHashCode()
{
unchecked
{
int hash = 5;
if (Api != null)
{
hash ^= 397 * Api.GetHashCode();
}
if (Errors != null)
{
foreach (var Errors_elm in Errors)
{
hash ^= 397 * Errors_elm.GetHashCode();
}
}
return hash;
}
}
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| SetApiSettingsCommandMutation_UpdateApiSettings_UpdateApiSettingsPayload |
csharp | ivanpaulovich__clean-architecture-manga | accounts-api/src/Infrastructure/DataAccess/UnitOfWork.cs | {
"start": 241,
"end": 920
} | public sealed class ____ : IUnitOfWork, IDisposable
{
private readonly MangaContext _context;
private bool _disposed;
public UnitOfWork(MangaContext context) => this._context = context;
/// <inheritdoc />
public void Dispose() => this.Dispose(true);
/// <inheritdoc />
public async Task<int> Save()
{
int affectedRows = await this._context
.SaveChangesAsync()
.ConfigureAwait(false);
return affectedRows;
}
private void Dispose(bool disposing)
{
if (!this._disposed && disposing)
{
this._context.Dispose();
}
this._disposed = true;
}
}
| UnitOfWork |
csharp | HangfireIO__Hangfire | src/Hangfire.Core/Dashboard/IDashboardDispatcher.cs | {
"start": 1604,
"end": 2080
} | public interface ____
{
/// <summary>
/// Processes the request within the provided <see cref="DashboardContext"/>.
/// </summary>
/// <param name="context">The context for the current dashboard request, containing information about the request and response.</param>
/// <returns>A task that represents the asynchronous dispatch operation.</returns>
Task Dispatch([NotNull] DashboardContext context);
}
} | IDashboardDispatcher |
csharp | SixLabors__Fonts | src/SixLabors.Fonts/Tables/General/Colr/ColrGlyphSourceBase.cs | {
"start": 292,
"end": 338
} | class ____ COLR glyph sources.
/// </summary>
| for |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/TestModels/JsonQuery/JsonEntityAllTypes.cs | {
"start": 357,
"end": 4308
} | public class ____
{
private ObservableCollection<int?> _testNullableInt32CollectionX = [99];
private Collection<JsonEnum?> _testNullableEnumCollectionX = [];
private Collection<JsonEnum?> _testNullableEnumWithIntConverterCollectionX = [JsonEnum.Three];
public List<List<long>> TestInt64CollectionCollection { get; set; } = [];
public IReadOnlyList<double[]> TestDoubleCollectionCollection { get; set; } = new List<double[]>();
public List<float>[] TestSingleCollectionCollection { get; set; } = [[1.1f, 1.2f]];
public bool[][] TestBooleanCollectionCollection { get; set; } = [];
public ObservableCollection<ReadOnlyCollection<char>> TestCharacterCollectionCollection { get; set; } = [];
public int Id { get; set; }
public JsonOwnedAllTypes Reference { get; init; }
public List<JsonOwnedAllTypes> Collection { get; init; }
public string[] TestDefaultStringCollection { get; init; }
public List<string> TestMaxLengthStringCollection { get; init; }
public IList<short> TestInt16Collection { get; set; }
public string[][] TestDefaultStringCollectionCollection { get; init; }
public List<IReadOnlyList<string>> TestMaxLengthStringCollectionCollection { get; init; }
public IReadOnlyList<IReadOnlyList<short>> TestInt16CollectionCollection { get; set; }
public int[] TestInt32Collection { get; set; } = [];
public int[][] TestInt32CollectionCollection { get; set; } = [];
public decimal[] TestDecimalCollection { get; set; }
public List<DateTime> TestDateTimeCollection { get; set; }
public IList<DateTimeOffset> TestDateTimeOffsetCollection { get; set; }
public TimeSpan[] TestTimeSpanCollection { get; set; } = [new(1, 1, 1)];
public ReadOnlyCollection<long> TestInt64Collection { get; set; } = new([]);
public IList<double> TestDoubleCollection { get; set; } = new List<double>();
public IReadOnlyList<float> TestSingleCollection { get; set; } = [1.1f, 1.2f];
public IList<bool> TestBooleanCollection { get; set; } = new List<bool> { true };
public ObservableCollection<char> TestCharacterCollection { get; set; } = [];
public byte[] TestByteCollection { get; set; }
[Required]
public ReadOnlyCollection<Guid> TestGuidCollection { get; set; }
public IList<ushort> TestUnsignedInt16Collection { get; set; }
public uint[] TestUnsignedInt32Collection { get; set; }
public ObservableCollection<ulong> TestUnsignedInt64Collection { get; set; }
public sbyte[] TestSignedByteCollection { get; set; }
public ObservableCollection<int?> TestNullableInt32Collection
{
get => _testNullableInt32CollectionX;
set
{
_testNullableInt32CollectionX = value;
NewCollectionSet = true;
}
}
public IList<JsonEnum> TestEnumCollection { get; set; }
public JsonEnum[] TestEnumWithIntConverterCollection { get; set; }
public Collection<JsonEnum?> TestNullableEnumCollection
{
get => _testNullableEnumCollectionX;
set
{
NewCollectionSet = true;
_testNullableEnumCollectionX = value;
}
}
public Collection<JsonEnum?> TestNullableEnumWithIntConverterCollection
{
get => _testNullableEnumWithIntConverterCollectionX;
set
{
_testNullableEnumWithIntConverterCollectionX = value;
NewCollectionSet = true;
}
}
public ObservableCollection<int?[]> TestNullableInt32CollectionCollection { get; set; } = [[99]];
public ICollection<List<Collection<JsonEnum?>>> TestNullableEnumCollectionCollection { get; set; } = [];
public JsonEnum?[][][] TestNullableEnumWithIntConverterCollectionCollection { get; set; } = [[[JsonEnum.Three]]];
public JsonEnum?[] TestNullableEnumWithConverterThatHandlesNullsCollection { get; set; }
[NotMapped]
public bool NewCollectionSet { get; private set; }
}
| JsonEntityAllTypes |
csharp | nopSolutions__nopCommerce | src/Plugins/Nop.Plugin.Shipping.UPS/API/Rates/RateClient.cs | {
"start": 277235,
"end": 278760
} | public partial class ____
{
/// <summary>
/// Density is returned if the Shipper is eligible for Density based rate. Valid values:0 to 999.9
/// </summary>
[Newtonsoft.Json.JsonProperty("Density", Required = Newtonsoft.Json.Required.Always)]
[System.ComponentModel.DataAnnotations.Required]
[System.ComponentModel.DataAnnotations.StringLength(5, MinimumLength = 1)]
public string Density { get; set; }
/// <summary>
/// TotalCubic feet is returned if the Shipper is eligible for Density based rate. Valid values:0 to 99999.999
/// </summary>
[Newtonsoft.Json.JsonProperty("TotalCubicFeet", Required = Newtonsoft.Json.Required.Always)]
[System.ComponentModel.DataAnnotations.Required]
[System.ComponentModel.DataAnnotations.StringLength(9, MinimumLength = 1)]
public string TotalCubicFeet { get; set; }
private System.Collections.Generic.IDictionary<string, object> _additionalProperties;
[Newtonsoft.Json.JsonExtensionData]
public System.Collections.Generic.IDictionary<string, object> AdditionalProperties
{
get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary<string, object>()); }
set { _additionalProperties = value; }
}
}
[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.0.7.0 (NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0))")]
| FRSShipmentData_FreightDensityRate |
csharp | microsoft__garnet | main/GarnetServer/Extensions/MSetPx.cs | {
"start": 478,
"end": 1781
} | sealed class ____ : CustomTransactionProcedure
{
/// <summary>
/// No transactional phase, skip Prepare
/// </summary>
public override bool Prepare<TGarnetReadApi>(TGarnetReadApi api, ref CustomProcedureInput procInput)
=> false;
/// <summary>
/// Main will not be called because Prepare returns false
/// </summary>
public override void Main<TGarnetApi>(TGarnetApi api, ref CustomProcedureInput procInput, ref MemoryResult<byte> output)
=> throw new InvalidOperationException();
/// <summary>
/// Perform the MSETPX operation
/// </summary>
public override void Finalize<TGarnetApi>(TGarnetApi api, ref CustomProcedureInput procInput, ref MemoryResult<byte> output)
{
int offset = 0;
// Read expiry
var expiryMs = GetNextArg(ref procInput, ref offset);
// Read and set key-value pairs with expiry
ArgSlice key, value;
while ((key = GetNextArg(ref procInput, ref offset)).Length > 0)
{
value = GetNextArg(ref procInput, ref offset);
api.SETEX(key, value, expiryMs);
}
WriteSimpleString(ref output, "OK");
}
}
} | MSetPxTxn |
csharp | nuke-build__nuke | source/Nuke.Common/Tools/Unity/Unity.Generated.cs | {
"start": 152132,
"end": 153091
} | public partial class ____ : Enumeration
{
public static UnityPlatformTextureFormat dxt = (UnityPlatformTextureFormat) "dxt";
public static UnityPlatformTextureFormat pvrtc = (UnityPlatformTextureFormat) "pvrtc";
public static UnityPlatformTextureFormat atc = (UnityPlatformTextureFormat) "atc";
public static UnityPlatformTextureFormat etc = (UnityPlatformTextureFormat) "etc";
public static UnityPlatformTextureFormat etc2 = (UnityPlatformTextureFormat) "etc2";
public static UnityPlatformTextureFormat astc = (UnityPlatformTextureFormat) "astc";
public static implicit operator UnityPlatformTextureFormat(string value)
{
return new UnityPlatformTextureFormat { Value = value };
}
}
#endregion
#region UnityTestPlatform
/// <summary>Used within <see cref="UnityTasks"/>.</summary>
[PublicAPI]
[Serializable]
[ExcludeFromCodeCoverage]
[TypeConverter(typeof(TypeConverter<UnityTestPlatform>))]
| UnityPlatformTextureFormat |
csharp | files-community__Files | src/Files.App/Actions/FileSystem/RestoreAllRecycleBinAction.cs | {
"start": 210,
"end": 2034
} | partial class ____ : BaseUIAction, IAction
{
private readonly IStorageTrashBinService StorageTrashBinService = Ioc.Default.GetRequiredService<IStorageTrashBinService>();
public string Label
=> Strings.RestoreAllItems.GetLocalizedResource();
public string Description
=> Strings.RestoreAllRecycleBinDescription.GetLocalizedResource();
public RichGlyph Glyph
=> new(themedIconStyle: "App.ThemedIcons.RestoreDeleted");
public override bool IsExecutable =>
UIHelpers.CanShowDialog &&
StorageTrashBinService.HasItems();
public async Task ExecuteAsync(object? parameter = null)
{
// TODO: Use AppDialogService
var confirmationDialog = new ContentDialog()
{
Title = Strings.ConfirmRestoreBinDialogTitle.GetLocalizedResource(),
Content = Strings.ConfirmRestoreBinDialogContent.GetLocalizedResource(),
PrimaryButtonText = Strings.Yes.GetLocalizedResource(),
SecondaryButtonText = Strings.Cancel.GetLocalizedResource(),
DefaultButton = ContentDialogButton.Primary
};
if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8))
confirmationDialog.XamlRoot = MainWindow.Instance.Content.XamlRoot;
if (await confirmationDialog.TryShowAsync() is not ContentDialogResult.Primary)
return;
bool result = await StorageTrashBinService.RestoreAllTrashesAsync();
// Show error dialog when failed
if (!result)
{
var errorDialog = new ContentDialog()
{
Title = Strings.FailedToRestore.GetLocalizedResource(),
PrimaryButtonText = Strings.OK.GetLocalizedResource(),
};
if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8))
errorDialog.XamlRoot = MainWindow.Instance.Content.XamlRoot;
await errorDialog.TryShowAsync();
}
}
}
}
| RestoreAllRecycleBinAction |
csharp | bitwarden__server | bitwarden_license/src/Scim/Groups/PutGroupCommand.cs | {
"start": 284,
"end": 1716
} | public class ____ : IPutGroupCommand
{
private readonly IGroupRepository _groupRepository;
private readonly IUpdateGroupCommand _updateGroupCommand;
public PutGroupCommand(
IGroupRepository groupRepository,
IUpdateGroupCommand updateGroupCommand)
{
_groupRepository = groupRepository;
_updateGroupCommand = updateGroupCommand;
}
public async Task<Group> PutGroupAsync(Organization organization, Guid id, ScimGroupRequestModel model)
{
var group = await _groupRepository.GetByIdAsync(id);
if (group == null || group.OrganizationId != organization.Id)
{
throw new NotFoundException("Group not found.");
}
group.Name = model.DisplayName;
await _updateGroupCommand.UpdateGroupAsync(group, organization, EventSystemUser.SCIM);
await UpdateGroupMembersAsync(group, model);
return group;
}
private async Task UpdateGroupMembersAsync(Group group, ScimGroupRequestModel model)
{
if (model.Members == null)
{
return;
}
var memberIds = new List<Guid>();
foreach (var id in model.Members.Select(i => i.Value))
{
if (Guid.TryParse(id, out var guidId))
{
memberIds.Add(guidId);
}
}
await _groupRepository.UpdateUsersAsync(group.Id, memberIds);
}
}
| PutGroupCommand |
csharp | MassTransit__MassTransit | src/MassTransit/Middleware/Outbox/OutboxSendEndpointProvider.cs | {
"start": 100,
"end": 971
} | public class ____ :
ISendEndpointProvider
{
readonly OutboxSendContext _outboxContext;
readonly ISendEndpointProvider _sendEndpointProvider;
public OutboxSendEndpointProvider(OutboxSendContext outboxContext, ISendEndpointProvider sendEndpointProvider)
{
_outboxContext = outboxContext;
_sendEndpointProvider = sendEndpointProvider;
}
public ConnectHandle ConnectSendObserver(ISendObserver observer)
{
return _sendEndpointProvider.ConnectSendObserver(observer);
}
public async Task<ISendEndpoint> GetSendEndpoint(Uri address)
{
var endpoint = await _sendEndpointProvider.GetSendEndpoint(address).ConfigureAwait(false);
return new OutboxSendEndpoint(_outboxContext, endpoint);
}
}
}
| OutboxSendEndpointProvider |
csharp | dotnet__extensions | test/Generators/Microsoft.Gen.Logging/TestClasses/ConstraintsTestExtensions.cs | {
"start": 912,
"end": 1190
} | partial class ____<T>
where T : unmanaged
{
[LoggerMessage(0, LogLevel.Debug, "M0{p0}")]
public static partial void M0(ILogger logger, int p0);
public static void Foo(T _)
{
}
}
internal static | ConstraintsTestExtensions2 |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.Tests/Execution/InputsTests.cs | {
"start": 3071,
"end": 4129
} | public class ____ : ObjectGraphType
{
public UserQuery()
{
Field<UserType>("user")
.Resolve(c => new User
{
Id = 1,
Gender = Gender.Male,
ProfileImage = "hello.png"
});
Field<UserType>("getIntUser")
.Description("get user api")
.Argument<NonNullGraphType<IntGraphType>>("userId", "user id")
.Resolve(context =>
{
int id = context.GetArgument<int>("userId");
return new User
{
Id = id
};
}
);
Field<UserType>("getLongUser")
.Description("get user api")
.Argument<NonNullGraphType<LongGraphType>>("userId", "user id")
.Resolve(context =>
{
long id = context.GetArgument<long>("userId");
return new User
{
IdLong = id
};
}
);
}
}
| UserQuery |
csharp | kgrzybek__modular-monolith-with-ddd | src/Modules/UserAccess/Infrastructure/Configuration/Assemblies.cs | {
"start": 185,
"end": 321
} | internal static class ____
{
public static readonly Assembly Application = typeof(IUserAccessModule).Assembly;
}
} | Assemblies |
csharp | CommunityToolkit__WindowsCommunityToolkit | Microsoft.Toolkit.Uwp.UI.Media/Geometry/Core/GeometryTypeDefinitions.cs | {
"start": 344,
"end": 610
} | internal enum ____
{
FillRule,
PathFigure,
EllipseFigure,
PolygonFigure,
RectangleFigure,
RoundedRectangleFigure
}
/// <summary>
/// Enum for the various PathElements.
/// </summary>
| PathFigureType |
csharp | ChilliCream__graphql-platform | src/StrawberryShake/Client/src/Transport.InMemory/DependencyInjection/DefaultInMemoryClientFactory.cs | {
"start": 133,
"end": 1883
} | public class ____ : IInMemoryClientFactory
{
private readonly IRequestExecutorProvider _executorProvider;
private readonly IOptionsMonitor<InMemoryClientFactoryOptions> _optionsMonitor;
/// <summary>
/// Initializes a new instance of <see cref="DefaultInMemoryClientFactory"/>
/// </summary>
/// <param name="executorProvider">
/// The <see cref="IRequestExecutorProvider"/> that should be used to resolve the schemas
/// </param>
/// <param name="optionsMonitor">
/// The options monitor for the factory options
/// </param>
public DefaultInMemoryClientFactory(
IRequestExecutorProvider executorProvider,
IOptionsMonitor<InMemoryClientFactoryOptions> optionsMonitor)
{
ArgumentNullException.ThrowIfNull(executorProvider);
ArgumentNullException.ThrowIfNull(optionsMonitor);
_executorProvider = executorProvider;
_optionsMonitor = optionsMonitor;
}
/// <inheritdoc />
public async ValueTask<IInMemoryClient> CreateAsync(
string name,
CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrEmpty(name);
var options = _optionsMonitor.Get(name);
var client = new InMemoryClient(name);
foreach (var configurationAction in options.InMemoryClientActions)
{
await configurationAction(client, cancellationToken);
}
if (client.Executor is not null)
{
client.SchemaName = client.Executor.Schema.Name;
}
else
{
client.Executor = await _executorProvider.GetExecutorAsync(client.SchemaName, cancellationToken);
}
return client;
}
}
| DefaultInMemoryClientFactory |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/test/Types.Analyzers.Tests/PagingTests.cs | {
"start": 20736,
"end": 21466
} | public class ____(GreenDonut.Data.Page<Author> page, Author author) : PageEdge<Author>(page, author)
{
public Author Author => Node;
}
}
""").MatchMarkdownAsync();
}
[Fact]
public async Task GenerateSource_ConnectionFlags()
{
await TestHelper.GetGeneratedSourceSnapshot(
"""
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using HotChocolate;
using HotChocolate.Types;
using HotChocolate.Types.Pagination;
namespace TestNamespace
{
| AuthorEdge |
csharp | nopSolutions__nopCommerce | src/Plugins/Nop.Plugin.Payments.PayPalCommerce/Services/Api/Models/Enums/CategoryType.cs | {
"start": 143,
"end": 768
} | public enum ____
{
/// <summary>
/// Goods that are stored, delivered, and used in their electronic format. This value is not currently supported for API callers that leverage the [PayPal for Commerce Platform](https://www.paypal.com/us/webapps/mpp/commerce-platform) product.
/// </summary>
DIGITAL_GOODS,
/// <summary>
/// A tangible item that can be shipped with proof of delivery.
/// </summary>
PHYSICAL_GOODS,
/// <summary>
/// A contribution or gift for which no good or service is exchanged, usually to a not for profit organization.
/// </summary>
DONATION
} | CategoryType |
csharp | DuendeSoftware__IdentityServer | identity-server/hosts/UI/EntityFramework/Pages/Admin/Clients/ClientRepository.cs | {
"start": 1718,
"end": 8542
} | public class ____
{
private readonly ConfigurationDbContext _context;
public ClientRepository(ConfigurationDbContext context) => _context = context;
public async Task<IEnumerable<ClientSummaryModel>> GetAllAsync(string? filter = null)
{
var grants = new[] { GrantType.AuthorizationCode, GrantType.ClientCredentials };
var query = _context.Clients
.Include(x => x.AllowedGrantTypes)
.Where(x => x.AllowedGrantTypes.Count == 1 && x.AllowedGrantTypes.Any(grant => grants.Contains(grant.GrantType)));
if (!string.IsNullOrWhiteSpace(filter))
{
query = query.Where(x => x.ClientId.Contains(filter) || x.ClientName.Contains(filter));
}
var result = query.Select(x => new ClientSummaryModel
{
ClientId = x.ClientId,
Name = x.ClientName,
Flow = x.AllowedGrantTypes.Select(x => x.GrantType).Single() == GrantType.ClientCredentials ? Flow.ClientCredentials : Flow.CodeFlowWithPkce
});
return await result.ToArrayAsync();
}
public async Task<EditClientModel?> GetByIdAsync(string id)
{
var client = await _context.Clients
.Include(x => x.AllowedGrantTypes)
.Include(x => x.AllowedScopes)
.Include(x => x.RedirectUris)
.Include(x => x.PostLogoutRedirectUris)
.Where(x => x.ClientId == id)
.SingleOrDefaultAsync();
if (client == null)
{
return null;
}
return new EditClientModel
{
ClientId = client.ClientId,
Name = client.ClientName,
Flow = client.AllowedGrantTypes.Select(x => x.GrantType)
.Single() == GrantType.ClientCredentials ? Flow.ClientCredentials : Flow.CodeFlowWithPkce,
AllowedScopes = client.AllowedScopes.Count != 0 ? client.AllowedScopes.Select(x => x.Scope).Aggregate((a, b) => $"{a} {b}") : string.Empty,
RedirectUri = client.RedirectUris.Select(x => x.RedirectUri).SingleOrDefault(),
InitiateLoginUri = client.InitiateLoginUri,
PostLogoutRedirectUri = client.PostLogoutRedirectUris.Select(x => x.PostLogoutRedirectUri).SingleOrDefault(),
FrontChannelLogoutUri = client.FrontChannelLogoutUri,
BackChannelLogoutUri = client.BackChannelLogoutUri,
};
}
public async Task CreateAsync(CreateClientModel model)
{
ArgumentNullException.ThrowIfNull(model);
var client = new Duende.IdentityServer.Models.Client();
client.ClientId = model.ClientId.Trim();
client.ClientName = model.Name?.Trim();
client.ClientSecrets.Add(new Duende.IdentityServer.Models.Secret(model.Secret.Sha256()));
if (model.Flow == Flow.ClientCredentials)
{
client.AllowedGrantTypes = GrantTypes.ClientCredentials;
}
else
{
client.AllowedGrantTypes = GrantTypes.Code;
client.AllowOfflineAccess = true;
}
#pragma warning disable CA1849 // Call async methods when in an async method
// CA1849 Suppressed because AddAsync is only needed for value generators that
// need async database access (e.g., HiLoValueGenerator), and we don't use those
// generators
_context.Clients.Add(client.ToEntity());
#pragma warning restore CA1849 // Call async methods when in an async method
await _context.SaveChangesAsync();
}
public async Task UpdateAsync(EditClientModel model)
{
ArgumentNullException.ThrowIfNull(model);
var client = await _context.Clients
.Include(x => x.AllowedGrantTypes)
.Include(x => x.AllowedScopes)
.Include(x => x.RedirectUris)
.Include(x => x.PostLogoutRedirectUris)
.SingleOrDefaultAsync(x => x.ClientId == model.ClientId);
if (client == null)
{
throw new ArgumentException("Invalid Client Id");
}
if (client.ClientName != model.Name)
{
client.ClientName = model.Name?.Trim();
}
var scopes = model.AllowedScopes.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var currentScopes = (client.AllowedScopes.Select(x => x.Scope) ?? Enumerable.Empty<string>()).ToArray();
var scopesToAdd = scopes.Except(currentScopes).ToArray();
var scopesToRemove = currentScopes.Except(scopes).ToArray();
if (scopesToRemove.Length != 0)
{
client.AllowedScopes.RemoveAll(x => scopesToRemove.Contains(x.Scope));
}
if (scopesToAdd.Length != 0)
{
client.AllowedScopes.AddRange(scopesToAdd.Select(x => new ClientScope
{
Scope = x,
}));
}
var flow = client.AllowedGrantTypes.Select(x => x.GrantType)
.Single() == GrantType.ClientCredentials ? Flow.ClientCredentials : Flow.CodeFlowWithPkce;
if (flow == Flow.CodeFlowWithPkce)
{
if (client.RedirectUris.SingleOrDefault()?.RedirectUri != model.RedirectUri)
{
client.RedirectUris.Clear();
if (model.RedirectUri != null)
{
client.RedirectUris.Add(new ClientRedirectUri { RedirectUri = model.RedirectUri.Trim() });
}
}
if (client.InitiateLoginUri != model.InitiateLoginUri)
{
client.InitiateLoginUri = model.InitiateLoginUri;
}
if (client.PostLogoutRedirectUris.SingleOrDefault()?.PostLogoutRedirectUri != model.PostLogoutRedirectUri)
{
client.PostLogoutRedirectUris.Clear();
if (model.PostLogoutRedirectUri != null)
{
client.PostLogoutRedirectUris.Add(new ClientPostLogoutRedirectUri { PostLogoutRedirectUri = model.PostLogoutRedirectUri.Trim() });
}
}
if (client.FrontChannelLogoutUri != model.FrontChannelLogoutUri)
{
client.FrontChannelLogoutUri = model.FrontChannelLogoutUri?.Trim();
}
if (client.BackChannelLogoutUri != model.BackChannelLogoutUri)
{
client.BackChannelLogoutUri = model.BackChannelLogoutUri?.Trim();
}
}
await _context.SaveChangesAsync();
}
public async Task DeleteAsync(string clientId)
{
var client = await _context.Clients.SingleOrDefaultAsync(x => x.ClientId == clientId);
if (client == null)
{
throw new ArgumentException("Invalid Client Id");
}
_context.Clients.Remove(client);
await _context.SaveChangesAsync();
}
}
| ClientRepository |
csharp | dotnet__aspnetcore | src/Components/WebAssembly/testassets/Wasm.Prerendered.Server/Program.cs | {
"start": 174,
"end": 586
} | public class ____
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IHost BuildWebHost(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStaticWebAssets();
webBuilder.UseStartup<Startup>();
})
.Build();
}
| Program |
csharp | xunit__xunit | src/xunit.v3.core/Internal/TraceCaptureTestOutputWriter.cs | {
"start": 115,
"end": 887
} | public sealed class ____ : TraceListener
{
readonly ITestContextAccessor testContextAccessor;
/// <summary/>
public TraceCaptureTestOutputWriter(ITestContextAccessor testContextAccessor)
{
this.testContextAccessor = testContextAccessor;
Trace.Listeners.Add(this);
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
Trace.Listeners.Remove(this);
base.Dispose(disposing);
}
/// <inheritdoc/>
public override void Write(string? message)
{
if (message is not null)
testContextAccessor.Current.TestOutputHelper?.Write(message);
}
/// <inheritdoc/>
public override void WriteLine(string? message)
{
if (message is not null)
testContextAccessor.Current.TestOutputHelper?.WriteLine(message);
}
}
| TraceCaptureTestOutputWriter |
csharp | dotnet__maui | src/Controls/samples/Controls.Sample/Pages/Controls/CollectionViewGalleries/HeaderFooterGalleries/HeaderFooterTemplate.xaml.cs | {
"start": 673,
"end": 1539
} | class ____ : INotifyPropertyChanged
{
readonly DemoFilteredItemSource _demoFilteredItemSource = new DemoFilteredItemSource(3);
DateTime _currentTime;
public event PropertyChangedEventHandler? PropertyChanged;
public HeaderFooterDemoModel()
{
CurrentTime = DateTime.Now;
}
void OnPropertyChanged([CallerMemberName] string property = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
public ObservableCollection<CollectionViewGalleryTestItem> Items => _demoFilteredItemSource.Items;
public ICommand TapCommand => new Command(() => { CurrentTime = DateTime.Now; });
public DateTime CurrentTime
{
get => _currentTime;
set
{
if (value == _currentTime)
{
return;
}
_currentTime = value;
OnPropertyChanged();
}
}
}
}
} | HeaderFooterDemoModel |
csharp | NSubstitute__NSubstitute | src/NSubstitute/Routing/Handlers/PropertySetterHandler.cs | {
"start": 66,
"end": 925
} | public class ____(IPropertyHelper propertyHelper, IConfigureCall configureCall) : ICallHandler
{
public RouteAction Handle(ICall call)
{
if (propertyHelper.IsCallToSetAReadWriteProperty(call))
{
var callToPropertyGetter = propertyHelper.CreateCallToPropertyGetterFromSetterCall(call);
// It's important to use original arguments, as it provides better performance.
// It's safe to use original arguments here, as only by-ref arguments might be modified,
// which should never happen for this case.
var valueBeingSetOnProperty = call.GetOriginalArguments().Last();
configureCall.SetResultForCall(callToPropertyGetter, new ReturnValue(valueBeingSetOnProperty), MatchArgs.AsSpecifiedInCall);
}
return RouteAction.Continue();
}
} | PropertySetterHandler |
csharp | dotnet__BenchmarkDotNet | tests/BenchmarkDotNet.IntegrationTests/InProcess.EmitTests.T4/RunnableClassCaseBenchmark.cs | {
"start": 494,
"end": 552
} | class ____ check emitted msil cases
/// </summary>
| to |
csharp | dotnet__aspnetcore | src/Framework/AspNetCoreAnalyzers/test/WebApplicationBuilder/DisallowConfigureWebHostBuilderConfigureTest.cs | {
"start": 2997,
"end": 3217
} | public static class ____
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.WebHost./*MM*/Configure((context, webHostBuilder) => { });
}
}
| Program |
csharp | fluentassertions__fluentassertions | Tests/FluentAssertions.Specs/Formatting/FormatterSpecs.cs | {
"start": 1265,
"end": 19294
} | private class ____
{
public A X { get; set; }
public A Y { get; set; }
}
[Fact]
public void When_the_subject_or_expectation_contains_reserved_symbols_it_should_escape_then()
{
// Arrange
string result = "{ a : [{ b : \"2016-05-23T10:45:12Z\" } ]}";
string expectedJson = "{ a : [{ b : \"2016-05-23T10:45:12Z\" }] }";
// Act
Action act = () => result.Should().Be(expectedJson);
// Assert
act.Should().Throw<XunitException>().WithMessage("*at*index 37*");
}
[Fact]
public void When_a_timespan_is_one_tick_it_should_be_formatted_as_positive()
{
// Arrange
var time = TimeSpan.FromTicks(1);
// Act
string result = Formatter.ToString(time);
// Assert
result.Should().NotStartWith("-");
}
[Fact]
public void When_a_timespan_is_minus_one_tick_it_should_be_formatted_as_negative()
{
// Arrange
var time = TimeSpan.FromTicks(-1);
// Act
string result = Formatter.ToString(time);
// Assert
result.Should().StartWith("-");
}
[Fact]
public void When_a_datetime_is_very_close_to_the_edges_of_a_datetimeoffset_it_should_not_crash()
{
// Arrange
var dateTime = DateTime.MinValue + 1.Minutes();
// Act
string result = Formatter.ToString(dateTime);
// Assert
result.Should().Be("<00:01:00>");
}
[Fact]
public void When_the_minimum_value_of_a_datetime_is_provided_it_should_return_a_clear_representation()
{
// Arrange
var dateTime = DateTime.MinValue;
// Act
string result = Formatter.ToString(dateTime);
// Assert
result.Should().Be("<0001-01-01 00:00:00.000>");
}
[Fact]
public void When_the_maximum_value_of_a_datetime_is_provided_it_should_return_a_clear_representation()
{
// Arrange
var dateTime = DateTime.MaxValue;
// Act
string result = Formatter.ToString(dateTime);
// Assert
result.Should().Be("<9999-12-31 23:59:59.9999999>");
}
[Fact]
public void When_a_property_throws_an_exception_it_should_ignore_that_and_still_create_a_descriptive_error_message()
{
// Arrange
var subject = new ExceptionThrowingClass();
// Act
string result = Formatter.ToString(subject);
// Assert
result.Should().Contain("Member 'ThrowingProperty' threw an exception: 'CustomMessage'");
}
[Fact]
public void When_an_exception_contains_an_inner_exception_they_should_both_appear_in_the_error_message()
{
// Arrange
Exception subject = new("OuterExceptionMessage", new InvalidOperationException("InnerExceptionMessage"));
// Act
string result = Formatter.ToString(subject);
// Assert
result.Should().Contain("OuterExceptionMessage")
.And.Contain("InnerExceptionMessage");
}
[Fact]
public void When_the_object_is_a_generic_type_without_custom_string_representation_it_should_show_the_properties()
{
// Arrange
var stuff = new List<Stuff<int>>
{
new()
{
StuffId = 1,
Description = "Stuff_1",
Children = [1, 2, 3, 4]
},
new()
{
StuffId = 2,
Description = "Stuff_2",
Children = [1, 2, 3, 4]
}
};
// Act
var actual = Formatter.ToString(stuff);
// Assert
actual.Should().Match(
"""
{
FluentAssertions.Specs.Formatting.FormatterSpecs+Stuff`1[[System.Int32*]]
{
Children = {1, 2, 3, 4},
Description = "Stuff_1",
StuffId = 1
},
FluentAssertions.Specs.Formatting.FormatterSpecs+Stuff`1[[System.Int32*]]
{
Children = {1, 2, 3, 4},
Description = "Stuff_2",
StuffId = 2
}
}
""");
}
[Fact]
public void When_the_object_is_a_user_defined_type_it_should_show_the_name_on_the_initial_line()
{
// Arrange
var stuff = new StuffRecord(42, "description", new ChildRecord(24), [10, 20, 30, 40]);
// Act
Action act = () => stuff.Should().BeNull();
// Assert
act.Should().Throw<XunitException>()
.Which.Message.Should().Match(
"""
Expected stuff to be <null>, but found FluentAssertions.Specs.Formatting.FormatterSpecs+StuffRecord
{
RecordChildren = {10, 20, 30, 40},
RecordDescription = "description",
RecordId = 42,
SingleChild = FluentAssertions.Specs.Formatting.FormatterSpecs+ChildRecord
{
ChildRecordId = 24
}
}.
""");
}
[Fact]
public void When_the_object_is_an_anonymous_type_it_should_show_the_properties_recursively()
{
// Arrange
var stuff = new
{
Description = "absent",
SingleChild = new { ChildId = 8 },
Children = new[] { 1, 2, 3, 4 },
};
// Act
string actual = Formatter.ToString(stuff);
// Assert
actual.Should().Match(
"""
{
Children = {1, 2, 3, 4},
Description = "absent",
SingleChild =
{
ChildId = 8
}
}
""");
}
[Fact]
public void
When_the_object_is_a_list_of_anonymous_type_it_should_show_the_properties_recursively_with_newlines_and_indentation()
{
// Arrange
var expectedStuff =
new
{
ComplexChildren = new[]
{
new { Property = "hello" },
new { Property = "goodbye" },
},
};
// Act
var actual = Formatter.ToString(expectedStuff);
// Assert
actual.Should().Be(
"""
{
ComplexChildren =
{
{
Property = "hello"
},
{
Property = "goodbye"
}
}
}
""");
}
[Fact]
public void When_the_object_is_an_empty_anonymous_type_it_should_show_braces_on_the_same_line()
{
// Arrange
var stuff = new
{
};
// Act
Action act = () => stuff.Should().BeNull();
// Assert
act.Should().Throw<XunitException>()
.Which.Message.Should().Match("*but found *{ }*");
}
[Fact]
public void When_the_object_is_a_tuple_it_should_show_the_properties_recursively()
{
// Arrange
(int TupleId, string Description, List<int> Children) stuff = (1, "description", [1, 2, 3, 4]);
// Act
string actual = Formatter.ToString(stuff);
// Assert
actual.Should().Match(
"""
{
Item1 = 1,*
Item2 = "description",*
Item3 = {1, 2, 3, 4}
}
""");
}
[Fact]
public void When_the_object_is_a_record_it_should_show_the_properties_recursively()
{
// Arrange
var stuff = new StuffRecord(
RecordId: 9,
RecordDescription: "descriptive",
SingleChild: new ChildRecord(ChildRecordId: 80),
RecordChildren: [4, 5, 6, 7]);
var actual = Formatter.ToString(stuff);
// Assert
actual.Should().Match(
"""
FluentAssertions.Specs.Formatting.FormatterSpecs+StuffRecord
{
RecordChildren = {4, 5, 6, 7},*
RecordDescription = "descriptive",*
RecordId = 9,*
SingleChild = FluentAssertions.Specs.Formatting.FormatterSpecs+ChildRecord
{
ChildRecordId = 80
}
}
""");
}
[Fact]
public void When_the_to_string_override_throws_it_should_use_the_default_behavior()
{
// Arrange
var subject = new NullThrowingToStringImplementation();
// Act
string result = Formatter.ToString(subject);
// Assert
result.Should().Contain("SomeProperty");
}
[Fact]
public void
When_the_maximum_recursion_depth_is_met_it_should_give_a_descriptive_message()
{
// Arrange
var head = new Node();
var node = head;
int maxDepth = 10;
int iterations = (maxDepth / 2) + 1; // Each iteration adds two levels of depth to the graph
foreach (int i in Enumerable.Range(0, iterations))
{
var newHead = new Node();
node.Children.Add(newHead);
node = newHead;
}
// Act
string result = Formatter.ToString(head, new FormattingOptions
{
MaxDepth = maxDepth
});
// Assert
result.Should().ContainEquivalentOf($"maximum recursion depth of {maxDepth}");
}
[Fact]
public void When_the_maximum_recursion_depth_is_never_reached_it_should_render_the_entire_graph()
{
// Arrange
var head = new Node();
var node = head;
int iterations = 10;
foreach (int i in Enumerable.Range(0, iterations))
{
var newHead = new Node();
node.Children.Add(newHead);
node = newHead;
}
// Act
string result = Formatter.ToString(head, new FormattingOptions
{
// Each iteration adds two levels of depth to the graph
MaxDepth = (iterations * 2) + 1
});
// Assert
result.Should().NotContainEquivalentOf("maximum recursion depth");
}
[Fact]
public void When_formatting_a_collection_exceeds_the_max_line_count_it_should_cut_off_the_result()
{
// Arrange
var collection = Enumerable.Range(0, 20)
.Select(i => new StuffWithAField
{
Description = $"Property {i}",
Field = $"Field {i}",
StuffId = i
})
.ToArray();
// Act
string result = Formatter.ToString(collection, new FormattingOptions
{
MaxLines = 50
});
// Assert
result.Should().Match("*Output has exceeded*50*line*");
}
[Fact]
public void When_formatting_a_byte_array_it_should_limit_the_items()
{
// Arrange
byte[] value = new byte[1000];
new Random().NextBytes(value);
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().Match("{0x*, …968 more…}");
}
[Fact]
public void When_formatting_with_default_behavior_it_should_include_non_private_fields()
{
// Arrange
var stuffWithAField = new StuffWithAField { Field = "Some Text" };
// Act
string result = Formatter.ToString(stuffWithAField);
// Assert
result.Should().Contain("Field").And.Contain("Some Text");
result.Should().NotContain("privateField");
}
[Fact]
public void When_formatting_unsigned_integer_it_should_have_c_sharp_postfix()
{
// Arrange
uint value = 12U;
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().Be("12u");
}
[Fact]
public void When_formatting_long_integer_it_should_have_c_sharp_postfix()
{
// Arrange
long value = 12L;
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().Be("12L");
}
[Fact]
public void When_formatting_unsigned_long_integer_it_should_have_c_sharp_postfix()
{
// Arrange
ulong value = 12UL;
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().Be("12UL");
}
[Fact]
public void When_formatting_short_integer_it_should_have_f_sharp_postfix()
{
// Arrange
short value = 12;
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().Be("12s");
}
[Fact]
public void When_formatting_unsigned_short_integer_it_should_have_f_sharp_postfix()
{
// Arrange
ushort value = 12;
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().Be("12us");
}
[Fact]
public void When_formatting_byte_it_should_use_hexadecimal_notation()
{
// Arrange
byte value = 12;
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().Be("0x0C");
}
[Fact]
public void When_formatting_signed_byte_it_should_have_f_sharp_postfix()
{
// Arrange
sbyte value = 12;
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().Be("12y");
}
[Fact]
public void When_formatting_single_it_should_have_c_sharp_postfix()
{
// Arrange
float value = 12;
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().Be("12F");
}
[Fact]
public void When_formatting_single_positive_infinity_it_should_be_property_reference()
{
// Arrange
float value = float.PositiveInfinity;
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().Be("Single.PositiveInfinity");
}
[Fact]
public void When_formatting_single_negative_infinity_it_should_be_property_reference()
{
// Arrange
float value = float.NegativeInfinity;
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().Be("Single.NegativeInfinity");
}
[Fact]
public void When_formatting_single_it_should_have_max_precision()
{
// Arrange
float value = 1 / 3F;
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().BeOneOf("0.33333334F", "0.333333343F");
}
[Fact]
public void When_formatting_single_not_a_number_it_should_just_say_nan()
{
// Arrange
float value = float.NaN;
// Act
string result = Formatter.ToString(value);
// Assert
// NaN is not even equal to itself so its type does not matter.
result.Should().Be("NaN");
}
[Fact]
public void When_formatting_double_integer_it_should_have_decimal_point()
{
// Arrange
double value = 12;
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().Be("12.0");
}
[Fact]
public void When_formatting_double_with_big_exponent_it_should_have_exponent()
{
// Arrange
double value = 1E+30;
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().Be("1E+30");
}
[Fact]
public void When_formatting_double_positive_infinity_it_should_be_property_reference()
{
// Arrange
double value = double.PositiveInfinity;
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().Be("Double.PositiveInfinity");
}
[Fact]
public void When_formatting_double_negative_infinity_it_should_be_property_reference()
{
// Arrange
double value = double.NegativeInfinity;
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().Be("Double.NegativeInfinity");
}
[Fact]
public void When_formatting_double_not_a_number_it_should_just_say_nan()
{
// Arrange
double value = double.NaN;
// Act
string result = Formatter.ToString(value);
// Assert
// NaN is not even equal to itself so its type does not matter.
result.Should().Be("NaN");
}
[Fact]
public void When_formatting_double_it_should_have_max_precision()
{
// Arrange
double value = 1 / 3D;
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().BeOneOf("0.3333333333333333", "0.33333333333333331");
}
[Fact]
public void When_formatting_decimal_it_should_have_c_sharp_postfix()
{
// Arrange
decimal value = 12;
// Act
string result = Formatter.ToString(value);
// Assert
result.Should().Be("12M");
}
[Fact]
public void When_formatting_a_pending_task_it_should_return_the_task_status()
{
// Arrange
Task<int> bar = new TaskCompletionSource<int>().Task;
// Act
string result = Formatter.ToString(bar);
// Assert
result.Should().Be("System.Threading.Tasks.Task`1[System.Int32] {Status=WaitingForActivation}");
}
[Fact]
public void When_formatting_a_completion_source_it_should_include_the_underlying_task()
{
// Arrange
var completionSource = new TaskCompletionSource<int>();
// Act
string result = Formatter.ToString(completionSource);
// Assert
result.Should().Match("*TaskCompletionSource*Task*System.Int32*Status=WaitingForActivation*");
}
| B |
csharp | dotnet__machinelearning | src/Microsoft.ML.OnnxTransformer/OnnxTransform.cs | {
"start": 2296,
"end": 2934
} | internal sealed class ____
{
// Examples of how a column is defined in command line API:
// 2-by-3 tensor:
// Name=tensorName shape=2 shape=3
public CustomShapeInfo() { }
public CustomShapeInfo(string name, int[] shape)
{
Name = name;
Shape = shape;
}
[Argument(ArgumentType.Required, HelpText = "Name of the column")]
public string Name;
[Argument(ArgumentType.Multiple, HelpText = "Shape of the column")]
public int[] Shape;
}
| CustomShapeInfo |
csharp | npgsql__npgsql | test/Npgsql.PluginTests/JsonNetTests.cs | {
"start": 445,
"end": 4742
} | public class ____(NpgsqlDbType npgsqlDbType) : TestBase
{
[Test]
public Task Roundtrip_object()
=> AssertType(
JsonDataSource,
new Foo { Bar = 8 },
IsJsonb ? @"{""Bar"": 8}" : @"{""Bar"":8}",
_pgTypeName,
npgsqlDbType,
isDefault: false,
isNpgsqlDbTypeInferredFromClrType: false);
[Test, IssueLink("https://github.com/npgsql/npgsql/issues/3085")]
public Task Roundtrip_string()
=> AssertType(
JsonDataSource,
@"{""p"": 1}",
@"{""p"": 1}",
_pgTypeName,
npgsqlDbType,
isDefaultForWriting: false,
isNpgsqlDbTypeInferredFromClrType: false);
[Test, IssueLink("https://github.com/npgsql/npgsql/issues/3085")]
public Task Roundtrip_char_array()
=> AssertType(
JsonDataSource,
@"{""p"": 1}".ToCharArray(),
@"{""p"": 1}",
_pgTypeName,
npgsqlDbType,
isDefault: false,
isNpgsqlDbTypeInferredFromClrType: false);
[Test, IssueLink("https://github.com/npgsql/npgsql/issues/3085")]
public Task Roundtrip_byte_array()
=> AssertType(
JsonDataSource,
Encoding.ASCII.GetBytes(@"{""p"": 1}"),
@"{""p"": 1}",
_pgTypeName,
npgsqlDbType,
isDefault: false,
isNpgsqlDbTypeInferredFromClrType: false);
[Test]
public Task Roundtrip_JObject()
=> AssertType(
JsonDataSource,
new JObject { ["Bar"] = 8 },
IsJsonb ? @"{""Bar"": 8}" : @"{""Bar"":8}",
_pgTypeName,
npgsqlDbType,
// By default we map JObject to jsonb
isDefaultForWriting: IsJsonb,
isDefaultForReading: false,
isNpgsqlDbTypeInferredFromClrType: false);
[Test]
public Task Roundtrip_JArray()
=> AssertType(
JsonDataSource,
new JArray(new[] { 1, 2, 3 }),
IsJsonb ? "[1, 2, 3]" : "[1,2,3]",
_pgTypeName,
npgsqlDbType,
// By default we map JArray to jsonb
isDefaultForWriting: IsJsonb,
isDefaultForReading: false,
isNpgsqlDbTypeInferredFromClrType: false);
[Test]
public async Task Deserialize_failure()
{
await using var conn = await JsonDataSource.OpenConnectionAsync();
await using var cmd = new NpgsqlCommand($@"SELECT '[1, 2, 3]'::{_pgTypeName}", conn);
await using var reader = await cmd.ExecuteReaderAsync();
await reader.ReadAsync();
// Attempt to deserialize JSON array into object
Assert.That(() => reader.GetFieldValue<Foo>(0), Throws.TypeOf<JsonSerializationException>());
// State should still be OK to continue
var actual = reader.GetFieldValue<JArray>(0);
Assert.That((int)actual[0], Is.EqualTo(1));
}
[Test]
public async Task Clr_type_mapping()
{
var dataSourceBuilder = CreateDataSourceBuilder();
if (IsJsonb)
dataSourceBuilder.UseJsonNet(jsonbClrTypes: [typeof(Foo)]);
else
dataSourceBuilder.UseJsonNet(jsonClrTypes: [typeof(Foo)]);
await using var dataSource = dataSourceBuilder.Build();
await AssertType(
dataSource,
new Foo { Bar = 8 },
IsJsonb ? @"{""Bar"": 8}" : @"{""Bar"":8}",
_pgTypeName,
npgsqlDbType,
isDefaultForReading: false,
isNpgsqlDbTypeInferredFromClrType: false);
}
[Test]
public async Task Roundtrip_clr_array()
{
var dataSourceBuilder = CreateDataSourceBuilder();
if (IsJsonb)
dataSourceBuilder.UseJsonNet(jsonbClrTypes: [typeof(int[])]);
else
dataSourceBuilder.UseJsonNet(jsonClrTypes: [typeof(int[])]);
await using var dataSource = dataSourceBuilder.Build();
await AssertType(
dataSource,
new[] { 1, 2, 3 },
IsJsonb ? "[1, 2, 3]" : "[1,2,3]",
_pgTypeName,
npgsqlDbType,
isDefaultForReading: false,
isNpgsqlDbTypeInferredFromClrType: false);
}
| JsonNetTests |
csharp | jellyfin__jellyfin | MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs | {
"start": 547,
"end": 3198
} | public class ____ : IRemoteImageProvider, IHasOrder
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly TmdbClientManager _tmdbClientManager;
/// <summary>
/// Initializes a new instance of the <see cref="TmdbSeasonImageProvider"/> class.
/// </summary>
/// <param name="httpClientFactory">The <see cref="IHttpClientFactory"/>.</param>
/// <param name="tmdbClientManager">The <see cref="TmdbClientManager"/>.</param>
public TmdbSeasonImageProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
{
_httpClientFactory = httpClientFactory;
_tmdbClientManager = tmdbClientManager;
}
/// <inheritdoc/>
public int Order => 1;
/// <inheritdoc/>
public string Name => TmdbUtils.ProviderName;
/// <inheritdoc />
public bool Supports(BaseItem item)
{
return item is Season;
}
/// <inheritdoc />
public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
{
yield return ImageType.Primary;
}
/// <inheritdoc />
public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
{
var season = (Season)item;
var series = season?.Series;
var seriesTmdbId = Convert.ToInt32(series?.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
if (seriesTmdbId <= 0 || season?.IndexNumber is null)
{
return Enumerable.Empty<RemoteImageInfo>();
}
var language = item.GetPreferredMetadataLanguage();
// TODO use image languages if All Languages isn't toggled, but there's currently no way to get that value in here
var seasonResult = await _tmdbClientManager
.GetSeasonAsync(seriesTmdbId, season.IndexNumber.Value, null, null, null, cancellationToken)
.ConfigureAwait(false);
var posters = seasonResult?.Images?.Posters;
if (posters is null)
{
return Enumerable.Empty<RemoteImageInfo>();
}
return _tmdbClientManager.ConvertPostersToRemoteImageInfo(posters, language);
}
/// <inheritdoc />
public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
{
return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
}
}
}
| TmdbSeasonImageProvider |
csharp | dotnet__efcore | test/EFCore.InMemory.FunctionalTests/Query/AdHocQueryFiltersQueryInMemoryTest.cs | {
"start": 1702,
"end": 4542
} | protected class ____(DbContextOptions options) : DbContext(options)
{
public DbSet<Customer19708> Customers { get; set; }
public DbSet<CustomerMembership19708> CustomerMemberships { get; set; }
public DbSet<CustomerFilter19708> CustomerFilters { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CustomerFilter19708>()
.HasQueryFilter(e => (from a in (from c in Customers
join cm in CustomerMemberships on c.Id equals cm.CustomerId into g
from cm in g.DefaultIfEmpty()
select new { c.Id, CustomerMembershipId = (int?)cm.Id })
where a.CustomerMembershipId != null && a.Id == e.CustomerId
select a).Count()
> 0)
.HasKey(e => e.CustomerId);
modelBuilder.Entity<CustomerView19708>().HasNoKey().ToInMemoryQuery(Build_Customers_Sql_View_InMemory());
}
public Task SeedAsync()
{
var customer1 = new Customer19708 { Name = "First" };
var customer2 = new Customer19708 { Name = "Second" };
var customer3 = new Customer19708 { Name = "Third" };
var customerMembership1 = new CustomerMembership19708 { Name = "FirstChild", Customer = customer1 };
var customerMembership2 = new CustomerMembership19708 { Name = "SecondChild1", Customer = customer2 };
var customerMembership3 = new CustomerMembership19708 { Name = "SecondChild2", Customer = customer2 };
AddRange(customer1, customer2, customer3);
AddRange(customerMembership1, customerMembership2, customerMembership3);
return SaveChangesAsync();
}
private Expression<Func<IQueryable<CustomerView19708>>> Build_Customers_Sql_View_InMemory()
{
Expression<Func<IQueryable<CustomerView19708>>> query = () =>
from customer in Customers
join customerMembership in CustomerMemberships on customer.Id equals customerMembership.CustomerId into
nullableCustomerMemberships
from customerMembership in nullableCustomerMemberships.DefaultIfEmpty()
select new CustomerView19708
{
Id = customer.Id,
Name = customer.Name,
CustomerMembershipId = customerMembership != null ? customerMembership.Id : default(int?),
CustomerMembershipName = customerMembership != null ? customerMembership.Name : ""
};
return query;
}
| Context19708 |
csharp | fluentassertions__fluentassertions | Tests/FluentAssertions.Specs/Specialized/AssemblyAssertionSpecs.cs | {
"start": 2666,
"end": 5060
} | public class ____
{
[Fact]
public void When_an_assembly_is_referenced_and_should_reference_is_asserted_it_should_succeed()
{
// Arrange
var assemblyA = FindAssembly.Containing<ClassA>();
var assemblyB = FindAssembly.Containing<ClassB>();
// Act
Action act = () => assemblyA.Should().Reference(assemblyB);
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_an_assembly_is_referenced_it_should_allow_chaining()
{
// Arrange
var assemblyA = FindAssembly.Containing<ClassA>();
var assemblyB = FindAssembly.Containing<ClassB>();
// Act
Action act = () => assemblyA.Should().Reference(assemblyB)
.And.NotBeNull();
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_an_assembly_is_not_referenced_and_should_reference_is_asserted_it_should_fail()
{
// Arrange
var assemblyA = FindAssembly.Containing<ClassA>();
var assemblyB = FindAssembly.Containing<ClassB>();
// Act
Action act = () => assemblyB.Should().Reference(assemblyA);
// Assert
act.Should().Throw<XunitException>();
}
[Fact]
public void When_subject_is_null_reference_should_fail()
{
// Arrange
Assembly assemblyA = null;
Assembly assemblyB = FindAssembly.Containing<ClassB>();
// Act
Action act = () => assemblyA.Should().Reference(assemblyB, "we want to test the failure {0}", "message");
// Assert
act.Should().Throw<XunitException>()
.WithMessage(
"Expected assembly to reference assembly \"AssemblyB\" *failure message*, but assemblyA is <null>.");
}
[Fact]
public void When_an_assembly_is_referencing_null_it_should_throw()
{
// Arrange
var assemblyA = FindAssembly.Containing<ClassA>();
// Act
Action act = () => assemblyA.Should().Reference(null);
// Assert
act.Should().ThrowExactly<ArgumentNullException>()
.WithParameterName("assembly");
}
}
| Reference |
csharp | unoplatform__uno | src/Uno.UI.RuntimeTests/MUX/Microsoft_UI_Xaml_Controls/Repeater/Common/Mocks/MockStackLayout.cs | {
"start": 315,
"end": 1011
} | partial class ____ : StackLayout
{
public Func<Size, VirtualizingLayoutContext, Size> MeasureLayoutFunc { get; set; }
public Func<Size, VirtualizingLayoutContext, Size> ArrangeLayoutFunc { get; set; }
public new void InvalidateMeasure()
{
base.InvalidateMeasure();
}
protected internal override Size MeasureOverride(VirtualizingLayoutContext context, Size availableSize)
{
return MeasureLayoutFunc != null ? MeasureLayoutFunc(availableSize, context) : default(Size);
}
protected internal override Size ArrangeOverride(VirtualizingLayoutContext context, Size finalSize)
{
return ArrangeLayoutFunc != null ? ArrangeLayoutFunc(finalSize, context) : default(Size);
}
}
| MockStackLayout |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/Query/AdHocJsonQueryTestBase.cs | {
"start": 18738,
"end": 18948
} | public class ____
{
public int Id { get; set; }
public MyJsonEntity Reference { get; set; }
public List<MyJsonEntity> Collection { get; set; }
}
| MyEntity |
csharp | dotnetcore__WTM | src/WalkingTec.Mvvm.Core/Support/ListItem.cs | {
"start": 1214,
"end": 1578
} | public class ____: ComboSelectListItem
{
public bool Expended { get; set; }
public string Url { get; set; }
public string Tag { get; set; }
public string Id { get; set; }
public bool Leaf => Children == null || Children.Count() == 0;
public List<TreeSelectListItem> Children { get; set; }
}
}
| TreeSelectListItem |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Controls/CalendarView/CalendarView_Partial.cs | {
"start": 837,
"end": 92012
} | public partial class ____ : Control
{
private const string UIA_FLIPVIEW_PREVIOUS = "UIA_FLIPVIEW_PREVIOUS";
private const string UIA_FLIPVIEW_NEXT = "UIA_FLIPVIEW_NEXT";
private const char RTL_CHARACTER_CODE = '\x8207';
TrackableDateCollection m_tpSelectedDates;
Button m_tpHeaderButton;
Button m_tpPreviousButton;
Button m_tpNextButton;
Grid m_tpViewsGrid;
Calendar m_tpCalendar;
DateTimeFormatter m_tpMonthYearFormatter;
DateTimeFormatter m_tpYearFormatter;
CalendarViewGeneratorHost m_tpMonthViewItemHost;
CalendarViewGeneratorHost m_tpYearViewItemHost;
CalendarViewGeneratorHost m_tpDecadeViewItemHost;
ScrollViewer m_tpMonthViewScrollViewer;
ScrollViewer m_tpYearViewScrollViewer;
ScrollViewer m_tpDecadeViewScrollViewer;
// we define last displayed date by following:
// 1. if the last displayed item is visible, the date of last displayed item
// 2. if last focused item is not visible, we use the first_visible_inscope_date
// 3. when an item gets focused, we use the date of the focused item.
//
// the default last displayed date will be determined by following:
// 1. display Date if it is requested, if it is not requested, then
// 2. Today, if Today is not in given min/max range, then
// 3. the closest date to Today (i.e. the coerced date of Today)
internal DateTime m_lastDisplayedDate;
DateTime m_today;
// m_minDate and m_maxDate are effective min/max dates, which could be different
// than the values return from get_MinDate/get_MaxDate.
// because developer could set a minDate or maxDate that doesn't exist in
// current calendarsystem. (e.g. UmAlQuraCalendar doesn't have 1/1/2099).
DateTime m_maxDate;
DateTime m_minDate;
// the weekday of mindate.
DayOfWeek m_weekDayOfMinDate;
CalendarViewTemplateSettings m_tpTemplateSettings;
RoutedEventHandler m_epHeaderButtonClickHandler;
RoutedEventHandler m_epPreviousButtonClickHandler;
RoutedEventHandler m_epNextButtonClickHandler;
KeyEventHandler m_epMonthViewScrollViewerKeyDownEventHandler;
KeyEventHandler m_epYearViewScrollViewerKeyDownEventHandler;
KeyEventHandler m_epDecadeViewScrollViewerKeyDownEventHandler;
const int s_minNumberOfWeeks = 2;
const int s_maxNumberOfWeeks = 8;
const int s_defaultNumberOfWeeks = 6;
const int s_numberOfDaysInWeek = 7;
int m_colsInYearDecadeView; // default value is 4
int m_rowsInYearDecadeView; // default value is 4
// if we decide to have a different startIndex in YearView or DecadeView, we should make a corresponding change at CalendarViewItemAutomationPeer::get_ColumnImpl
// in MonthView, because we can set the DayOfWeek property, the first item is not always start from the first positon inside the Panel
int m_monthViewStartIndex;
// dayOfWeekNames stores abbreviated names of each day of the week. dayOfWeekNamesFull stores the full name to be read aloud by accessibility.
List<string> m_dayOfWeekNames = new List<string>();
List<string> m_dayOfWeekNamesFull = new List<string>();
IEnumerable<string> m_tpCalendarLanguages;
VectorChangedEventHandler<DateTimeOffset> m_epSelectedDatesChangedHandler;
// the keydown event args from CalendarItem.
WeakReference<KeyRoutedEventArgs> m_wrKeyDownEventArgsFromCalendarItem = new WeakReference<KeyRoutedEventArgs>(default);
// the focus state we need to set on the calendaritem after we change the display mode.
FocusState m_focusStateAfterDisplayModeChanged;
DateComparer m_dateComparer;
//
// Automation fields
//
// When Narrator gives focus to a day item, we expect it to read the month header
// (assuming the focus used to be outside or on a day item at a different month).
// During this focus transition, Narrator expects to be able to query the previous peer (if any).
// So we need to keep track of the current and previous month header peers.
CalendarViewHeaderAutomationPeer m_currentHeaderPeer;
CalendarViewHeaderAutomationPeer m_previousHeaderPeer;
// when mindate or maxdate changed, we set this flag
bool m_dateSourceChanged;
// when calendar identifier changed, we set this flag
bool m_calendarChanged;
bool m_itemHostsConnected;
bool m_areDirectManipulationStateChangeHandlersHooked;
// this flag indicts the change of SelectedDates comes from internal or external.
bool m_isSelectedDatesChangingInternally;
// when true we need to move focus to a calendaritem after we change the display mode.
bool m_focusItemAfterDisplayModeChanged;
bool m_isMultipleEraCalendar;
bool m_isSetDisplayDateRequested;
bool m_areYearDecadeViewDimensionsSet;
// After navigationbutton clicked, the head text doesn't change immediately. so we use this flag to tell if the update text is from navigation button
bool m_isNavigationButtonClicked;
public CalendarView()
{
// Ctor from core\elements\CalendarView.cpp
//m_pFocusBorderBrush = null;
//m_pSelectedHoverBorderBrush = null;
//m_pSelectedPressedBorderBrush = null;
//m_pSelectedBorderBrush = null;
//m_pHoverBorderBrush = null;
//m_pPressedBorderBrush = null;
//m_pCalendarItemBorderBrush = null;
//m_pOutOfScopeBackground = null;
//m_pCalendarItemBackground = null;
//m_pPressedForeground = null;
//m_pTodayForeground = null;
//m_pBlackoutForeground = null;
//m_pSelectedForeground = null;
//m_pOutOfScopeForeground = null;
//m_pCalendarItemForeground = null;
//m_pDayItemFontFamily = /*null;*/ "XamlAutoFontFamily";
m_pDisabledForeground = Resources[c_strDisabledForegroundStorage] as Brush;
m_pTodaySelectedInnerBorderBrush = Resources[c_strTodaySelectedInnerBorderBrushStorage] as Brush;
m_pTodayHoverBorderBrush = Resources[c_strTodayHoverBorderBrushStorage] as Brush;
m_pTodayPressedBorderBrush = Resources[c_strTodayPressedBorderBrushStorage] as Brush;
//m_pTodayBackground = Resources[c_strTodayBackgroundStorage] as Brush;
m_pTodayBlackoutBackground = Resources[c_strTodayBlackoutBackgroundStorage] as Brush;
//m_dayItemFontSize = 20.0f;
//m_dayItemFontStyle = FontStyle.Normal;
//m_dayItemFontWeight = FontWeights.Normal;
//m_todayFontWeight = FontWeights.SemiBold;
//m_pFirstOfMonthLabelFontFamily = /*null;*/ "XamlAutoFontFamily";
//m_firstOfMonthLabelFontSize = 12.0f;
//m_firstOfMonthLabelFontStyle = FontStyle.Normal;
//m_firstOfMonthLabelFontWeight = FontWeights.Normal;
//m_pMonthYearItemFontFamily = /*null;*/ "XamlAutoFontFamily";
//m_monthYearItemFontSize = 20.0f;
//m_monthYearItemFontStyle = FontStyle.Normal;
//m_monthYearItemFontWeight = FontWeights.Normal;
//m_pFirstOfYearDecadeLabelFontFamily = /*null;*/ "XamlAutoFontFamily";
//m_firstOfYearDecadeLabelFontSize = 12.0f;
//m_firstOfYearDecadeLabelFontStyle = FontStyle.Normal;
//m_firstOfYearDecadeLabelFontWeight = FontWeights.Normal;
//m_horizontalDayItemAlignment = HorizontalAlignment.Center;
//m_verticalDayItemAlignment = VerticalAlignment.Center;
//m_horizontalFirstOfMonthLabelAlignment = HorizontalAlignment.Center;
//m_verticalFirstOfMonthLabelAlignment = VerticalAlignment.Top;
//m_calendarItemBorderThickness = default;
// Ctor from lib\CalendarView_Partial.cpp
m_dateSourceChanged = true;
m_calendarChanged = false;
m_itemHostsConnected = false;
m_areYearDecadeViewDimensionsSet = false;
m_colsInYearDecadeView = 4;
m_rowsInYearDecadeView = 4;
m_monthViewStartIndex = 0;
m_weekDayOfMinDate = DayOfWeek.Sunday;
m_isSelectedDatesChangingInternally = false;
m_focusItemAfterDisplayModeChanged = false;
m_focusStateAfterDisplayModeChanged = FocusState.Programmatic;
m_isMultipleEraCalendar = false;
m_areDirectManipulationStateChangeHandlersHooked = false;
m_isSetDisplayDateRequested = true; // by default there is a displayDate request, which is m_lastDisplayedDate
m_isNavigationButtonClicked = false;
m_today = default;
m_maxDate = default;
m_minDate = default;
m_lastDisplayedDate = default;
PrepareState();
DefaultStyleKey = typeof(CalendarView);
#if __WASM__
IsMeasureDirtyPathDisabled = true;
#endif
}
~CalendarView()
{
//DetachButtonClickedEvents();
//m_tpSelectedDates.VectorChanged -= m_epSelectedDatesChangedHandler;
//DetachScrollViewerKeyDownEvents();
if (m_tpSelectedDates is { } selectedDates)
{
((TrackableDateCollection)selectedDates).SetCollectionChangingCallback(null);
}
}
// UNO SPECIFIC
private protected override void OnLoaded()
{
base.OnLoaded();
AttachButtonClickedEvents();
AttachScrollViewerKeyDownEvents();
}
// UNO SPECIFIC
private protected override void OnUnloaded()
{
base.OnUnloaded();
DetachButtonClickedEvents();
DetachScrollViewerKeyDownEvents();
}
private void PrepareState()
{
//base.PrepareState();
{
m_dateComparer = new DateComparer();
TrackableDateCollection spSelectedDates;
spSelectedDates = new TrackableDateCollection();
m_epSelectedDatesChangedHandler ??= new VectorChangedEventHandler<DateTimeOffset>((pSender, pArgs) => OnSelectedDatesChanged(pSender, pArgs));
spSelectedDates.VectorChanged += m_epSelectedDatesChangedHandler;
spSelectedDates.SetCollectionChangingCallback(
(TrackableDateCollection.CollectionChanging action, DateTimeOffset addingDate) =>
{
OnSelectedDatesChanging(action, addingDate);
});
m_tpSelectedDates = spSelectedDates;
SelectedDates = spSelectedDates;
}
{
CalendarViewGeneratorMonthViewHost spMonthViewItemHost;
CalendarViewGeneratorYearViewHost spYearViewItemHost;
CalendarViewGeneratorDecadeViewHost spDecadeViewItemHost;
spMonthViewItemHost = new CalendarViewGeneratorMonthViewHost();
m_tpMonthViewItemHost = spMonthViewItemHost;
m_tpMonthViewItemHost.Owner = this;
spYearViewItemHost = new CalendarViewGeneratorYearViewHost();
m_tpYearViewItemHost = spYearViewItemHost;
m_tpYearViewItemHost.Owner = this;
spDecadeViewItemHost = new CalendarViewGeneratorDecadeViewHost();
m_tpDecadeViewItemHost = spDecadeViewItemHost;
m_tpDecadeViewItemHost.Owner = this;
}
{
CreateCalendarLanguages();
CreateCalendarAndMonthYearFormatter();
}
{
CalendarViewTemplateSettings spTemplateSettings;
spTemplateSettings = new CalendarViewTemplateSettings();
spTemplateSettings.HasMoreViews = true;
TemplateSettings = spTemplateSettings;
m_tpTemplateSettings = spTemplateSettings;
}
}
// UNO Specific: Default values are set in DP declaration
//// Override the GetDefaultValue method to return the default values
//// for Hub dependency properties.
//private static void GetDefaultValue2(
// DependencyProperty pDP,
// out object pValue)
//{
// if (pDP == CalendarView.CalendarIdentifierProperty)
// {
// pValue = "GregorianCalendar";
// }
// else if (pDP == CalendarView.NumberOfWeeksInViewProperty)
// {
// pValue = s_defaultNumberOfWeeks;
// }
// else
// {
// base.GetDefaultValue2(pDP, out pValue);
// }
//}
// Basically these Alignment properties only affect Arrange, but in CalendarView
// the item size and Panel size are also affected when we change the property from
// stretch to unstretch, or vice versa. In these cases we need to invalidate panels' measure.
private void OnAlignmentChanged(DependencyPropertyChangedEventArgs args)
{
//uint oldAlignment = 0;
//uint newAlignment = 0;
bool isOldStretched = false;
bool isNewStretched = false;
//oldAlignment = (uint)args.OldValue;
//newAlignment = (uint)args.NewValue;
switch (args.Property)
{
case DependencyProperty Control_HorizontalContentAlignment when Control_HorizontalContentAlignment == Control.HorizontalContentAlignmentProperty:
case DependencyProperty FrameworkElement_HorizontalAlignment when FrameworkElement_HorizontalAlignment == FrameworkElement.HorizontalAlignmentProperty:
isOldStretched = (HorizontalAlignment)(args.OldValue) == HorizontalAlignment.Stretch;
isNewStretched = (HorizontalAlignment)(args.NewValue) == HorizontalAlignment.Stretch;
break;
case DependencyProperty Control_VerticalContentAlignment when Control_VerticalContentAlignment == Control.VerticalContentAlignmentProperty:
case DependencyProperty FrameworkElement_VerticalAlignment when FrameworkElement_VerticalAlignment == FrameworkElement.VerticalAlignmentProperty:
isOldStretched = (VerticalAlignment)(args.OldValue) == VerticalAlignment.Stretch;
isNewStretched = (VerticalAlignment)(args.NewValue) == VerticalAlignment.Stretch;
break;
default:
global::System.Diagnostics.Debug.Assert(false);
break;
}
if (isOldStretched != isNewStretched)
{
ForeachHost((CalendarViewGeneratorHost pHost) =>
{
var pPanel = pHost.Panel;
if (pPanel is { })
{
pPanel.InvalidateMeasure();
}
return;
});
}
return;
}
// Handle the custom property changed event and call the OnPropertyChanged methods.
internal override void OnPropertyChanged2(
DependencyPropertyChangedEventArgs args)
{
base.OnPropertyChanged2(args);
switch (args.Property)
{
case DependencyProperty Control_HorizontalContentAlignmentProperty when Control_HorizontalContentAlignmentProperty == Control.HorizontalContentAlignmentProperty:
case DependencyProperty Control_VerticalContentAlignmentProperty when Control_VerticalContentAlignmentProperty == Control.VerticalContentAlignmentProperty:
case DependencyProperty FrameworkElement_HorizontalAlignmentProperty when FrameworkElement_HorizontalAlignmentProperty == FrameworkElement.HorizontalAlignmentProperty:
case DependencyProperty FrameworkElement_VerticalAlignmentProperty when FrameworkElement_VerticalAlignmentProperty == FrameworkElement.VerticalAlignmentProperty:
OnAlignmentChanged(args);
break;
case DependencyProperty CalendarView_MinDateProperty when CalendarView_MinDateProperty == CalendarView.MinDateProperty:
case DependencyProperty CalendarView_MaxDateProperty when CalendarView_MaxDateProperty == CalendarView.MaxDateProperty:
m_dateSourceChanged = true;
InvalidateMeasure();
break;
case DependencyProperty FrameworkElement_LanguageProperty when FrameworkElement_LanguageProperty == FrameworkElement.LanguageProperty:
// Globlization.Calendar doesn't support changing languages, so when languages changed,
// we have to create a new Globalization.Calendar, and also we'll update the date source so
// the change of languages can take effect on the existing items.
CreateCalendarLanguages();
// fall through
goto fall_through_1;
case DependencyProperty CalendarView_CalendarIdentifierProperty when CalendarView_CalendarIdentifierProperty == CalendarView.CalendarIdentifierProperty:
fall_through_1:
m_calendarChanged = true;
m_dateSourceChanged = true; //calendarid changed, even if the mindate or maxdate is not changed we still need to regenerate all calendar items.
InvalidateMeasure();
break;
case DependencyProperty CalendarView_NumberOfWeeksInViewProperty when CalendarView_NumberOfWeeksInViewProperty == CalendarView.NumberOfWeeksInViewProperty:
{
int rows = 0;
rows = (int)args.NewValue;
if (rows < s_minNumberOfWeeks || rows > s_maxNumberOfWeeks)
{
throw new ArgumentOutOfRangeException("ERROR_CALENDAR_NUMBER_OF_WEEKS_OUTOFRANGE");
}
if (m_tpMonthViewItemHost.Panel is { })
{
m_tpMonthViewItemHost.Panel.SetSuggestedDimension(s_numberOfDaysInWeek, rows);
}
}
break;
case DependencyProperty CalendarView_DayOfWeekFormatProperty when CalendarView_DayOfWeekFormatProperty == CalendarView.DayOfWeekFormatProperty:
FormatWeekDayNames();
// fall through
goto fall_through_2;
case DependencyProperty CalendarView_FirstDayOfWeekProperty when CalendarView_FirstDayOfWeekProperty == CalendarView.FirstDayOfWeekProperty:
fall_through_2:
UpdateWeekDayNames();
break;
case DependencyProperty CalendarView_SelectionModeProperty when CalendarView_SelectionModeProperty == CalendarView.SelectionModeProperty:
OnSelectionModeChanged();
break;
case DependencyProperty CalendarView_IsOutOfScopeEnabledProperty when CalendarView_IsOutOfScopeEnabledProperty == CalendarView.IsOutOfScopeEnabledProperty:
OnIsOutOfScopePropertyChanged();
break;
case DependencyProperty CalendarView_DisplayModeProperty when CalendarView_DisplayModeProperty == CalendarView.DisplayModeProperty:
{
CalendarViewDisplayMode oldDisplayMode = 0;
CalendarViewDisplayMode newDisplayMode = 0;
oldDisplayMode = (CalendarViewDisplayMode)args.OldValue;
newDisplayMode = (CalendarViewDisplayMode)args.NewValue;
OnDisplayModeChanged(
(CalendarViewDisplayMode)(oldDisplayMode),
(CalendarViewDisplayMode)(newDisplayMode)
);
}
break;
case DependencyProperty CalendarView_IsTodayHighlightedProperty when CalendarView_IsTodayHighlightedProperty == CalendarView.IsTodayHighlightedProperty:
OnIsTodayHighlightedPropertyChanged();
break;
case DependencyProperty CalendarView_IsGroupLabelVisibleProperty when CalendarView_IsGroupLabelVisibleProperty == CalendarView.IsGroupLabelVisibleProperty:
OnIsLabelVisibleChanged();
break;
// To reduce memory usage, we move lots font/brush properties from CalendarViewItem to CalendarView,
// the cost is we can't benefit from property system to invalidate measure/render automatically.
// However changing these font/brush properties is not a frequent scenario. So once they are changed
// we'll manually update the items.
// Basically we should only update those affected items (e.g. when PressedBackground changed, we should only update
// the item which is being pressed) but to make the code simple we'll update all realized item, unless
// we see performance issue here.
// Border brushes and Background (they are chromes) will take effect in next Render walk.
case DependencyProperty CalendarView_FocusBorderBrushProperty when CalendarView_FocusBorderBrushProperty == CalendarView.FocusBorderBrushProperty:
case DependencyProperty CalendarView_SelectedHoverBorderBrushProperty when CalendarView_SelectedHoverBorderBrushProperty == CalendarView.SelectedHoverBorderBrushProperty:
case DependencyProperty CalendarView_SelectedPressedBorderBrushProperty when CalendarView_SelectedPressedBorderBrushProperty == CalendarView.SelectedPressedBorderBrushProperty:
case DependencyProperty CalendarView_SelectedBorderBrushProperty when CalendarView_SelectedBorderBrushProperty == CalendarView.SelectedBorderBrushProperty:
case DependencyProperty CalendarView_HoverBorderBrushProperty when CalendarView_HoverBorderBrushProperty == CalendarView.HoverBorderBrushProperty:
case DependencyProperty CalendarView_PressedBorderBrushProperty when CalendarView_PressedBorderBrushProperty == CalendarView.PressedBorderBrushProperty:
case DependencyProperty CalendarView_CalendarItemBorderBrushProperty when CalendarView_CalendarItemBorderBrushProperty == CalendarView.CalendarItemBorderBrushProperty:
case DependencyProperty CalendarView_OutOfScopeBackgroundProperty when CalendarView_OutOfScopeBackgroundProperty == CalendarView.OutOfScopeBackgroundProperty:
case DependencyProperty CalendarView_CalendarItemBackgroundProperty when CalendarView_CalendarItemBackgroundProperty == CalendarView.CalendarItemBackgroundProperty:
ForeachHost(pHost =>
{
ForeachChildInPanel(
pHost.Panel,
pItem =>
{
pItem.InvalidateRender();
});
});
break;
// Foreground will take effect immediately
case DependencyProperty CalendarView_PressedForegroundProperty when CalendarView_PressedForegroundProperty == CalendarView.PressedForegroundProperty:
case DependencyProperty CalendarView_TodayForegroundProperty when CalendarView_TodayForegroundProperty == CalendarView.TodayForegroundProperty:
case DependencyProperty CalendarView_BlackoutForegroundProperty when CalendarView_BlackoutForegroundProperty == CalendarView.BlackoutForegroundProperty:
case DependencyProperty CalendarView_SelectedForegroundProperty when CalendarView_SelectedForegroundProperty == CalendarView.SelectedForegroundProperty:
case DependencyProperty CalendarView_OutOfScopeForegroundProperty when CalendarView_OutOfScopeForegroundProperty == CalendarView.OutOfScopeForegroundProperty:
case DependencyProperty CalendarView_CalendarItemForegroundProperty when CalendarView_CalendarItemForegroundProperty == CalendarView.CalendarItemForegroundProperty:
ForeachHost(pHost =>
{
ForeachChildInPanel(
pHost.Panel,
pItem =>
{
pItem.UpdateTextBlockForeground();
});
});
break;
case DependencyProperty CalendarView_TodayFontWeightProperty when CalendarView_TodayFontWeightProperty == CalendarView.TodayFontWeightProperty:
{
ForeachHost(pHost =>
{
var pPanel = pHost.Panel;
if (pPanel is { })
{
int indexOfToday = -1;
indexOfToday = pHost.CalculateOffsetFromMinDate(m_today);
if (indexOfToday != -1)
{
DependencyObject spChildAsIDO;
CalendarViewBaseItem spChildAsI;
spChildAsIDO = pPanel.ContainerFromIndex(indexOfToday);
spChildAsI = spChildAsIDO as CalendarViewBaseItem;
// today item is realized already, we need to update the state here.
// if today item is not realized yet, we'll update the state when today item is being prepared.
if (spChildAsI is { })
{
CalendarViewBaseItem spChild;
spChild = (CalendarViewBaseItem)spChildAsI;
spChild.UpdateTextBlockFontProperties();
}
}
}
});
break;
}
// Font properties for DayItem (affect measure and arrange)
case DependencyProperty CalendarView_DayItemFontFamilyProperty when CalendarView_DayItemFontFamilyProperty == CalendarView.DayItemFontFamilyProperty:
case DependencyProperty CalendarView_DayItemFontSizeProperty when CalendarView_DayItemFontSizeProperty == CalendarView.DayItemFontSizeProperty:
case DependencyProperty CalendarView_DayItemFontStyleProperty when CalendarView_DayItemFontStyleProperty == CalendarView.DayItemFontStyleProperty:
case DependencyProperty CalendarView_DayItemFontWeightProperty when CalendarView_DayItemFontWeightProperty == CalendarView.DayItemFontWeightProperty:
{
// if these DayItem properties changed, we need to re-determine the
// biggest dayitem in monthPanel, which will invalidate monthpanel's measure
var pMonthPanel = m_tpMonthViewItemHost.Panel;
if (pMonthPanel is { })
{
pMonthPanel.SetNeedsToDetermineBiggestItemSize();
}
}
goto fall_through_3;
// Font properties for MonthLabel (they won't affect measure or arrange)
case DependencyProperty CalendarView_FirstOfMonthLabelFontFamilyProperty when CalendarView_FirstOfMonthLabelFontFamilyProperty == CalendarView.FirstOfMonthLabelFontFamilyProperty:
case DependencyProperty CalendarView_FirstOfMonthLabelFontSizeProperty when CalendarView_FirstOfMonthLabelFontSizeProperty == CalendarView.FirstOfMonthLabelFontSizeProperty:
case DependencyProperty CalendarView_FirstOfMonthLabelFontStyleProperty when CalendarView_FirstOfMonthLabelFontStyleProperty == CalendarView.FirstOfMonthLabelFontStyleProperty:
case DependencyProperty CalendarView_FirstOfMonthLabelFontWeightProperty when CalendarView_FirstOfMonthLabelFontWeightProperty == CalendarView.FirstOfMonthLabelFontWeightProperty:
fall_through_3:
ForeachChildInPanel(
m_tpMonthViewItemHost.Panel,
pItem =>
{
pItem.UpdateTextBlockFontProperties();
});
break;
// Font properties for MonthYearItem
case DependencyProperty CalendarView_MonthYearItemFontFamilyProperty when CalendarView_MonthYearItemFontFamilyProperty == CalendarView.MonthYearItemFontFamilyProperty:
case DependencyProperty CalendarView_MonthYearItemFontSizeProperty when CalendarView_MonthYearItemFontSizeProperty == CalendarView.MonthYearItemFontSizeProperty:
case DependencyProperty CalendarView_MonthYearItemFontStyleProperty when CalendarView_MonthYearItemFontStyleProperty == CalendarView.MonthYearItemFontStyleProperty:
case DependencyProperty CalendarView_MonthYearItemFontWeightProperty when CalendarView_MonthYearItemFontWeightProperty == CalendarView.MonthYearItemFontWeightProperty:
{
// these properties will affect MonthItem and YearItem's size, so we should
// tell their panels to re-determine the biggest item size.
CalendarPanel[] pPanels = new[]{
m_tpYearViewItemHost.Panel, m_tpDecadeViewItemHost.Panel
};
;
for (var i = 0; i < pPanels.Length; ++i)
{
if (pPanels[i] is { })
{
pPanels[i].SetNeedsToDetermineBiggestItemSize();
}
}
}
// fall through
goto fall_through_4;
case DependencyProperty CalendarView_FirstOfYearDecadeLabelFontFamilyProperty when CalendarView_FirstOfYearDecadeLabelFontFamilyProperty == CalendarView.FirstOfYearDecadeLabelFontFamilyProperty:
case DependencyProperty CalendarView_FirstOfYearDecadeLabelFontSizeProperty when CalendarView_FirstOfYearDecadeLabelFontSizeProperty == CalendarView.FirstOfYearDecadeLabelFontSizeProperty:
case DependencyProperty CalendarView_FirstOfYearDecadeLabelFontStyleProperty when CalendarView_FirstOfYearDecadeLabelFontStyleProperty == CalendarView.FirstOfYearDecadeLabelFontStyleProperty:
case DependencyProperty CalendarView_FirstOfYearDecadeLabelFontWeightProperty when CalendarView_FirstOfYearDecadeLabelFontWeightProperty == CalendarView.FirstOfYearDecadeLabelFontWeightProperty:
fall_through_4:
{
CalendarPanel[] pPanels = new[]
{
m_tpYearViewItemHost.Panel, m_tpDecadeViewItemHost.Panel
}
;
for (var i = 0; i < pPanels.Length; ++i)
{
ForeachChildInPanel(pPanels[i],
(CalendarViewBaseItem pItem) =>
{
pItem.UpdateTextBlockFontProperties();
});
}
break;
}
// Alignments affect DayItem only
case DependencyProperty CalendarView_HorizontalDayItemAlignmentProperty when CalendarView_HorizontalDayItemAlignmentProperty == CalendarView.HorizontalDayItemAlignmentProperty:
case DependencyProperty CalendarView_VerticalDayItemAlignmentProperty when CalendarView_VerticalDayItemAlignmentProperty == CalendarView.VerticalDayItemAlignmentProperty:
case DependencyProperty CalendarView_HorizontalFirstOfMonthLabelAlignmentProperty when CalendarView_HorizontalFirstOfMonthLabelAlignmentProperty == CalendarView.HorizontalFirstOfMonthLabelAlignmentProperty:
case DependencyProperty CalendarView_VerticalFirstOfMonthLabelAlignmentProperty when CalendarView_VerticalFirstOfMonthLabelAlignmentProperty == CalendarView.VerticalFirstOfMonthLabelAlignmentProperty:
ForeachChildInPanel(
m_tpMonthViewItemHost.Panel,
pItem =>
{
pItem.UpdateTextBlockAlignments();
});
break;
// border thickness affects measure (and arrange)
case DependencyProperty CalendarView_CalendarItemBorderThicknessProperty when CalendarView_CalendarItemBorderThicknessProperty == CalendarView.CalendarItemBorderThicknessProperty:
ForeachHost(pHost =>
{
ForeachChildInPanel(
pHost.Panel,
pItem =>
{
pItem.InvalidateMeasure();
});
});
break;
// Dayitem style changed, update style for all existing day items.
case DependencyProperty CalendarView_CalendarViewDayItemStyleProperty when CalendarView_CalendarViewDayItemStyleProperty == CalendarView.CalendarViewDayItemStyleProperty:
{
Style spStyle;
spStyle = args.NewValue as Style;
var pMonthPanel = m_tpMonthViewItemHost.Panel;
ForeachChildInPanel(
pMonthPanel,
pItem =>
{
SetDayItemStyle(pItem, spStyle);
});
// Some properties could affect dayitem size (e.g. Dayitem font properties, dayitem size),
// when anyone of them is changed, we need to re-determine the biggest day item.
// This is not a frequent scenario so we can simply set below flag and invalidate measure.
if (pMonthPanel is { })
{
pMonthPanel.SetNeedsToDetermineBiggestItemSize();
}
break;
}
}
}
protected override void OnApplyTemplate()
{
CalendarPanel spMonthViewPanel;
CalendarPanel spYearViewPanel;
CalendarPanel spDecadeViewPanel;
Button spHeaderButton;
Button spPreviousButton;
Button spNextButton;
Grid spViewsGrid;
ScrollViewer spMonthViewScrollViewer;
ScrollViewer spYearViewScrollViewer;
ScrollViewer spDecadeViewScrollViewer;
string strAutomationName;
DetachVisibleIndicesUpdatedEvents();
//DetachButtonClickedEvents();
DetachScrollViewerFocusEngagedEvents();
DetachScrollViewerKeyDownEvents();
// This will clean up the panels and clear the children
DisconnectItemHosts();
if (m_areDirectManipulationStateChangeHandlersHooked)
{
m_areDirectManipulationStateChangeHandlersHooked = false;
ForeachHost(pHost =>
{
var pScrollViewer = pHost.ScrollViewer;
if (pScrollViewer is { })
{
pScrollViewer.SetDirectManipulationStateChangeHandler(null);
}
});
}
ForeachHost(pHost =>
{
pHost.Panel = null;
pHost.ScrollViewer = null;
});
m_tpHeaderButton = null;
m_tpPreviousButton = null;
m_tpNextButton = null;
m_tpViewsGrid = null;
base.OnApplyTemplate();
spMonthViewPanel = this.GetTemplateChild<CalendarPanel>("MonthViewPanel");
spYearViewPanel = this.GetTemplateChild<CalendarPanel>("YearViewPanel");
spDecadeViewPanel = this.GetTemplateChild<CalendarPanel>("DecadeViewPanel");
m_tpMonthViewItemHost.Panel = spMonthViewPanel;
m_tpYearViewItemHost.Panel = spYearViewPanel;
m_tpDecadeViewItemHost.Panel = spDecadeViewPanel;
if (spMonthViewPanel is { })
{
CalendarPanel pPanel = (CalendarPanel)spMonthViewPanel;
int numberOfWeeksInView = 0;
// MonthView panel is the only primary panel (and never changes)
pPanel.PanelType = CalendarPanelType.Primary;
numberOfWeeksInView = NumberOfWeeksInView;
pPanel.SetSuggestedDimension(s_numberOfDaysInWeek, numberOfWeeksInView);
pPanel.Orientation = Orientation.Horizontal;
}
if (spYearViewPanel is { })
{
CalendarPanel pPanel = (CalendarPanel)spYearViewPanel;
// YearView panel is a Secondary_SelfAdaptive panel by default
if (!m_areYearDecadeViewDimensionsSet)
{
pPanel.PanelType = CalendarPanelType.Secondary_SelfAdaptive;
}
pPanel.SetSuggestedDimension(m_colsInYearDecadeView, m_rowsInYearDecadeView);
pPanel.Orientation = Orientation.Horizontal;
}
if (spDecadeViewPanel is { })
{
CalendarPanel pPanel = (CalendarPanel)spDecadeViewPanel;
// DecadeView panel is a Secondary_SelfAdaptive panel by default
if (!m_areYearDecadeViewDimensionsSet)
{
pPanel.PanelType = CalendarPanelType.Secondary_SelfAdaptive;
}
pPanel.SetSuggestedDimension(m_colsInYearDecadeView, m_rowsInYearDecadeView);
pPanel.Orientation = Orientation.Horizontal;
}
spHeaderButton = this.GetTemplateChild<Button>("HeaderButton");
spPreviousButton = this.GetTemplateChild<Button>("PreviousButton");
spNextButton = this.GetTemplateChild<Button>("NextButton");
if (spPreviousButton is { })
{
strAutomationName = AutomationProperties.GetName((Button)spPreviousButton);
if (strAutomationName == null)
{
// USe the same resource string as for FlipView's Previous Button.
strAutomationName = DXamlCore.GetCurrentNoCreate().GetLocalizedResourceString(UIA_FLIPVIEW_PREVIOUS);
AutomationProperties.SetName((Button)spPreviousButton, strAutomationName);
}
}
if (spNextButton is { })
{
strAutomationName = AutomationProperties.GetName((Button)spNextButton);
if (strAutomationName == null)
{
// USe the same resource string as for FlipView's Next Button.
strAutomationName = DXamlCore.GetCurrentNoCreate().GetLocalizedResourceString(UIA_FLIPVIEW_NEXT);
AutomationProperties.SetName((Button)spNextButton, strAutomationName);
}
}
m_tpHeaderButton = spHeaderButton;
m_tpPreviousButton = spPreviousButton;
m_tpNextButton = spNextButton;
spViewsGrid = this.GetTemplateChild<Grid>("Views");
m_tpViewsGrid = spViewsGrid;
spMonthViewScrollViewer = this.GetTemplateChild<ScrollViewer>("MonthViewScrollViewer");
spYearViewScrollViewer = this.GetTemplateChild<ScrollViewer>("YearViewScrollViewer");
spDecadeViewScrollViewer = this.GetTemplateChild<ScrollViewer>("DecadeViewScrollViewer");
m_tpMonthViewItemHost.ScrollViewer = spMonthViewScrollViewer;
m_tpYearViewItemHost.ScrollViewer = spYearViewScrollViewer;
m_tpDecadeViewItemHost.ScrollViewer = spDecadeViewScrollViewer;
// Setting custom CalendarScrollViewerAutomationPeer for these scrollviewers to be the default one.
if (spMonthViewScrollViewer is { })
{
((ScrollViewer)spMonthViewScrollViewer).AutomationPeerFactoryIndex = () => new CalendarScrollViewerAutomationPeer(spMonthViewScrollViewer);
m_tpMonthViewScrollViewer = spMonthViewScrollViewer;
}
if (spYearViewScrollViewer is { })
{
((ScrollViewer)spYearViewScrollViewer).AutomationPeerFactoryIndex = () => new CalendarScrollViewerAutomationPeer(spYearViewScrollViewer);
m_tpYearViewScrollViewer = spYearViewScrollViewer;
}
if (spDecadeViewScrollViewer is { })
{
((ScrollViewer)spDecadeViewScrollViewer).AutomationPeerFactoryIndex = () => new CalendarScrollViewerAutomationPeer(spDecadeViewScrollViewer);
m_tpDecadeViewScrollViewer = spDecadeViewScrollViewer;
}
global::System.Diagnostics.Debug.Assert(!m_areDirectManipulationStateChangeHandlersHooked);
ForeachHost(pHost =>
{
var pScrollViewer = pHost.ScrollViewer;
if (pScrollViewer is { })
{
pScrollViewer.TemplatedParentHandlesScrolling = true;
pScrollViewer.SetDirectManipulationStateChangeHandler(pHost);
pScrollViewer.m_templatedParentHandlesMouseButton = true;
}
});
m_areDirectManipulationStateChangeHandlersHooked = true;
AttachVisibleIndicesUpdatedEvents();
AttachButtonClickedEvents();
AttachScrollViewerKeyDownEvents();
// This will connect the new panels with ItemHosts
RegisterItemHosts();
AttachScrollViewerFocusEngagedEvents();
UpdateVisualState(false /*bUseTransitions*/);
UpdateFlowDirectionForView();
}
// Change to the correct visual state for the control.
private protected override void ChangeVisualState(
bool bUseTransitions)
{
CalendarViewDisplayMode mode = CalendarViewDisplayMode.Month;
//bool bIgnored = false;
mode = DisplayMode;
if (mode == CalendarViewDisplayMode.Month)
{
GoToState(bUseTransitions, "Month");
}
else if (mode == CalendarViewDisplayMode.Year)
{
GoToState(bUseTransitions, "Year");
}
else //if (mode == CalendarViewDisplayMode.Decade)
{
GoToState(bUseTransitions, "Decade");
}
bool isEnabled = false;
isEnabled = IsEnabled;
// Common States Group
if (!isEnabled)
{
GoToState(bUseTransitions, "Disabled");
}
else
{
GoToState(bUseTransitions, "Normal");
}
return;
}
// Primary panel will determine CalendarView's size, when Primary Panel's desired size changed, we need
// to update the template settings so other template parts can update their size correspondingly.
internal void OnPrimaryPanelDesiredSizeChanged(CalendarViewGeneratorHost pHost)
{
// monthpanel is the only primary panel
global::System.Diagnostics.Debug.Assert(pHost == m_tpMonthViewItemHost);
var pMonthViewPanel = pHost.Panel;
global::System.Diagnostics.Debug.Assert(pMonthViewPanel is { });
Size desiredViewportSize = default;
desiredViewportSize = pMonthViewPanel.GetDesiredViewportSize();
CalendarViewTemplateSettings pTemplateSettingsConcrete = ((CalendarViewTemplateSettings)m_tpTemplateSettings);
pTemplateSettingsConcrete.MinViewWidth = desiredViewportSize.Width;
return;
}
protected override Size MeasureOverride(
Size availableSize)
{
Size pDesired = default;
if (m_calendarChanged)
{
m_calendarChanged = false;
CreateCalendarAndMonthYearFormatter();
FormatWeekDayNames();
UpdateFlowDirectionForView();
}
if (m_dateSourceChanged)
{
// m_minDate or m_maxDate changed, we need to refresh all dates
// so we should disconnect itemhosts and update the itemhosts, then register them again.
m_dateSourceChanged = false;
DisconnectItemHosts();
RefreshItemHosts();
InitializeIndexCorrectionTableIfNeeded(); // for some timezones, we need to figure out where are the gaps (missing days)
RegisterItemHosts();
UpdateWeekDayNames();
}
pDesired = base.MeasureOverride(availableSize);
return pDesired;
}
protected override Size ArrangeOverride(
Size finalSize)
{
Size returnValue = default;
returnValue = base.ArrangeOverride(finalSize);
if (m_tpViewsGrid is { })
{
// When switching views, the up-scaled view needs to be clipped by the original size.
double viewsHeight = 0.0;
double viewsWidth = 0.0;
CalendarViewTemplateSettings pTemplateSettingsConcrete = ((CalendarViewTemplateSettings)m_tpTemplateSettings);
viewsHeight = ((Grid)m_tpViewsGrid).ActualHeight;
viewsWidth = ((Grid)m_tpViewsGrid).ActualWidth;
Rect clipRect = new Rect(0.0, 0.0, (float)(viewsWidth), (float)(viewsHeight));
pTemplateSettingsConcrete.ClipRect = clipRect;
// ScaleTransform.CenterX and CenterY
pTemplateSettingsConcrete.CenterX = (viewsWidth / 2);
pTemplateSettingsConcrete.CenterY = (viewsHeight / 2);
}
if (m_isSetDisplayDateRequested)
{
// m_lastDisplayedDate is already coerced and adjusted, time to process this request and clear the flag.
m_isSetDisplayDateRequested = false;
SetDisplayDateInternal(m_lastDisplayedDate);
}
return returnValue;
}
// create a list of languages to construct Globalization.Calendar and Globalization.DateTimeFormatter.
// here we prepend CalendarView.Language to ApplicationLanguage.Languages as the new list.
private void CreateCalendarLanguages()
{
string strLanguage;
IEnumerable<string> spCalendarLanguages;
strLanguage = Language;
spCalendarLanguages = CreateCalendarLanguagesStatic(strLanguage);
m_tpCalendarLanguages = spCalendarLanguages;
return;
}
// helper method to prepend a string into a collection of string.
/*static */
internal static IEnumerable<string> CreateCalendarLanguagesStatic(
string language)
{
IEnumerable<string> ppLanguages = default;
IReadOnlyList<string> spApplicationLanguages;
IList<string> spCalendarLanguages;
int size = 0;
spApplicationLanguages = ApplicationLanguages.Languages;
spCalendarLanguages = new List<string>();
if (language is { }) // UNO
{
spCalendarLanguages.Add(language);
}
size = spApplicationLanguages.Count;
for (uint i = 0; i < size; ++i)
{
string strApplicationLanguage;
strApplicationLanguage = spApplicationLanguages[(int)i];
spCalendarLanguages.Add(strApplicationLanguage);
}
ppLanguages = spCalendarLanguages;
return ppLanguages;
}
private void CreateCalendarAndMonthYearFormatter()
{
//CalendarFactory spCalendarFactory;
Calendar spCalendar;
string strClock = "24HourClock"; // it doesn't matter if it is 24 or 12 hour clock
string strCalendarIdentifier;
strCalendarIdentifier = CalendarIdentifier;
//Create the calendar
//ctl.GetActivationFactory(
// RuntimeClass_Windows_Globalization_Calendar,
// &spCalendarFactory);
//spCalendarFactory.CreateCalendar(
// m_tpCalendarLanguages,
// strCalendarIdentifier,
// strClock,
// spCalendar);
spCalendar = new Calendar(m_tpCalendarLanguages, strCalendarIdentifier, strClock);
m_tpCalendar = spCalendar;
// create a Calendar clone (have the same timezone, same calendarlanguages and identifier) for DateComparer and SelectedDates
// changing the date on the Calendar in DateComparer will not affect the Calendar in CalendarView.
m_dateComparer.SetCalendarForComparison(spCalendar);
((TrackableDateCollection)m_tpSelectedDates).SetCalendarForComparison(spCalendar);
// in multiple era calendar, we'll have different (slower) logic to handle the decade scope.
{
int firstEra = 0;
int lastEra = 0;
firstEra = m_tpCalendar.FirstEra;
lastEra = m_tpCalendar.LastEra;
m_isMultipleEraCalendar = firstEra != lastEra;
}
m_tpCalendar.SetToNow();
m_today = m_tpCalendar.GetDateTime();
// default displaydate is today
if (m_lastDisplayedDate.UniversalTime == 0)
{
m_lastDisplayedDate = m_today;
}
ForeachHost(pHost =>
{
var pPanel = pHost.Panel;
if (pPanel is { })
{
pPanel.SetNeedsToDetermineBiggestItemSize();
}
pHost.ResetPossibleItemStrings();
return;
});
{
DateTimeFormatter spFormatter;
// month year formatter needs to be updated when calendar is updated (languages or calendar identifier changed).
CreateDateTimeFormatter("month year", out spFormatter);
m_tpMonthYearFormatter = spFormatter;
// year formatter also needs to be updated when the calendar is updated.
CreateDateTimeFormatter("year", out spFormatter);
m_tpYearFormatter = spFormatter;
}
return;
}
private void DisconnectItemHosts()
{
if (m_itemHostsConnected)
{
m_itemHostsConnected = false;
ForeachHost((CalendarViewGeneratorHost pHost) =>
{
var pPanel = pHost.Panel;
if (pPanel is { })
{
pPanel.DisconnectItemsHost();
}
return;
});
}
return;
}
private void RegisterItemHosts()
{
global::System.Diagnostics.Debug.Assert(!m_itemHostsConnected);
m_itemHostsConnected = true;
ForeachHost((CalendarViewGeneratorHost pHost) =>
{
var pPanel = pHost.Panel;
if (pPanel is { })
{
pPanel.RegisterItemsHost(pHost);
}
return;
});
return;
}
private void RefreshItemHosts()
{
DateTime minDate;
DateTime maxDate;
minDate = MinDate;
maxDate = MaxDate;
// making sure our MinDate and MaxDate are supported by the current Calendar
{
DateTime tempDate;
m_tpCalendar.SetToMin();
tempDate = m_tpCalendar.GetDateTime();
m_minDate.UniversalTime = Math.Max(minDate.UniversalTime, tempDate.UniversalTime);
m_tpCalendar.SetToMax();
tempDate = m_tpCalendar.GetDateTime();
m_maxDate.UniversalTime = Math.Min(maxDate.UniversalTime, tempDate.UniversalTime);
}
if (m_dateComparer.LessThan(m_maxDate, m_minDate))
{
//ErrorHelper.OriginateErrorUsingResourceID(E_FAIL, ERROR_CALENDAR_INVALID_MIN_MAX_DATE);
throw new InvalidOperationException("ERROR_CALENDAR_INVALID_MIN_MAX_DATE");
}
CoerceDate(ref m_lastDisplayedDate);
m_tpCalendar.SetDateTime(m_minDate);
m_weekDayOfMinDate = m_tpCalendar.DayOfWeek;
ForeachHost((CalendarViewGeneratorHost pHost) =>
{
pHost.ResetScope(); // reset the scope data to force update the scope and header text.
pHost.ComputeSize();
return;
});
return;
}
private void AttachVisibleIndicesUpdatedEvents()
{
ForeachHost((CalendarViewGeneratorHost pHost) =>
{
pHost.AttachVisibleIndicesUpdatedEvent();
});
}
private void DetachVisibleIndicesUpdatedEvents()
{
ForeachHost((CalendarViewGeneratorHost pHost) =>
{
pHost.DetachVisibleIndicesUpdatedEvent();
});
}
// attach FocusEngaged event for all three hosts
private void AttachScrollViewerFocusEngagedEvents()
{
ForeachHost((CalendarViewGeneratorHost pHost) =>
{
pHost.AttachScrollViewerFocusEngagedEvent();
});
}
// detach FocusEngaged event for all three hosts
private void DetachScrollViewerFocusEngagedEvents()
{
ForeachHost((CalendarViewGeneratorHost pHost) =>
{
pHost.DetachScrollViewerFocusEngagedEvent();
});
}
private void AttachButtonClickedEvents()
{
DetachButtonClickedEvents(); // Uno
if (m_tpHeaderButton is { })
{
m_epHeaderButtonClickHandler ??= new RoutedEventHandler((object pSender, RoutedEventArgs pArgs) =>
{
OnHeaderButtonClicked();
});
((Button)m_tpHeaderButton).Click += m_epHeaderButtonClickHandler;
}
if (m_tpPreviousButton is { })
{
m_epPreviousButtonClickHandler ??= new RoutedEventHandler(
(object pSender, RoutedEventArgs pArgs) =>
{
OnNavigationButtonClicked(false /*forward*/);
});
((Button)m_tpPreviousButton).Click += m_epPreviousButtonClickHandler;
}
if (m_tpNextButton is { })
{
m_epNextButtonClickHandler ??= new RoutedEventHandler(
(object pSender, RoutedEventArgs pArgs) =>
{
OnNavigationButtonClicked(true /*forward*/);
});
((Button)m_tpNextButton).Click += m_epNextButtonClickHandler;
}
}
private void DetachButtonClickedEvents()
{
if (m_epHeaderButtonClickHandler is { } && m_tpHeaderButton is { })
{
m_tpHeaderButton.Click -= m_epHeaderButtonClickHandler;
m_epHeaderButtonClickHandler = null;
}
if (m_epPreviousButtonClickHandler is { } && m_tpPreviousButton is { })
{
m_tpPreviousButton.Click -= m_epPreviousButtonClickHandler;
m_epPreviousButtonClickHandler = null;
}
if (m_epNextButtonClickHandler is { } && m_tpNextButton is { })
{
m_tpNextButton.Click -= m_epNextButtonClickHandler;
m_epNextButtonClickHandler = null;
}
}
private void AttachScrollViewerKeyDownEvents()
{
DetachScrollViewerKeyDownEvents(); // UNO
//Engagement now prevents events from bubbling from an engaged element. Before we relied on the bubbling behavior to
//receive the KeyDown events from the ScrollViewer in the CalendarView. Now instead we have to handle the ScrollViewer's
//On Key Down. To prevent handling the same OnKeyDown twice we only call into OnKeyDown if the ScrollViewer is engaged,
//if it isn't it will bubble up the event.
if (m_tpMonthViewScrollViewer is { })
{
m_epMonthViewScrollViewerKeyDownEventHandler ??= new KeyEventHandler(
(object pSender, KeyRoutedEventArgs pArgs) =>
{
bool isEngaged = false;
isEngaged = ((ScrollViewer)m_tpMonthViewScrollViewer).IsFocusEngaged;
if (isEngaged)
{
OnKeyDown(pArgs);
}
return;
});
m_tpMonthViewScrollViewer.KeyDown += m_epMonthViewScrollViewerKeyDownEventHandler;
}
if (m_tpYearViewScrollViewer is { })
{
m_epYearViewScrollViewerKeyDownEventHandler ??= new KeyEventHandler(
(object pSender, KeyRoutedEventArgs pArgs) =>
{
bool isEngaged = false;
isEngaged = ((ScrollViewer)m_tpYearViewScrollViewer).IsFocusEngaged;
if (isEngaged)
{
OnKeyDown(pArgs);
}
return;
});
m_tpYearViewScrollViewer.KeyDown += m_epYearViewScrollViewerKeyDownEventHandler;
}
if (m_tpDecadeViewScrollViewer is { })
{
m_epDecadeViewScrollViewerKeyDownEventHandler ??= new KeyEventHandler(
(object pSender, KeyRoutedEventArgs pArgs) =>
{
bool isEngaged = false;
isEngaged = ((ScrollViewer)m_tpDecadeViewScrollViewer).IsFocusEngaged;
if (isEngaged)
{
OnKeyDown(pArgs);
}
return;
});
m_tpDecadeViewScrollViewer.KeyDown += m_epDecadeViewScrollViewerKeyDownEventHandler;
}
return;
}
private void DetachScrollViewerKeyDownEvents()
{
if (m_epMonthViewScrollViewerKeyDownEventHandler is { } && m_tpMonthViewScrollViewer is { })
{
m_tpMonthViewScrollViewer.KeyDown -= m_epMonthViewScrollViewerKeyDownEventHandler;
m_epMonthViewScrollViewerKeyDownEventHandler = null;
}
if (m_epYearViewScrollViewerKeyDownEventHandler is { } && m_tpYearViewScrollViewer is { })
{
m_tpYearViewScrollViewer.KeyDown -= m_epYearViewScrollViewerKeyDownEventHandler;
m_epYearViewScrollViewerKeyDownEventHandler = null;
}
if (m_epDecadeViewScrollViewerKeyDownEventHandler is { } && m_tpDecadeViewScrollViewer is { })
{
m_tpDecadeViewScrollViewer.KeyDown -= m_epDecadeViewScrollViewerKeyDownEventHandler;
m_epDecadeViewScrollViewerKeyDownEventHandler = null;
}
return;
}
private void UpdateHeaderText(bool withAnimation)
{
CalendarViewGeneratorHost spHost;
GetActiveGeneratorHost(out spHost);
CalendarViewTemplateSettings pTemplateSettingsConcrete = ((CalendarViewTemplateSettings)m_tpTemplateSettings);
pTemplateSettingsConcrete.HeaderText = spHost.GetHeaderTextOfCurrentScope();
if (withAnimation)
{
bool bIgnored = false;
// play animation on the HeaderText after view mode changed.
bIgnored = GoToState(true, "ViewChanged");
bIgnored = GoToState(true, "ViewChanging");
}
// If UpdateText is because navigation button is clicked, make narrator to say the header.
if (m_isNavigationButtonClicked)
{
m_isNavigationButtonClicked = false;
RaiseAutomationNotificationAfterNavigationButtonClicked();
}
return;
}
// disable the button if we don't have more content
private void UpdateNavigationButtonStates()
{
CalendarViewGeneratorHost spHost;
GetActiveGeneratorHost(out spHost);
var pCalendarPanel = spHost.Panel;
if (pCalendarPanel is { })
{
int firstVisibleIndex = 0;
int lastVisibleIndex = 0;
uint size = 0;
CalendarViewTemplateSettings pTemplateSettingsConcrete = ((CalendarViewTemplateSettings)m_tpTemplateSettings);
firstVisibleIndex = pCalendarPanel.FirstVisibleIndexBase;
lastVisibleIndex = pCalendarPanel.LastVisibleIndexBase;
size = spHost.Size();
pTemplateSettingsConcrete.HasMoreContentBefore = firstVisibleIndex > 0;
pTemplateSettingsConcrete.HasMoreContentAfter = lastVisibleIndex + 1 < (int)(size);
}
return;
}
private void OnHeaderButtonClicked()
{
CalendarViewDisplayMode mode = CalendarViewDisplayMode.Month;
mode = DisplayMode;
if (mode != CalendarViewDisplayMode.Decade)
{
if (mode == CalendarViewDisplayMode.Month)
{
mode = CalendarViewDisplayMode.Year;
}
else // if (mode == CalendarViewDisplayMode.Year)
{
mode = CalendarViewDisplayMode.Decade;
}
DisplayMode = mode;
}
else
{
global::System.Diagnostics.Debug.Assert(false, "header button should be disabled already in decade view mode.");
}
}
private void RaiseAutomationNotificationAfterNavigationButtonClicked()
{
if (m_tpHeaderButton is { })
{
string automationName;
automationName = AutomationProperties.GetName(((Button)m_tpHeaderButton));
if (automationName is null)
{
//FrameworkElement.GetStringFromObject(m_tpHeaderButton, automationName);
automationName = m_tpHeaderButton.Content?.ToString();
}
if (automationName is { })
{
AutomationPeer calendarViewAutomationPeer;
calendarViewAutomationPeer = GetAutomationPeer();
if (calendarViewAutomationPeer is { })
{
// Two possible solution: RaisePropertyChangedEvent or RaiseNotificationEvent. If Raise PropertyChangedEvent each time when head is changing,
// it would be overkilling since header is already included in other automation event. More information about RaiseNotificationEvent, please
// refer to https://docs.microsoft.com/en-us/uwp/api/windows.ui.automation.peers.automationnotificationkind
calendarViewAutomationPeer.RaiseNotificationEvent(
AutomationNotificationKind.ActionCompleted,
AutomationNotificationProcessing.MostRecent,
automationName,
"CalenderViewNavigationButtonCompleted");
}
}
}
return;
}
private void OnNavigationButtonClicked(bool forward)
{
CalendarViewGeneratorHost spHost;
GetActiveGeneratorHost(out spHost);
var pCalendarPanel = spHost.Panel;
if (pCalendarPanel is { })
{
bool canPanelShowFullScope = false;
int firstVisibleIndex = 0;
DependencyObject spChildAsIDO;
CalendarViewBaseItem spChildAsI;
CalendarViewBaseItem spChild;
DateTime dateOfFirstVisibleItem = default;
DateTime targetDate = default;
CanPanelShowFullScope(spHost, out canPanelShowFullScope);
firstVisibleIndex = pCalendarPanel.FirstVisibleIndexBase;
spChildAsIDO = pCalendarPanel.ContainerFromIndex(firstVisibleIndex);
spChildAsI = spChildAsIDO as CalendarViewBaseItem;
if (spChildAsI is { })
{
try
{
spChild = ((CalendarViewBaseItem)spChildAsI);
dateOfFirstVisibleItem = spChild.DateBase;
if (canPanelShowFullScope)
{
// if Panel can show a full scope, we navigate by a scope.
spHost.GetFirstDateOfNextScope(dateOfFirstVisibleItem, forward, out targetDate);
}
else
{
// if Panel can't show a full scope, we navigate by a page, so we don't skip items.
int cols = 0;
int rows = 0;
rows = pCalendarPanel.Rows;
cols = pCalendarPanel.Cols;
int numberOfItemsPerPage = cols * rows;
int distance = forward ? numberOfItemsPerPage : -numberOfItemsPerPage;
targetDate = dateOfFirstVisibleItem;
spHost.AddUnits(targetDate, distance);
#if DEBUG && false
if (SUCCEEDED(hr))
{
// targetDate should be still in valid range.
var temp = targetDate;
CoerceDate(temp);
global::System.Diagnostics.Debug.Assert(temp.UniversalTime == targetDate.UniversalTime);
}
#endif
}
}
catch (Exception)
{
// if we crossed the boundaries when we compute the target date, we use the hard limit.
targetDate = forward ? m_maxDate : m_minDate;
}
ScrollToDateWithAnimation(spHost, targetDate);
// After navigation button is clicked, header text is not updated immediately. ScrollToDateWithAnimation is the first step,
// OnVisibleIndicesUpdated and UpdateHeaderText would be in another UI message processing loop.
// This flag is to identify that the HeaderText update is from navigation button.
m_isNavigationButtonClicked = true;
}
}
return;
}
// change the dimensions of YearView and DecadeView.
// API name to be reviewed.
public void SetYearDecadeDisplayDimensions(int columns, int rows)
{
global::System.Diagnostics.Debug.Assert(columns > 0 && rows > 0);
// note once this is set, developer can't unset it
m_areYearDecadeViewDimensionsSet = true;
m_colsInYearDecadeView = columns;
m_rowsInYearDecadeView = rows;
var pYearPanel = m_tpYearViewItemHost.Panel;
if (pYearPanel is { })
{
// Panel type is no longer Secondary_SelfAdaptive
pYearPanel.PanelType = CalendarPanelType.Secondary;
pYearPanel.SetSuggestedDimension(columns, rows);
}
var pDecadePanel = m_tpDecadeViewItemHost.Panel;
if (pDecadePanel is { })
{
// Panel type is no longer Secondary_SelfAdaptive
pDecadePanel.PanelType = CalendarPanelType.Secondary;
pDecadePanel.SetSuggestedDimension(columns, rows);
}
return;
}
// When we call SetDisplayDate, we'll check if the current view is big enough to hold a whole scope.
// If yes then we'll bring the first date in this scope into view,
// otherwise bring the display date into view then the display date will be on first visible line.
//
// note: when panel can't show a fullscope, we might be still able to show the first day and the requested date
// in the viewport (e.g. NumberOfWeeks is 4, we request to display 1/9/2000, in this case 1/1/2000 and 1/9/2000 can
// be visible at the same time). To consider this case we need more logic, we can fix later when needed.
private void BringDisplayDateintoView(
CalendarViewGeneratorHost pHost)
{
bool canPanelShowFullScope = false;
DateTime dateToBringintoView;
CanPanelShowFullScope(pHost, out canPanelShowFullScope);
if (canPanelShowFullScope)
{
m_tpCalendar.SetDateTime(m_lastDisplayedDate);
pHost.AdjustToFirstUnitInThisScope(out dateToBringintoView);
CoerceDate(ref dateToBringintoView);
}
else
{
dateToBringintoView = m_lastDisplayedDate;
}
ScrollToDate(pHost, dateToBringintoView);
return;
}
// bring a item into view
// This function will scroll to the target item immediately,
// when target is far away from realized window, we'll not see unrealized area.
private void ScrollToDate(
CalendarViewGeneratorHost pHost,
DateTime date)
{
int index = 0;
index = pHost.CalculateOffsetFromMinDate(date);
global::System.Diagnostics.Debug.Assert(index >= 0);
global::System.Diagnostics.Debug.Assert(pHost.Panel is { });
pHost.Panel.ScrollItemIntoView(
index,
ScrollIntoViewAlignment.Leading,
0.0 /* offset */,
true /* forceSynchronous */);
}
// Bring a item into view with animation.
// This function will scroll to the target item with DManip animation so
// if target is not realized yet, we might see unrealized area.
// This only gets called in NavigationButton clicked event where
// the target should be less than one page away from visible window.
private void ScrollToDateWithAnimation(
CalendarViewGeneratorHost pHost,
DateTime date)
{
var pScrollViewer = pHost.ScrollViewer;
if (pScrollViewer is { })
{
int index = 0;
int firstVisibleIndex = 0;
int cols = 0;
DependencyObject spFirstVisibleItemAsI;
CalendarViewBaseItem spFirstVisibleItem;
object spVerticalOffset;
double? spVerticalOffsetReference;
bool handled = false;
var pCalendarPanel = pHost.Panel;
// The target item may be not realized yet so we can't get
// the offset from virtualization information.
// However all items have the same size so we could deduce the target's
// exact offset from the current realized item, e.g. the firstVisibleItem
// 1. compute the target index.
index = pHost.CalculateOffsetFromMinDate(date);
global::System.Diagnostics.Debug.Assert(index >= 0);
cols = pCalendarPanel.Cols;
global::System.Diagnostics.Debug.Assert(cols > 0);
// cols should not be 0 at this point. If it is, perhaps
// the calendar view has not been fully brought up yet.
// If cols is 0, we do not want to bring the process down though.
// Doing a no-op for the scroll to date in this case.
if (cols > 0)
{
// 2. find the first visible index.
firstVisibleIndex = pCalendarPanel.FirstVisibleIndex;
spFirstVisibleItemAsI = pCalendarPanel.ContainerFromIndex(firstVisibleIndex);
spFirstVisibleItem = (CalendarViewBaseItem)spFirstVisibleItemAsI;
global::System.Diagnostics.Debug.Assert(spFirstVisibleItem.GetVirtualizationInformation() is { });
// 3. based on the first visible item's bounds, compute the target item's offset
var bounds = spFirstVisibleItem.GetVirtualizationInformation().Bounds;
var verticalDistance = (index - firstVisibleIndex) / cols;
// if target item is before the first visible index and is not the first in that row, we should substract 1 from the distance
// because -6 / 7 = 0 (we expect -1).
if ((index - firstVisibleIndex) % cols != 0 && index <= firstVisibleIndex)
{
--verticalDistance;
}
// there are some corner cases in Japanese calendar where the target date and current date are in the same row.
// e.g. Showa 64 only has 1 month, in year view, January Show64 and January Heisei are in the same row.
// When we try to scroll down from showa64 to Heisei1 in year view, verticalDistance would be 0 since those 2 years are in the same row.
// We do ++verticalDistance here to point to March of Heise 1 in the next row, otherwise we'll get stuck in the first row and navigate down button would stop working.
else if (verticalDistance == 0 && index > firstVisibleIndex)
{
++verticalDistance;
}
var offset = bounds.Y + verticalDistance * bounds.Height;
// 4. scroll to target item's offset (with animation)
spVerticalOffset = offset;
spVerticalOffsetReference = offset; // (double)spVerticalOffset;
handled = pScrollViewer.ChangeView(
null /*horizontalOffset*/,
spVerticalOffsetReference,
null /*zoomFactor*/,
false /*disableAnimation*/);
global::System.Diagnostics.Debug.Assert(handled);
}
}
return;
}
public void SetDisplayDate(global::System.DateTimeOffset date)
{
// Uno specific: Force conversion from System.DateTimeOffset to Windows.Foundation.DateTime
// Don't use date parameter except in this line.
DateTime wfDate = date;
// if m_dateSourceChanged is true, this means we might changed m_minDate or m_maxDate
// so we should not call CoerceDate until next measure pass, by then the m_minDate and
// m_maxDate are updated.
if (!m_dateSourceChanged)
{
CoerceDate(ref wfDate);
SetDisplayDateInternal(wfDate);
}
else
{
// given that m_dateSourceChanged is true, we'll have a new layout pass soon.
// we're going to honer the display date request in that layout pass.
// note: there is an issue to call ScrollItemintoView in MCBP's measure pass
// the workaround is call it in Arrange pass or later. here we'll call it
// in the arrange pass.
m_isSetDisplayDateRequested = true;
m_lastDisplayedDate = wfDate;
}
return;
}
private void SetDisplayDateInternal(DateTime date)
{
CalendarViewGeneratorHost spHost;
GetActiveGeneratorHost(out spHost);
m_lastDisplayedDate = date;
if (spHost.Panel is { })
{
// note if panel is not loaded yet (i.e. we call SetDisplayDate before Panel is loaded,
// below call will fail silently. This is not a problem because
// we'll call this again in panel loaded event.
BringDisplayDateintoView(spHost);
}
}
internal void CoerceDate(ref DateTime date)
{
// we should not call CoerceDate when m_dateSourceChanged is true, because
// m_dateSourceChanged being true means the current m_minDate or m_maxDate is
// out of dated.
global::System.Diagnostics.Debug.Assert(!m_dateSourceChanged);
if (m_dateComparer.LessThan(date, m_minDate))
{
date = m_minDate;
}
if (m_dateComparer.LessThan(m_maxDate, date))
{
date = m_maxDate;
}
}
internal void OnVisibleIndicesUpdated(
CalendarViewGeneratorHost pHost)
{
int firstVisibleIndex = 0;
int lastVisibleIndex = 0;
DependencyObject spTempChildAsIDO;
CalendarViewBaseItem spTempChildAsI;
DateTime firstDate = default;
DateTime lastDate = default;
bool isScopeChanged = false;
int startIndex = 0;
int numberOfItemsInCol;
var pCalendarPanel = pHost.Panel;
global::System.Diagnostics.Debug.Assert(pCalendarPanel is { });
// We explicitly call UpdateLayout in OnDisplayModeChanged, this will ocassionaly make CalendarPanelType invalid,
// which causes CalendarPanel to skip the row&col calculations.
// If CalendarPanelType is invalid, just skip the current update
// since this method will be called again in later layout passes.
if (pCalendarPanel.PanelType != CalendarPanelType.Invalid)
{
startIndex = pCalendarPanel.StartIndex;
numberOfItemsInCol = pCalendarPanel.Cols;
global::System.Diagnostics.Debug.Assert(startIndex < numberOfItemsInCol);
firstVisibleIndex = pCalendarPanel.FirstVisibleIndexBase;
lastVisibleIndex = pCalendarPanel.LastVisibleIndexBase;
spTempChildAsIDO = pCalendarPanel.ContainerFromIndex(firstVisibleIndex);
spTempChildAsI = (CalendarViewBaseItem)spTempChildAsIDO;
firstDate = ((CalendarViewBaseItem)spTempChildAsI).DateBase;
spTempChildAsIDO = pCalendarPanel.ContainerFromIndex(lastVisibleIndex);
spTempChildAsI = (CalendarViewBaseItem)spTempChildAsIDO;
lastDate = ((CalendarViewBaseItem)spTempChildAsI).DateBase;
//now determine the current scope based on this date.
pHost.UpdateScope(firstDate, lastDate, out isScopeChanged);
if (isScopeChanged)
{
#if __ANDROID__
// .InvalidateMeasure() bug https://github.com/unoplatform/uno/issues/6236
DispatcherQueue.TryEnqueue(() => UpdateHeaderText(false /*withAnimation*/));
#else
UpdateHeaderText(false /*withAnimation*/);
#endif
}
// everytime visible indices changed, we need to update
// navigationButtons' states.
UpdateNavigationButtonStates();
UpdateItemsScopeState(
pHost,
true, /*ignoreWhenIsOutOfScopeDisabled*/
true /*ignoreInDirectManipulation*/);
}
}
// to achieve best visual effect we define that items are in OutOfScope state only when:
// 1. IsOutOfScopeEnabled is true, and
// 2. item is in Visible window and it is not in current scope.
// 3. Not in manipulation.
// for all other cases, item is in InScope state.
//
// this function updates the ScopeState for
// 1. all visible items, and
// 2. the items that are not visible but was marked as OutOfScope (because viewport changed)
//
// so we'll call this function when
// 1. IsOutOfScopeEnabled property changed, or
// 2. Visible Indices changed
// 3. Manipulation state changed.
internal void UpdateItemsScopeState(
CalendarViewGeneratorHost pHost,
bool ignoreWhenIsOutOfScopeDisabled,
bool ignoreInDirectManipulation)
{
var pCalendarPanel = pHost.Panel;
if (pCalendarPanel is null || pCalendarPanel.DesiredSize == default)
{
// it is possible that we change IsOutOfScopeEnabled property before CalendarView enters visual tree.
return;
}
bool isOutOfScopeEnabled = false;
isOutOfScopeEnabled = IsOutOfScopeEnabled;
if (ignoreWhenIsOutOfScopeDisabled && !isOutOfScopeEnabled)
{
return;
}
bool isInDirectManipulation = pHost.ScrollViewer is { } && pHost.ScrollViewer.IsInDirectManipulation;
if (ignoreInDirectManipulation && isInDirectManipulation)
{
return;
}
bool canHaveOutOfScopeState = isOutOfScopeEnabled && !isInDirectManipulation;
int firstIndex = -1;
int lastIndex = -1;
DependencyObject spChildAsIDO;
CalendarViewBaseItem spChildAsI;
CalendarViewBaseItem spChild;
DateTime date;
firstIndex = pCalendarPanel.FirstVisibleIndex;
lastIndex = pCalendarPanel.LastVisibleIndex;
// given that all items not in visible window have InScope state, so we only want
// to check the visible window, plus the items in last visible window. this way
// we don't need to check against virtualization window.
var lastVisibleIndicesPair = pHost.GetLastVisibleIndicesPairRef();
if (firstIndex != -1 && lastIndex != -1)
{
for (int index = firstIndex; index <= lastIndex; ++index)
{
spChildAsIDO = pCalendarPanel.ContainerFromIndex(index);
spChildAsI = (CalendarViewBaseItem)spChildAsIDO;
spChild = ((CalendarViewBaseItem)spChildAsI);
date = spChild.DateBase;
bool isOutOfScope = m_dateComparer.LessThan(date, pHost.GetMinDateOfCurrentScope()) || m_dateComparer.LessThan(pHost.GetMaxDateOfCurrentScope(), date);
spChild.SetIsOutOfScope(canHaveOutOfScopeState && isOutOfScope);
}
}
// now let's check the items were marked as OutOfScope but now not in Visible window (so they should be marked as InScope)
if (lastVisibleIndicesPair[0] != -1 && lastVisibleIndicesPair[1] != -1)
{
if (lastVisibleIndicesPair[0] < firstIndex)
{
for (int index = lastVisibleIndicesPair[0]; index <= Math.Min(lastVisibleIndicesPair[1], firstIndex - 1); ++index)
{
spChildAsIDO = pCalendarPanel.ContainerFromIndex(index);
spChildAsI = spChildAsIDO as CalendarViewBaseItem;
if (spChildAsI is { })
{
// this item is not in visible window but was marked as OutOfScope before, set it to "InScope" now.
((CalendarViewBaseItem)spChildAsI).SetIsOutOfScope(false);
}
}
}
if (lastVisibleIndicesPair[1] > lastIndex)
{
for (int index = lastVisibleIndicesPair[1]; index >= Math.Max(lastVisibleIndicesPair[0], lastIndex + 1); --index)
{
spChildAsIDO = pCalendarPanel.ContainerFromIndex(index);
spChildAsI = spChildAsIDO as CalendarViewBaseItem;
if (spChildAsI is { })
{
// this item is not in visible window but was marked as OutOfScope before, set it to "InScope" now.
((CalendarViewBaseItem)spChildAsI).SetIsOutOfScope(false);
}
}
}
}
// store the visible indices pair
lastVisibleIndicesPair[0] = firstIndex;
lastVisibleIndicesPair[1] = lastIndex;
return;
}
// this property affects Today in MonthView, ThisMonth in YearView and ThisYear in DecadeView.
private void OnIsTodayHighlightedPropertyChanged()
{
ForeachHost((CalendarViewGeneratorHost pHost) =>
{
var pPanel = pHost.Panel;
if (pPanel is { })
{
int indexOfToday = -1;
indexOfToday = pHost.CalculateOffsetFromMinDate(m_today);
if (indexOfToday != -1)
{
DependencyObject spChildAsIDO;
CalendarViewBaseItem spChildAsI;
spChildAsIDO = pPanel.ContainerFromIndex(indexOfToday);
spChildAsI = spChildAsIDO as CalendarViewBaseItem;
// today item is realized already, we need to update the state here.
// if today item is not realized yet, we'll update the state when today item is being prepared.
if (spChildAsI is { })
{
bool isTodayHighlighted = false;
isTodayHighlighted = IsTodayHighlighted;
((CalendarViewBaseItem)spChildAsI).SetIsToday(isTodayHighlighted);
}
}
}
});
}
private void OnIsOutOfScopePropertyChanged()
{
CalendarViewGeneratorHost spHost;
bool isOutOfScopeEnabled = false;
isOutOfScopeEnabled = IsOutOfScopeEnabled;
// when IsOutOfScopeEnabled property is false, we don't care about scope state (all are inScope),
// so we don't need to hook to ScrollViewer's state change handler.
// when IsOutOfScopeEnabled property is true, we need to do so.
if (m_areDirectManipulationStateChangeHandlersHooked != isOutOfScopeEnabled)
{
m_areDirectManipulationStateChangeHandlersHooked = !m_areDirectManipulationStateChangeHandlersHooked;
ForeachHost((CalendarViewGeneratorHost pHost) =>
{
var pScrollViewer = pHost.ScrollViewer;
if (pScrollViewer is { })
{
pScrollViewer.SetDirectManipulationStateChangeHandler(
isOutOfScopeEnabled ? pHost : null
);
}
return;
});
}
GetActiveGeneratorHost(out spHost);
UpdateItemsScopeState(
spHost,
false, /*ignoreWhenIsOutOfScopeDisabled*/
true /*ignoreInDirectManipulation*/);
return;
}
internal void OnScrollViewerFocusEngaged(
FocusEngagedEventArgs pArgs)
{
CalendarViewGeneratorHost spHost;
GetActiveGeneratorHost(out spHost);
if (spHost is { })
{
bool focused = false;
m_focusItemAfterDisplayModeChanged = false;
FocusEngagedEventArgs spArgs = pArgs;
FocusItemByDate(spHost, m_lastDisplayedDate, m_focusStateAfterDisplayModeChanged, out focused);
spArgs.Handled = focused;
}
return;
}
private void OnDisplayModeChanged(
CalendarViewDisplayMode oldDisplayMode,
CalendarViewDisplayMode newDisplayMode)
{
CalendarViewGeneratorHost spCurrentHost;
CalendarViewGeneratorHost spOldHost;
bool isEngaged = false;
GetGeneratorHost(oldDisplayMode, out spOldHost);
if (spOldHost is { })
{
var pScrollViewer = spOldHost.ScrollViewer;
if (pScrollViewer is { })
{
// if old host is engaged, disengage
isEngaged = pScrollViewer.IsFocusEngaged;
if (isEngaged)
{
pScrollViewer.RemoveFocusEngagement();
}
}
}
UpdateLastDisplayedDate(oldDisplayMode);
UpdateVisualState();
GetGeneratorHost(newDisplayMode, out spCurrentHost);
var pCurrentPanel = spCurrentHost.Panel;
if (pCurrentPanel is { })
{
// if panel is not loaded yet (e.g. the first time we switch to the YearView or DecadeView),
// ScrollItemintoView (called by FocusItemByDate) will not work because ScrollViewer is not
// hooked up yet. Give the panel an extra layout pass to hook up the ScrollViewer.
if (newDisplayMode != CalendarViewDisplayMode.Month)
{
#if HAS_UNO // Uno workaround: UpdateLayout requires XamlRoot to find the root element in our case. #20681
pCurrentPanel.XamlRoot ??= spCurrentHost.ScrollViewer?.XamlRoot;
#endif
pCurrentPanel.UpdateLayout();
}
// If Engaged, make sure that the new scroll viewer is engaged. Note that
// you want to Engage before focusing ItemByDate to land on the correct item.
if (isEngaged)
{
var spScrollViewer = spCurrentHost.ScrollViewer;
if (spScrollViewer is { })
{
// The old ScrollViewer was engaged, engage the new ScrollViewer
//A control must be focused before we can set Engagement on it, attempt to set focus first
bool focused = false;
focused = this.SetFocusedElementWithDirection(spScrollViewer, FocusState.Keyboard, false /*animateIfBringintoView*/, FocusNavigationDirection.None);
if (focused)
{
FocusManager.SetEngagedControl(spScrollViewer);
}
}
}
// If we requested to move focus to item, let's do it.
if (m_focusItemAfterDisplayModeChanged)
{
bool focused = false;
m_focusItemAfterDisplayModeChanged = false;
FocusItemByDate(spCurrentHost, m_lastDisplayedDate, m_focusStateAfterDisplayModeChanged, out focused);
}
else // we only scroll to the focusedDate without moving focus to it
{
BringDisplayDateintoView(spCurrentHost);
}
}
CalendarViewTemplateSettings pTemplateSettingsConcrete = ((CalendarViewTemplateSettings)m_tpTemplateSettings);
pTemplateSettingsConcrete.HasMoreViews = (newDisplayMode != CalendarViewDisplayMode.Decade);
UpdateHeaderText(true /*withAnimation*/);
UpdateNavigationButtonStates();
return;
}
private void UpdateLastDisplayedDate(CalendarViewDisplayMode lastDisplayMode)
{
CalendarViewGeneratorHost spPreviousHost;
GetGeneratorHost(lastDisplayMode, out spPreviousHost);
var pPreviousPanel = spPreviousHost.Panel;
if (pPreviousPanel is { })
{
int firstVisibleIndex = 0;
int lastVisibleIndex = 0;
DateTime firstVisibleDate = default;
DateTime lastVisibleDate = default;
DependencyObject spChildAsIDO;
CalendarViewBaseItem spChildAsI;
firstVisibleIndex = pPreviousPanel.FirstVisibleIndexBase;
lastVisibleIndex = pPreviousPanel.LastVisibleIndexBase;
global::System.Diagnostics.Debug.Assert(firstVisibleIndex != -1 && lastVisibleIndex != -1);
spChildAsIDO = pPreviousPanel.ContainerFromIndex(firstVisibleIndex);
spChildAsI = spChildAsIDO as CalendarViewBaseItem;
firstVisibleDate = ((CalendarViewBaseItem)spChildAsI).DateBase;
spChildAsIDO = pPreviousPanel.ContainerFromIndex(lastVisibleIndex);
spChildAsI = spChildAsIDO as CalendarViewBaseItem;
lastVisibleDate = ((CalendarViewBaseItem)spChildAsI).DateBase;
// check if last displayed Date is visible or not
bool isLastDisplayedDateVisible = false;
int result = 0;
result = spPreviousHost.CompareDate(m_lastDisplayedDate, firstVisibleDate);
if (result >= 0)
{
result = spPreviousHost.CompareDate(m_lastDisplayedDate, lastVisibleDate);
if (result <= 0)
{
isLastDisplayedDateVisible = true;
}
}
if (!isLastDisplayedDateVisible)
{
// if last displayed date is not visible, we use the first_visible_inscope_date as the last displayed date
// first try to use the first_inscope_date
DateTime firstVisibleInscopeDate = spPreviousHost.GetMinDateOfCurrentScope();
// check if first_inscope_date is visible or not
result = spPreviousHost.CompareDate(firstVisibleInscopeDate, firstVisibleDate);
if (result < 0)
{
// the firstInscopeDate is not visible, then we use the firstVisibleDate.
#if DEBUG
{
// in this case firstVisibleDate must be in scope (i.e. it must be less than or equals to the maxDateOfCurrentScope).
int temp = 0;
temp = spPreviousHost.CompareDate(firstVisibleDate, spPreviousHost.GetMaxDateOfCurrentScope());
global::System.Diagnostics.Debug.Assert(temp <= 0);
}
#endif
firstVisibleInscopeDate = firstVisibleDate;
}
// based on the display mode, partially copy the firstVisibleInscopeDate to m_lastDisplayedDate.
CopyDate(
lastDisplayMode,
firstVisibleInscopeDate,
ref m_lastDisplayedDate);
}
}
return;
}
private void OnIsLabelVisibleChanged()
{
// we don't have label text in decade view.
var hosts = new CalendarViewGeneratorHost[2]
{
m_tpMonthViewItemHost, m_tpYearViewItemHost
}
;
bool isLabelVisible = false;
isLabelVisible = IsGroupLabelVisible;
for (uint i = 0; i < hosts.Length; ++i)
{
var pHost = hosts[i];
var pPanel = pHost.Panel;
if (pPanel is { })
{
ForeachChildInPanel(pPanel,
(CalendarViewBaseItem pItem) =>
{
pHost.UpdateLabel(pItem, isLabelVisible);
});
}
}
}
private void CreateDateTimeFormatter(
string format,
out DateTimeFormatter ppDateTimeFormatter)
{
DateTimeFormatter spFormatter;
string strClock = "24HourClock"; // it doesn't matter if it is 24 or 12 hour clock
string strGeographicRegion = "ZZ"; // geographicRegion doesn't really matter as we have no decimal separator or grouping
string strCalendarIdentifier;
strCalendarIdentifier = CalendarIdentifier;
spFormatter = new DateTimeFormatter(format,
m_tpCalendarLanguages,
strGeographicRegion,
strCalendarIdentifier,
strClock);
ppDateTimeFormatter = spFormatter;
}
private void FormatWeekDayNames()
{
if (m_tpMonthViewItemHost.Panel is { })
{
object spDayOfWeekFormat;
bool isUnsetValue = false;
DayOfWeek dayOfWeek = DayOfWeek.Sunday;
DateTimeFormatter spFormatter = default;
spDayOfWeekFormat = ReadLocalValue(DayOfWeekFormatProperty);
isUnsetValue = spDayOfWeekFormat == DependencyProperty.UnsetValue;
m_tpCalendar.SetToNow();
dayOfWeek = m_tpCalendar.DayOfWeek;
// adjust to next sunday.
m_tpCalendar.AddDays((s_numberOfDaysInWeek - (int)dayOfWeek) % s_numberOfDaysInWeek);
m_dayOfWeekNames.Clear();
//m_dayOfWeekNames.reserve(s_numberOfDaysInWeek);
// Fill m_dayOfWeekNamesFull. This will always be the full name of the day regardless of abbreviation used for m_dayOfWeekNames.
m_dayOfWeekNamesFull.Clear();
//m_dayOfWeekNamesFull.reserve(s_numberOfDaysInWeek);
if (!isUnsetValue) // format is set, use this format.
{
string dayOfWeekFormat;
dayOfWeekFormat = DayOfWeekFormat;
// Workaround: we can't bind an unset value to a property.
// Here we'll check if the format is empty or not - because in CalendarDatePicker this property
// is bound to CalendarDatePicker.DayOfWeekFormat which will cause this value is always set.
if (!dayOfWeekFormat.IsNullOrEmpty())
{
CreateDateTimeFormatter(dayOfWeekFormat, out spFormatter);
}
}
for (int i = 0; i < s_numberOfDaysInWeek; ++i)
{
string str;
if (spFormatter is { }) // there is a valid datetimeformatter specified by user, use it
{
DateTime date;
date = m_tpCalendar.GetDateTime();
str = spFormatter.Format(date);
}
else // otherwise use the shortest string formatted by calendar.
{
str = m_tpCalendar.DayOfWeekAsString(
1 /*shortest length*/
);
}
m_dayOfWeekNames.Add(str);
// for automation peer name, we always use the full string.
var @string = m_tpCalendar.DayOfWeekAsFullString();
m_dayOfWeekNamesFull.Add(@string);
m_tpCalendar.AddDays(1);
}
}
}
private void UpdateWeekDayNameAPName(string str, string name)
{
TextBlock spWeekDay;
spWeekDay = this.GetTemplateChild<TextBlock>(str);
AutomationProperties.SetName(((TextBlock)spWeekDay), name);
return;
}
private void UpdateWeekDayNames()
{
var pMonthPanel = m_tpMonthViewItemHost.Panel;
if (pMonthPanel is { })
{
DayOfWeek firstDayOfWeek = DayOfWeek.Sunday;
int index = 0;
CalendarViewTemplateSettings pTemplateSettingsConcrete = ((CalendarViewTemplateSettings)m_tpTemplateSettings);
firstDayOfWeek = FirstDayOfWeek;
if (m_dayOfWeekNames.Empty())
{
FormatWeekDayNames();
}
index = (int)(firstDayOfWeek - DayOfWeek.Sunday);
pTemplateSettingsConcrete.WeekDay1 = (m_dayOfWeekNames[index]);
UpdateWeekDayNameAPName(("WeekDay1"), m_dayOfWeekNamesFull[index]);
index = (index + 1) % s_numberOfDaysInWeek;
pTemplateSettingsConcrete.WeekDay2 = (m_dayOfWeekNames[index]);
UpdateWeekDayNameAPName(("WeekDay2"), m_dayOfWeekNamesFull[index]);
index = (index + 1) % s_numberOfDaysInWeek;
pTemplateSettingsConcrete.WeekDay3 = (m_dayOfWeekNames[index]);
UpdateWeekDayNameAPName(("WeekDay3"), m_dayOfWeekNamesFull[index]);
index = (index + 1) % s_numberOfDaysInWeek;
pTemplateSettingsConcrete.WeekDay4 = (m_dayOfWeekNames[index]);
UpdateWeekDayNameAPName(("WeekDay4"), m_dayOfWeekNamesFull[index]);
index = (index + 1) % s_numberOfDaysInWeek;
pTemplateSettingsConcrete.WeekDay5 = (m_dayOfWeekNames[index]);
UpdateWeekDayNameAPName(("WeekDay5"), m_dayOfWeekNamesFull[index]);
index = (index + 1) % s_numberOfDaysInWeek;
pTemplateSettingsConcrete.WeekDay6 = (m_dayOfWeekNames[index]);
UpdateWeekDayNameAPName(("WeekDay6"), m_dayOfWeekNamesFull[index]);
index = (index + 1) % s_numberOfDaysInWeek;
pTemplateSettingsConcrete.WeekDay7 = (m_dayOfWeekNames[index]);
UpdateWeekDayNameAPName(("WeekDay7"), m_dayOfWeekNamesFull[index]);
m_monthViewStartIndex = (m_weekDayOfMinDate - firstDayOfWeek + s_numberOfDaysInWeek) % s_numberOfDaysInWeek;
global::System.Diagnostics.Debug.Assert(m_monthViewStartIndex >= 0 && m_monthViewStartIndex < s_numberOfDaysInWeek);
pMonthPanel.StartIndex = m_monthViewStartIndex;
}
}
internal void GetActiveGeneratorHost(out CalendarViewGeneratorHost ppHost)
{
CalendarViewDisplayMode mode = CalendarViewDisplayMode.Month;
ppHost = null;
mode = DisplayMode;
GetGeneratorHost(mode, out ppHost);
}
private void GetGeneratorHost(
CalendarViewDisplayMode mode,
out CalendarViewGeneratorHost ppHost)
{
if (mode == CalendarViewDisplayMode.Month)
{
ppHost = m_tpMonthViewItemHost;
}
else if (mode == CalendarViewDisplayMode.Year)
{
ppHost = m_tpYearViewItemHost;
}
else if (mode == CalendarViewDisplayMode.Decade)
{
ppHost = m_tpDecadeViewItemHost;
}
else
{
global::System.Diagnostics.Debug.Assert(false);
throw new InvalidOperationException();
}
}
internal string FormatYearName(DateTime date)
{
var pName = m_tpYearFormatter.Format(date);
return pName;
}
internal string FormatMonthYearName(DateTime date)
{
var pName = m_tpMonthYearFormatter.Format(date);
return pName;
}
// Partially copy date from source to target.
// Only copy the parts we want and keep the remaining part.
// Once the remaining part becomes invalid with the new copied parts,
// we need to adjust the remaining part to the most reasonable value.
// e.g. target: 3/31/2014, source 2/1/2013 and we want to copy month part,
// the target will become 2/31/2013 and we'll adjust the day to 2/28/2013.
private void CopyDate(
CalendarViewDisplayMode displayMode,
DateTime source,
ref DateTime target)
{
bool copyEra = true;
bool copyYear = true;
bool copyMonth = displayMode == CalendarViewDisplayMode.Month ||
displayMode == CalendarViewDisplayMode.Year;
bool copyDay = displayMode == CalendarViewDisplayMode.Month;
if (copyEra && copyYear && copyMonth && copyDay)
{
// copy everything.
target = source;
}
else
{
int era = 0;
int year = 0;
int month = 0;
int day = 0;
m_tpCalendar.SetDateTime(source);
if (copyEra)
{
era = m_tpCalendar.Era;
}
if (copyYear)
{
year = m_tpCalendar.Year;
}
if (copyMonth)
{
month = m_tpCalendar.Month;
}
if (copyDay)
{
day = m_tpCalendar.Day;
}
m_tpCalendar.SetDateTime(target);
if (copyEra)
{
// era is always valid.
//m_tpCalendar.Era = era; --- FIX FOR https://github.com/unoplatform/uno/issues/6160
}
if (copyYear)
{
// year might not be valid.
int first = 0;
int last = 0;
first = m_tpCalendar.FirstYearInThisEra;
last = m_tpCalendar.LastYearInThisEra;
year = Math.Min(last, Math.Max(first, year));
m_tpCalendar.Year = year;
}
if (copyMonth)
{
// month might not be valid.
int first = 0;
int last = 0;
first = m_tpCalendar.FirstMonthInThisYear;
last = m_tpCalendar.LastMonthInThisYear;
month = Math.Min(last, Math.Max(first, month));
m_tpCalendar.Month = month;
}
if (copyDay)
{
// day might not be valid.
int first = 0;
int last = 0;
first = m_tpCalendar.FirstDayInThisMonth;
last = m_tpCalendar.LastDayInThisMonth;
day = Math.Min(last, Math.Max(first, day));
m_tpCalendar.Day = day;
}
target = m_tpCalendar.GetDateTime();
// make sure the target is still in range.
CoerceDate(ref target);
}
}
/*static*/
internal static void CanPanelShowFullScope(
CalendarViewGeneratorHost pHost,
out bool pCanPanelShowFullScope)
{
var pCalendarPanel = pHost.Panel;
int row = 0;
int col = 0;
pCanPanelShowFullScope = false;
global::System.Diagnostics.Debug.Assert(pCalendarPanel is { });
row = pCalendarPanel.Rows;
col = pCalendarPanel.Cols;
// Consider about the corner case: the first item in this scope
// is laid on the last col in first row, so according dimension
// row x col, we could arrange up to (row - 1) x col + 1 items
pCanPanelShowFullScope = (row - 1) * col + 1 >= pHost.GetMaximumScopeSize();
return;
}
private void ForeachChildInPanel(
CalendarPanel pCalendarPanel,
Action<CalendarViewBaseItem> func)
{
if (pCalendarPanel is { })
{
if (pCalendarPanel.IsInLiveTree)
{
int firstCacheIndex = 0;
int lastCacheIndex = 0;
firstCacheIndex = pCalendarPanel.FirstCacheIndex;
lastCacheIndex = pCalendarPanel.LastCacheIndex;
for (int i = firstCacheIndex; i <= lastCacheIndex; ++i)
{
DependencyObject spChildAsIDO;
CalendarViewBaseItem spChildAsI;
spChildAsIDO = pCalendarPanel.ContainerFromIndex(i);
spChildAsI = spChildAsIDO as CalendarViewBaseItem;
func(((CalendarViewBaseItem)spChildAsI));
}
}
}
return;
}
private void ForeachHost(Action<CalendarViewGeneratorHost> func)
{
func(m_tpMonthViewItemHost);
func(m_tpYearViewItemHost);
func(m_tpDecadeViewItemHost);
return;
}
/*static*/
internal static void SetDayItemStyle(
CalendarViewBaseItem pItem,
Style pStyle)
{
global::System.Diagnostics.Debug.Assert(pItem is CalendarViewDayItem);
if (pStyle is { })
{
pItem.Style = pStyle;
}
else
{
pItem.ClearValue(FrameworkElement.StyleProperty);
}
return;
}
protected override AutomationPeer OnCreateAutomationPeer()
{
AutomationPeer ppAutomationPeer = null;
CalendarViewAutomationPeer spAutomationPeer;
spAutomationPeer = new CalendarViewAutomationPeer(this);
ppAutomationPeer = spAutomationPeer;
return ppAutomationPeer;
}
// Called when the IsEnabled property changes.
private protected override void OnIsEnabledChanged(IsEnabledChangedEventArgs pArgs)
{
UpdateVisualState();
}
internal void GetRowHeaderForItemAutomationPeer(
DateTime itemDate,
CalendarViewDisplayMode displayMode,
out uint pReturnValueCount,
out IRawElementProviderSimple[] ppReturnValue)
{
pReturnValueCount = 0;
ppReturnValue = null;
CalendarViewDisplayMode mode = CalendarViewDisplayMode.Month;
mode = DisplayMode;
//Ensure we only read out this header when in Month mode or Year mode. Decade mode reading the header isn't helpful.
if (displayMode == mode)
{
int month, year;
m_tpCalendar.SetDateTime(itemDate);
month = m_tpCalendar.Month;
year = m_tpCalendar.Year;
bool useCurrentHeaderPeer =
m_currentHeaderPeer is { } &&
(m_currentHeaderPeer.GetMonth() == month || mode == CalendarViewDisplayMode.Year) &&
m_currentHeaderPeer.GetYear() == year &&
m_currentHeaderPeer.GetMode() == mode;
bool usePreviousHeaderPeer =
m_previousHeaderPeer is { } &&
(m_previousHeaderPeer.GetMonth() == month || mode == CalendarViewDisplayMode.Year) &&
m_previousHeaderPeer.GetYear() == year &&
m_previousHeaderPeer.GetMode() == mode;
bool createNewHeaderPeer = !useCurrentHeaderPeer && !usePreviousHeaderPeer;
if (createNewHeaderPeer)
{
CalendarViewHeaderAutomationPeer peer;
peer = new CalendarViewHeaderAutomationPeer();
string headerName;
if (mode == CalendarViewDisplayMode.Month)
{
headerName = FormatMonthYearName(itemDate);
}
else
{
global::System.Diagnostics.Debug.Assert(mode == CalendarViewDisplayMode.Year);
headerName = FormatYearName(itemDate);
}
peer.Initialize(headerName, month, year, mode);
m_previousHeaderPeer = m_currentHeaderPeer;
m_currentHeaderPeer = peer;
}
global::System.Diagnostics.Debug.Assert(m_currentHeaderPeer is { } || m_previousHeaderPeer is { });
var peerToUse =
usePreviousHeaderPeer ? m_previousHeaderPeer : m_currentHeaderPeer;
IRawElementProviderSimple provider;
provider = peerToUse.ProviderFromPeer(peerToUse);
ppReturnValue = new[] { provider };
pReturnValueCount = 1;
}
return;
}
private void UpdateFlowDirectionForView()
{
if (m_tpViewsGrid is { } && m_tpMonthYearFormatter is { })
{
bool isRTL = false;
{
IReadOnlyList<string> spPatterns;
spPatterns = m_tpMonthYearFormatter.Patterns;
string strFormatPattern;
strFormatPattern = spPatterns[0];
if (strFormatPattern is { })
{
//uint length = 0;
var buffer = strFormatPattern;
isRTL = buffer[0] == RTL_CHARACTER_CODE;
}
}
var flowDirection = isRTL ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
((Grid)m_tpViewsGrid).FlowDirection = flowDirection;
}
return;
}
}
}
| CalendarView |
csharp | EventStore__EventStore | src/KurrentDB.Core/DataStructures/ObjectPool.cs | {
"start": 330,
"end": 736
} | public class ____ : Exception {
public ObjectPoolDisposingException(string poolName)
: this(poolName, null) {
}
public ObjectPoolDisposingException(string poolName, Exception innerException)
: base(string.Format("Object pool '{0}' is disposing/disposed while Get operation is requested.", poolName),
innerException) {
Ensure.NotNullOrEmpty(poolName, "poolName");
}
}
| ObjectPoolDisposingException |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Controls/WebView/Utils/WebViewUtils.cs | {
"start": 48,
"end": 1191
} | internal static class ____
{
/// <summary>
/// Determines if a navigation is an anchor navigation within the same page.
/// </summary>
/// <param name="currentUrl">The URL of the current page</param>
/// <param name="newUrl">The URL being navigated to</param>
/// <returns>True if this is an anchor navigation, false otherwise</returns>
internal static bool IsAnchorNavigation(string currentUrl, string newUrl)
{
if (string.IsNullOrEmpty(currentUrl) || string.IsNullOrEmpty(newUrl))
{
return false;
}
var currentUrlParts = currentUrl.Split('#');
var newUrlParts = newUrl.Split('#');
// Check if this is anchor navigation:
// 1. Both URLs should have the same base (before #)
// 2. New URL should have an anchor part (after #)
// 3. The anchor parts should be different (or one missing)
return currentUrlParts.Length >= 1
&& newUrlParts.Length >= 2
&& currentUrlParts[0].Equals(newUrlParts[0], StringComparison.OrdinalIgnoreCase)
&& !string.IsNullOrEmpty(newUrlParts[1])
&& (currentUrlParts.Length == 1 || !currentUrlParts[1].Equals(newUrlParts[1], StringComparison.OrdinalIgnoreCase));
}
} | WebViewUtils |
csharp | dotnet__extensions | src/Libraries/Microsoft.AspNetCore.Diagnostics.Middleware/Latency/CapturePipelineEntryStartupFilter.cs | {
"start": 407,
"end": 1051
} | internal sealed class ____ : IStartupFilter
{
/// <summary>
/// Wraps the <see cref="IApplicationBuilder"/> directly adds
/// <see cref="CapturePipelineEntryMiddleware"/> at the beginning the middleware pipeline.
/// </summary>
/// <param name="next">The Configure method to extend.</param>
/// <returns>A modified <see cref="Action"/>.</returns>
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
return builder =>
{
_ = builder.UseMiddleware<CapturePipelineEntryMiddleware>();
next(builder);
};
}
}
| CapturePipelineEntryStartupFilter |
csharp | dotnet__machinelearning | src/Microsoft.ML.FastTree/FastTreeArguments.cs | {
"start": 14783,
"end": 14918
} | public enum ____ : byte
{
None = 0,
AggregateLowPopulation = 1,
Adjacent = 2
}
[BestFriend]
| Bundle |
csharp | MassTransit__MassTransit | src/MassTransit/Middleware/ExecuteActivityFilter.cs | {
"start": 344,
"end": 2141
} | public class ____<TActivity, TArguments> :
IFilter<ExecuteActivityContext<TActivity, TArguments>>
where TActivity : class, IExecuteActivity<TArguments>
where TArguments : class
{
readonly ActivityObservable _observers;
public ExecuteActivityFilter(ActivityObservable observers)
{
_observers = observers;
}
void IProbeSite.Probe(ProbeContext context)
{
context.CreateFilterScope("execute");
}
public async Task Send(ExecuteActivityContext<TActivity, TArguments> context, IPipe<ExecuteActivityContext<TActivity, TArguments>> next)
{
try
{
if (_observers.Count > 0)
await _observers.PreExecute(context).ConfigureAwait(false);
var result = context.Result = await context.Activity.Execute(context).ConfigureAwait(false)
?? context.Faulted(new ActivityExecutionException("The activity execute did not return a result"));
if (result.IsFaulted(out var exception))
exception.Rethrow();
await next.Send(context).ConfigureAwait(false);
if (_observers.Count > 0)
await _observers.PostExecute(context).ConfigureAwait(false);
}
catch (Exception exception)
{
if (context.Result == null || !context.Result.IsFaulted(out var faultException) || faultException != exception)
context.Result = context.Faulted(exception);
if (_observers.Count > 0)
await _observers.ExecuteFault(context, exception).ConfigureAwait(false);
throw;
}
}
}
}
| ExecuteActivityFilter |
csharp | unoplatform__uno | src/Uno.UI.Tests/BinderTests/Given_Binder.DynamicObject.cs | {
"start": 391,
"end": 2520
} | public partial class ____
{
[TestMethod]
public void When_ReadValue()
{
var target = new MyControl();
dynamic source = new MyDynamicObject();
target.SetBinding(
MyControl.MyPropertyProperty,
new Microsoft.UI.Xaml.Data.Binding()
{
Path = new PropertyPath("TestDynamicProperty")
}
);
source.TestDynamicProperty = "Dynamic Value";
target.DataContext = source;
Assert.AreEqual("Dynamic Value", target.MyProperty);
}
[TestMethod]
public void When_ReadValue_And_Update()
{
var target = new MyControl();
dynamic source = new MyDynamicObject();
target.SetBinding(
MyControl.MyPropertyProperty,
new Microsoft.UI.Xaml.Data.Binding()
{
Path = new PropertyPath("TestDynamicProperty")
}
);
source.TestDynamicProperty = "Dynamic Value";
target.DataContext = source;
Assert.AreEqual("Dynamic Value", target.MyProperty);
source.TestDynamicProperty = "Dynamic Value2";
Assert.AreEqual("Dynamic Value2", target.MyProperty);
}
[TestMethod]
public void When_TwoWay_Binding()
{
var target = new MyControl();
dynamic source = new MyDynamicObject();
target.SetBinding(
MyControl.MyPropertyProperty,
new Microsoft.UI.Xaml.Data.Binding()
{
Path = new PropertyPath("TestDynamicProperty")
,
Mode = BindingMode.TwoWay
}
);
source.TestDynamicProperty = "Dynamic Value";
target.DataContext = source;
Assert.AreEqual("Dynamic Value", target.MyProperty);
target.MyProperty = "target value";
Assert.AreEqual("target value", source.TestDynamicProperty);
}
[TestMethod]
public void When_Unknown_Property()
{
var target = new MyControl();
dynamic source = new MyDynamicObject();
target.SetBinding(
MyControl.MyPropertyProperty,
new Microsoft.UI.Xaml.Data.Binding()
{
Path = new PropertyPath("UnknownProperty")
,
Mode = BindingMode.TwoWay
}
);
target.DataContext = source;
Assert.IsNull(target.MyProperty);
target.MyProperty = "42";
Assert.AreEqual("42", source.UnknownProperty);
}
| Given_Binder_DynamicObject |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.Application.Cms.Core.Targets/ServiceExtensions.cs | {
"start": 103,
"end": 1854
} | public static class ____
{
/// <summary>
/// Adds Orchard CMS services to the application.
/// </summary>
public static OrchardCoreBuilder AddOrchardCms(this IServiceCollection services)
{
ArgumentNullException.ThrowIfNull(services);
var builder = services.AddOrchardCore()
.AddCommands()
.AddSecurity()
.AddMvc()
.AddIdGeneration()
.AddEmailAddressValidator()
.AddHtmlSanitizer()
.AddSetupFeatures("OrchardCore.Setup")
.AddDataAccess()
.AddDataStorage()
.AddBackgroundService()
.AddScripting()
.AddTheming()
.AddGlobalFeatures("OrchardCore.Liquid.Core")
.AddCaching();
// OrchardCoreBuilder is not available in OrchardCore.ResourceManagement as it has to
// remain independent from OrchardCore.
builder.ConfigureServices(s =>
{
s.AddResourceManagement();
s.AddTagHelpers<LinkTagHelper>();
s.AddTagHelpers<MetaTagHelper>();
s.AddTagHelpers<ResourcesTagHelper>();
s.AddTagHelpers<ScriptTagHelper>();
s.AddTagHelpers<StyleTagHelper>();
});
return builder;
}
/// <summary>
/// Adds Orchard CMS services to the application and let the app change the
/// default tenant behavior and set of features through a configure action.
/// </summary>
public static IServiceCollection AddOrchardCms(this IServiceCollection services, Action<OrchardCoreBuilder> configure)
{
var builder = services.AddOrchardCms();
configure?.Invoke(builder);
return services;
}
}
| ServiceExtensions |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.ContentFields/GraphQL/Startup.cs | {
"start": 431,
"end": 1150
} | public sealed class ____ : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IContentFieldProvider, ObjectGraphTypeFieldProvider>();
services.AddTransient<IContentFieldProvider, ContentFieldsProvider>();
services.AddObjectGraphType<LinkField, LinkFieldQueryObjectType>();
services.AddObjectGraphType<HtmlField, HtmlFieldQueryObjectType>();
services.AddObjectGraphType<ContentPickerField, ContentPickerFieldQueryObjectType>();
services.AddObjectGraphType<UserPickerField, UserPickerFieldQueryObjectType>();
}
}
[RequireFeatures("OrchardCore.Apis.GraphQL", "OrchardCore.ContentFields.Indexing.SQL")]
| Startup |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Rules/Drivers/IsAuthenticatedConditionDisplayDriver.cs | {
"start": 160,
"end": 919
} | public sealed class ____ : DisplayDriver<Condition, IsAuthenticatedCondition>
{
public override Task<IDisplayResult> DisplayAsync(IsAuthenticatedCondition condition, BuildDisplayContext context)
{
return
CombineAsync(
View("IsAuthenticatedCondition_Fields_Summary", condition).Location(OrchardCoreConstants.DisplayType.Summary, "Content"),
View("IsAuthenticatedCondition_Fields_Thumbnail", condition).Location("Thumbnail", "Content")
);
}
public override IDisplayResult Edit(IsAuthenticatedCondition condition, BuildEditorContext context)
{
return View("IsAuthenticatedCondition_Fields_Edit", condition).Location("Content");
}
}
| IsAuthenticatedConditionDisplayDriver |
csharp | Cysharp__UniTask | src/UniTask/Assets/Plugins/UniTask/Runtime/Linq/Join.cs | {
"start": 191,
"end": 6085
} | partial class ____
{
public static IUniTaskAsyncEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(this IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector)
{
Error.ThrowArgumentNullException(outer, nameof(outer));
Error.ThrowArgumentNullException(inner, nameof(inner));
Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector));
Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector));
Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector));
return new Join<TOuter, TInner, TKey, TResult>(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer<TKey>.Default);
}
public static IUniTaskAsyncEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(this IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector, IEqualityComparer<TKey> comparer)
{
Error.ThrowArgumentNullException(outer, nameof(outer));
Error.ThrowArgumentNullException(inner, nameof(inner));
Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector));
Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector));
Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector));
Error.ThrowArgumentNullException(comparer, nameof(comparer));
return new Join<TOuter, TInner, TKey, TResult>(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer);
}
public static IUniTaskAsyncEnumerable<TResult> JoinAwait<TOuter, TInner, TKey, TResult>(this IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, UniTask<TKey>> outerKeySelector, Func<TInner, UniTask<TKey>> innerKeySelector, Func<TOuter, TInner, UniTask<TResult>> resultSelector)
{
Error.ThrowArgumentNullException(outer, nameof(outer));
Error.ThrowArgumentNullException(inner, nameof(inner));
Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector));
Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector));
Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector));
return new JoinAwait<TOuter, TInner, TKey, TResult>(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer<TKey>.Default);
}
public static IUniTaskAsyncEnumerable<TResult> JoinAwait<TOuter, TInner, TKey, TResult>(this IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, UniTask<TKey>> outerKeySelector, Func<TInner, UniTask<TKey>> innerKeySelector, Func<TOuter, TInner, UniTask<TResult>> resultSelector, IEqualityComparer<TKey> comparer)
{
Error.ThrowArgumentNullException(outer, nameof(outer));
Error.ThrowArgumentNullException(inner, nameof(inner));
Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector));
Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector));
Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector));
Error.ThrowArgumentNullException(comparer, nameof(comparer));
return new JoinAwait<TOuter, TInner, TKey, TResult>(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer);
}
public static IUniTaskAsyncEnumerable<TResult> JoinAwaitWithCancellation<TOuter, TInner, TKey, TResult>(this IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, CancellationToken, UniTask<TKey>> outerKeySelector, Func<TInner, CancellationToken, UniTask<TKey>> innerKeySelector, Func<TOuter, TInner, CancellationToken, UniTask<TResult>> resultSelector)
{
Error.ThrowArgumentNullException(outer, nameof(outer));
Error.ThrowArgumentNullException(inner, nameof(inner));
Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector));
Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector));
Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector));
return new JoinAwaitWithCancellation<TOuter, TInner, TKey, TResult>(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer<TKey>.Default);
}
public static IUniTaskAsyncEnumerable<TResult> JoinAwaitWithCancellation<TOuter, TInner, TKey, TResult>(this IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, CancellationToken, UniTask<TKey>> outerKeySelector, Func<TInner, CancellationToken, UniTask<TKey>> innerKeySelector, Func<TOuter, TInner, CancellationToken, UniTask<TResult>> resultSelector, IEqualityComparer<TKey> comparer)
{
Error.ThrowArgumentNullException(outer, nameof(outer));
Error.ThrowArgumentNullException(inner, nameof(inner));
Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector));
Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector));
Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector));
Error.ThrowArgumentNullException(comparer, nameof(comparer));
return new JoinAwaitWithCancellation<TOuter, TInner, TKey, TResult>(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer);
}
}
| UniTaskAsyncEnumerable |
csharp | cake-build__cake | src/Cake.Common.Tests/Unit/Tools/NuGet/Sources/NuGetSourcesTests.cs | {
"start": 18330,
"end": 21022
} | public sealed class ____
{
[Fact]
public void Should_Throw_If_Source_Is_Null()
{
// Given
var fixture = new NuGetHasSourceFixture();
fixture.Source = null;
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsArgumentNullException(result, "source");
}
[Theory]
[InlineData("")]
[InlineData("\t")]
public void Should_Throw_If_Source_Is_Empty(string source)
{
// Given
var fixture = new NuGetHasSourceFixture();
fixture.Source = source;
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsArgumentException(result, "source", "Source cannot be empty.");
}
[Fact]
public void Should_Throw_If_Settings_Is_Null()
{
// Given
var fixture = new NuGetHasSourceFixture();
fixture.Settings = null;
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsArgumentNullException(result, "settings");
}
[Fact]
public void Should_Add_Mandatory_Arguments()
{
// Given
var fixture = new NuGetHasSourceFixture();
// When
var result = fixture.Run();
// Then
Assert.Equal("sources List -NonInteractive", result.Args);
}
[Fact]
public void Should_Add_ConfigFile_To_Arguments_If_Set()
{
// Given
var fixture = new NuGetHasSourceFixture();
fixture.Settings.ConfigFile = "./src/NuGet.config";
// When
var result = fixture.Run();
// Then
Assert.Equal("sources List -ConfigFile \"src/NuGet.config\" -NonInteractive", result.Args);
}
[Fact]
public void Should_Add_Argument_Customization()
{
// Given
var fixture = new NuGetHasSourceFixture();
fixture.Settings.ArgumentCustomization = arg => arg.Append("-Foo");
// When
var result = fixture.Run();
// Then
Assert.Equal("sources List -NonInteractive -Foo", result.Args);
}
}
}
} | TheHasSourceMethod |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.ContentManagement/Handlers/ContentPartHandlerCoordinator.cs | {
"start": 260,
"end": 22997
} | public class ____ : ContentHandlerBase
{
private readonly IContentPartHandlerResolver _contentPartHandlerResolver;
private readonly IContentFieldHandlerResolver _contentFieldHandlerResolver;
private readonly ITypeActivatorFactory<ContentPart> _contentPartFactory;
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly ITypeActivatorFactory<ContentField> _contentFieldFactory;
private readonly ILogger _logger;
public ContentPartHandlerCoordinator(
IContentPartHandlerResolver contentPartHandlerResolver,
IContentFieldHandlerResolver contentFieldHandlerResolver,
ITypeActivatorFactory<ContentPart> contentPartFactory,
ITypeActivatorFactory<ContentField> contentFieldFactory,
IContentDefinitionManager contentDefinitionManager,
ILogger<ContentPartHandlerCoordinator> logger)
{
_contentPartHandlerResolver = contentPartHandlerResolver;
_contentFieldHandlerResolver = contentFieldHandlerResolver;
_contentPartFactory = contentPartFactory;
_contentFieldFactory = contentFieldFactory;
_contentDefinitionManager = contentDefinitionManager;
_logger = logger;
}
public override Task ActivatingAsync(ActivatingContentContext context)
{
// This method is called on New()
// Adds all the parts to a content item based on the content type definition.
// When a part/field does not exists, we create the part from it's known type or from a generic one
var fieldContext = new ActivatingContentFieldContext(context.ContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.ActivatingAsync(context, part),
(handler, context, field) => handler.ActivatingAsync(fieldContext, field),
createPartIfNotExists: true,
createFieldIfNotExists: true);
}
public override Task ActivatedAsync(ActivatedContentContext context)
{
var fieldContext = new ActivatedContentFieldContext(context.ContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.ActivatedAsync(context, part),
(handler, context, field) => handler.ActivatedAsync(fieldContext, field));
}
public override Task CreatingAsync(CreateContentContext context)
{
var fieldContext = new CreateContentFieldContext(context.ContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.CreatingAsync(context, part),
(handler, context, field) => handler.CreatingAsync(fieldContext, field));
}
public override Task CreatedAsync(CreateContentContext context)
{
var fieldContext = new CreateContentFieldContext(context.ContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.CreatedAsync(context, part),
(handler, context, field) => handler.CreatedAsync(fieldContext, field));
}
public override Task ImportingAsync(ImportContentContext context)
{
var fieldContext = new ImportContentFieldContext(context.ContentItem, context.OriginalContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.ImportingAsync(context, part),
(handler, context, field) => handler.ImportingAsync(fieldContext, field));
}
public override Task ImportedAsync(ImportContentContext context)
{
var fieldContext = new ImportContentFieldContext(context.ContentItem, context.OriginalContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.ImportedAsync(context, part),
(handler, context, field) => handler.ImportedAsync(fieldContext, field));
}
public override Task InitializingAsync(InitializingContentContext context)
{
var fieldContext = new InitializingContentFieldContext(context.ContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.InitializingAsync(context, part),
(handler, context, field) => handler.InitializingAsync(fieldContext, field));
}
public override Task InitializedAsync(InitializingContentContext context)
{
var fieldContext = new InitializingContentFieldContext(context.ContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.InitializedAsync(context, part),
(handler, context, field) => handler.InitializedAsync(fieldContext, field));
}
public override Task LoadingAsync(LoadContentContext context)
{
// This method is called on Get()
// Adds all the missing parts to a content item based on the content type definition.
// A part is missing if the content type is changed and an old content item is loaded,
// like edited.
var fieldContext = new LoadContentFieldContext(context.ContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.LoadingAsync(context, part),
(handler, context, field) => handler.LoadingAsync(fieldContext, field),
createPartIfNotExists: true,
createFieldIfNotExists: true);
}
public override Task LoadedAsync(LoadContentContext context)
{
var fieldContext = new LoadContentFieldContext(context.ContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.LoadedAsync(context, part),
(handler, context, field) => handler.LoadedAsync(fieldContext, field));
}
public override Task ValidatingAsync(ValidateContentContext context)
{
return InvokeHandlers(context,
(handler, context, part) => handler.ValidatingAsync(context, part),
(handler, context, field) => handler.ValidatingAsync(context, field));
}
public override Task ValidatedAsync(ValidateContentContext context)
{
return InvokeHandlers(context,
(handler, context, part) => handler.ValidatedAsync(context, part),
(handler, context, field) => handler.ValidatedAsync(new ValidateContentFieldContext(context.ContentItem), field));
}
public override Task DraftSavingAsync(SaveDraftContentContext context)
{
var fieldContext = new SaveDraftContentFieldContext(context.ContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.DraftSavingAsync(context, part),
(handler, context, field) => handler.DraftSavingAsync(fieldContext, field));
}
public override Task DraftSavedAsync(SaveDraftContentContext context)
{
var fieldContext = new SaveDraftContentFieldContext(context.ContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.DraftSavedAsync(context, part),
(handler, context, field) => handler.DraftSavedAsync(fieldContext, field));
}
public override Task PublishingAsync(PublishContentContext context)
{
var fieldContext = new PublishContentFieldContext(context.ContentItem, context.PreviousItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.PublishingAsync(context, part),
(handler, context, field) => handler.PublishingAsync(fieldContext, field));
}
public override Task PublishedAsync(PublishContentContext context)
{
var fieldContext = new PublishContentFieldContext(context.ContentItem, context.PreviousItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.PublishedAsync(context, part),
(handler, context, field) => handler.PublishedAsync(fieldContext, field));
}
public override Task RemovingAsync(RemoveContentContext context)
{
var fieldContext = new RemoveContentFieldContext(context.ContentItem, context.NoActiveVersionLeft);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.RemovingAsync(context, part),
(handler, context, field) => handler.RemovingAsync(fieldContext, field));
}
public override Task RemovedAsync(RemoveContentContext context)
{
var fieldContext = new RemoveContentFieldContext(context.ContentItem, context.NoActiveVersionLeft);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.RemovedAsync(context, part),
(handler, context, field) => handler.RemovedAsync(fieldContext, field));
}
public override Task UnpublishingAsync(PublishContentContext context)
{
var fieldContext = new PublishContentFieldContext(context.ContentItem, context.PreviousItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.UnpublishingAsync(context, part),
(handler, context, field) => handler.UnpublishingAsync(fieldContext, field));
}
public override Task UnpublishedAsync(PublishContentContext context)
{
var fieldContext = new PublishContentFieldContext(context.ContentItem, context.PreviousItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.UnpublishedAsync(context, part),
(handler, context, field) => handler.UnpublishedAsync(fieldContext, field));
}
public override Task UpdatingAsync(UpdateContentContext context)
{
var fieldContext = new UpdateContentFieldContext(context.ContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.UpdatingAsync(context, part),
(handler, context, field) => handler.UpdatingAsync(fieldContext, field));
}
public override Task UpdatedAsync(UpdateContentContext context)
{
var fieldContext = new UpdateContentFieldContext(context.ContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.UpdatedAsync(context, part),
(handler, context, field) => handler.UpdatedAsync(fieldContext, field));
}
public override Task VersioningAsync(VersionContentContext context)
{
var fieldContext = new VersionContentFieldContext(context.ContentItem, context.BuildingContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, existingPart, buildingPart) => handler.VersioningAsync(context, existingPart, buildingPart),
(handler, context, existingField, buildingField) => handler.VersioningAsync(fieldContext, existingField, buildingField));
}
public override Task VersionedAsync(VersionContentContext context)
{
var fieldContext = new VersionContentFieldContext(context.ContentItem, context.BuildingContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, existingPart, buildingPart) => handler.VersionedAsync(context, existingPart, buildingPart),
(handler, context, existingField, buildingField) => handler.VersionedAsync(fieldContext, existingField, buildingField));
}
public override async Task GetContentItemAspectAsync(ContentItemAspectContext context)
{
var contentTypeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
{
return;
}
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
if (typePartDefinition.PartDefinition is null)
{
continue;
}
var partName = typePartDefinition.PartDefinition.Name;
var activator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(activator.Type, typePartDefinition.Name) as ContentPart;
if (part == null)
{
continue;
}
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync((handler, context, part) => handler.GetContentItemAspectAsync(context, part), context, part, _logger);
if (typePartDefinition.PartDefinition.Fields is null)
{
continue;
}
foreach (var partFieldDefinition in typePartDefinition.PartDefinition.Fields)
{
var fieldName = partFieldDefinition.FieldDefinition.Name;
var fieldActivator = _contentFieldFactory.GetTypeActivator(fieldName);
var field = context.ContentItem.Get(fieldActivator.Type, partFieldDefinition.Name) as ContentField;
if (field == null)
{
continue;
}
var fieldHandlers = _contentFieldHandlerResolver.GetHandlers(fieldName);
await fieldHandlers.InvokeAsync((handler, context, field) => handler.GetContentItemAspectAsync(context, field), context, field, _logger);
}
}
}
public override Task ClonedAsync(CloneContentContext context)
{
var fieldContext = new CloneContentFieldContext(context.ContentItem, context.CloneContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.ClonedAsync(context, part),
(handler, context, field) => handler.ClonedAsync(fieldContext, field));
}
public override Task CloningAsync(CloneContentContext context)
{
var fieldContext = new CloneContentFieldContext(context.ContentItem, context.CloneContentItem);
return InvokeHandlers(context, fieldContext,
(handler, context, part) => handler.CloningAsync(context, part),
(handler, context, field) => handler.CloningAsync(fieldContext, field));
}
private async Task InvokeHandlers<TContext, TFieldContext>(
TContext context,
TFieldContext fieldContext,
Func<IContentPartHandler, TContext, ContentPart, Task> partHandlerAction,
Func<IContentFieldHandler, TFieldContext, ContentField, Task> fieldHandlerAction,
bool createPartIfNotExists = false,
bool createFieldIfNotExists = false)
where TContext : ContentContextBase
where TFieldContext : ContentFieldContextBase
{
var contentTypeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
{
return;
}
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
if (typePartDefinition.PartDefinition is null)
{
continue;
}
var partName = typePartDefinition.PartDefinition.Name;
var partActivator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(partActivator.Type, typePartDefinition.Name) as ContentPart;
if (part == null && createPartIfNotExists)
{
part = partActivator.CreateInstance();
context.ContentItem.Weld(typePartDefinition.Name, part);
}
if (part == null)
{
continue;
}
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync(partHandlerAction, context, part, _logger);
if (typePartDefinition.PartDefinition.Fields == null)
{
continue;
}
foreach (var partFieldDefinition in typePartDefinition.PartDefinition.Fields)
{
var fieldName = partFieldDefinition.FieldDefinition.Name;
var fieldActivator = _contentFieldFactory.GetTypeActivator(fieldName);
// Attempt to get the field from the part.
var field = part.Get(fieldActivator.Type, partFieldDefinition.Name) as ContentField;
if (field == null && createFieldIfNotExists)
{
field = fieldActivator.CreateInstance();
part.Weld(partFieldDefinition.Name, field);
}
if (field == null)
{
continue;
}
fieldContext.ContentPartFieldDefinition = partFieldDefinition;
fieldContext.PartName = typePartDefinition.Name ?? partName;
var fieldHandlers = _contentFieldHandlerResolver.GetHandlers(fieldName);
await fieldHandlers.InvokeAsync(fieldHandlerAction, fieldContext, field, _logger);
}
}
}
private async Task InvokeHandlers<TContext, TFieldContext>(
TContext context,
TFieldContext fieldContext,
Func<IContentPartHandler, TContext, ContentPart, ContentPart, Task> partHandlerAction,
Func<IContentFieldHandler, TFieldContext, ContentField, ContentField, Task> fieldHandlerAction)
where TContext : VersionContentContext
where TFieldContext : VersionContentFieldContext
{
var contentTypeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
{
return;
}
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
if (typePartDefinition.PartDefinition is null)
{
continue;
}
var partName = typePartDefinition.PartDefinition.Name;
var partActivator = _contentPartFactory.GetTypeActivator(partName);
var buildingPart = (ContentPart)context.BuildingContentItem.Get(partActivator.Type, partName);
var existingPart = (ContentPart)context.ContentItem.Get(partActivator.Type, typePartDefinition.Name);
if (buildingPart == null || existingPart == null)
{
continue;
}
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
await partHandlers.InvokeAsync(partHandlerAction, context, existingPart, buildingPart, _logger);
if (typePartDefinition.PartDefinition.Fields == null)
{
continue;
}
foreach (var partFieldDefinition in typePartDefinition.PartDefinition.Fields)
{
var fieldName = partFieldDefinition.FieldDefinition.Name;
var fieldActivator = _contentFieldFactory.GetTypeActivator(fieldName);
var buildingField = (ContentField)buildingPart.Get(fieldActivator.Type, fieldName);
var existingField = (ContentField)existingPart.Get(fieldActivator.Type, partFieldDefinition.Name);
if (buildingField == null || existingField == null)
{
continue;
}
fieldContext.ContentPartFieldDefinition = partFieldDefinition;
fieldContext.PartName = typePartDefinition.Name ?? partName;
var fieldHandlers = _contentFieldHandlerResolver.GetHandlers(fieldName);
await fieldHandlers.InvokeAsync(fieldHandlerAction, fieldContext, existingField, buildingField, _logger);
}
}
}
private async Task InvokeHandlers<TContext>(
TContext context,
Func<IContentPartHandler, ValidateContentContext, ContentPart, Task> partHandlerAction,
Func<IContentFieldHandler, ValidateContentFieldContext, ContentField, Task> fieldHandlerAction)
where TContext : ValidateContentContext
{
var contentTypeDefinition = await _contentDefinitionManager.GetTypeDefinitionAsync(context.ContentItem.ContentType);
if (contentTypeDefinition == null)
{
return;
}
foreach (var typePartDefinition in contentTypeDefinition.Parts)
{
if (typePartDefinition.PartDefinition is null)
{
continue;
}
var partName = typePartDefinition.PartDefinition.Name;
var partActivator = _contentPartFactory.GetTypeActivator(partName);
var part = context.ContentItem.Get(partActivator.Type, typePartDefinition.Name) as ContentPart;
if (part == null)
{
continue;
}
var partHandlers = _contentPartHandlerResolver.GetHandlers(partName);
var partValidationContext = new ValidateContentPartContext(context.ContentItem)
{
ContentTypePartDefinition = typePartDefinition,
};
await partHandlers.InvokeAsync(partHandlerAction, partValidationContext, part, _logger);
// Add any part errors to the context errors.
foreach (var error in partValidationContext.ContentValidateResult.Errors)
{
context.ContentValidateResult.Fail(error);
}
if (typePartDefinition.PartDefinition.Fields == null)
{
continue;
}
foreach (var partFieldDefinition in typePartDefinition.PartDefinition.Fields)
{
var fieldName = partFieldDefinition.FieldDefinition.Name;
var fieldActivator = _contentFieldFactory.GetTypeActivator(fieldName);
var field = part.Get(fieldActivator.Type, partFieldDefinition.Name) as ContentField;
if (field == null)
{
continue;
}
var validateFieldContentContext = new ValidateContentFieldContext(context.ContentItem)
{
ContentPartFieldDefinition = partFieldDefinition,
PartName = typePartDefinition.Name ?? partName,
};
var fieldHandlers = _contentFieldHandlerResolver.GetHandlers(fieldName);
await fieldHandlers.InvokeAsync(fieldHandlerAction, validateFieldContentContext, field, _logger);
// Add any field errors to the context errors.
foreach (var error in validateFieldContentContext.ContentValidateResult.Errors)
{
context.ContentValidateResult.Fail(error);
}
}
}
}
}
| ContentPartHandlerCoordinator |
csharp | microsoft__semantic-kernel | dotnet/src/SemanticKernel.AotTests/UnitTests/Search/VectorStoreTextSearchTests.cs | {
"start": 2571,
"end": 2873
} | private sealed class ____
{
[TextSearchResultName]
public required string Key { get; init; }
[TextSearchResultValue]
public required string Text { get; init; }
[TextSearchResultLinkAttribute]
public required string Link { get; init; }
}
}
| DataModel |
csharp | abpframework__abp | modules/docs/src/Volo.Docs.Web/HtmlConverting/DocumentNavigationDto.cs | {
"start": 37,
"end": 149
} | public class ____
{
public string Name { get; set; }
public string Path { get; set; }
} | DocumentNavigationDto |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 6233916,
"end": 6235320
} | public partial record ____
{
public PageInfoData(global::System.String __typename, global::System.Boolean? hasPreviousPage = default !, global::System.Boolean? hasNextPage = default !, global::System.String? endCursor = default !, global::System.String? startCursor = default !)
{
this.__typename = __typename ?? throw new global::System.ArgumentNullException(nameof(__typename));
HasPreviousPage = hasPreviousPage;
HasNextPage = hasNextPage;
EndCursor = endCursor;
StartCursor = startCursor;
}
public global::System.String __typename { get; init; }
///<summary>Indicates whether more edges exist prior the set defined by the clients arguments.</summary>
public global::System.Boolean? HasPreviousPage { get; init; }
///<summary>Indicates whether more edges exist following the set defined by the clients arguments.</summary>
public global::System.Boolean? HasNextPage { get; init; }
///<summary>When paginating forwards, the cursor to continue.</summary>
public global::System.String? EndCursor { get; init; }
///<summary>When paginating backwards, the cursor to continue.</summary>
public global::System.String? StartCursor { get; init; }
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| PageInfoData |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.Tests/DI.xUnit/ServiceRegisterExtensions.cs | {
"start": 45,
"end": 787
} | internal static class ____
{
public static void Transient<TService>(this IServiceRegister register)
{
register.Register(typeof(TService), typeof(TService), ServiceLifetime.Transient);
}
public static void Scoped<TService>(this IServiceRegister register)
{
register.Register(typeof(TService), typeof(TService), ServiceLifetime.Scoped);
}
public static void Singleton<TService>(this IServiceRegister register)
{
register.Register(typeof(TService), typeof(TService), ServiceLifetime.Singleton);
}
public static void Singleton<TService>(this IServiceRegister register, TService instance)
{
register.Register(typeof(TService), instance!);
}
}
| ServiceRegisterExtensions |
csharp | exceptionless__Exceptionless | src/Exceptionless.Core/Pipeline/Base/PipelineContextBase.cs | {
"start": 62,
"end": 114
} | interface ____ pipeline context data
/// </summary>
| for |
csharp | nopSolutions__nopCommerce | src/Libraries/Nop.Services/Catalog/Caching/ReviewTypeCacheEventConsumer.cs | {
"start": 204,
"end": 542
} | public partial class ____ : CacheEventConsumer<ReviewType>
{
public override async Task HandleEventAsync(EntityDeletedEvent<ReviewType> eventMessage)
{
await RemoveByPrefixAsync(NopCatalogDefaults.ProductReviewTypeMappingByReviewIdPrefix);
await base.HandleEventAsync(eventMessage);
}
} | ReviewTypeCacheEventConsumer |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/SagaStateMachineTests/Dynamic Modify/Transition_Specs.cs | {
"start": 192,
"end": 2332
} | public class ____
{
[Test]
public void Should_call_the_enter_event()
{
Assert.That(_instance.EnterCalled, Is.True);
}
[Test]
public void Should_have_first_moved_to_initial()
{
Assert.Multiple(() =>
{
Assert.That(_observer.Events[0].Previous, Is.EqualTo(null));
Assert.That(_observer.Events[0].Current, Is.EqualTo(_machine.Initial));
});
}
[Test]
public void Should_have_second_moved_to_running()
{
Assert.Multiple(() =>
{
Assert.That(_observer.Events[1].Previous, Is.EqualTo(_machine.Initial));
Assert.That(_observer.Events[1].Current, Is.EqualTo(Running));
});
}
[Test]
public void Should_raise_the_event()
{
Assert.That(_observer.Events, Has.Count.EqualTo(2));
}
State Running;
Instance _instance;
StateMachine<Instance> _machine;
StateChangeObserver<Instance> _observer;
[OneTimeSetUp]
public void Specifying_an_event_activity()
{
_instance = new Instance();
_machine = MassTransitStateMachine<Instance>
.New(builder => builder
.State("Running", out Running)
.Event("Initialized", out Event Initialized)
.Event("Finish", out Event Finish)
.During(builder.Initial)
.When(Initialized, b => b.TransitionTo(Running))
.During(Running)
.When(Finish, b => b.Finalize())
.WhenEnter(Running, x => x.Then(context => context.Instance.EnterCalled = true))
);
_observer = new StateChangeObserver<Instance>();
using (IDisposable subscription = _machine.ConnectStateObserver(_observer))
{
_machine.TransitionToState(_instance, Running)
.Wait();
}
}
| Explicitly_transitioning_to_a_state |
csharp | nunit__nunit | src/NUnitFramework/tests/Internal/TestWorkerTests.cs | {
"start": 268,
"end": 1376
} | public class ____
{
private WorkItemQueue _queue;
private TestWorker _worker;
[SetUp]
public void SetUp()
{
_queue = new WorkItemQueue("TestQ", true, ApartmentState.MTA);
_worker = new TestWorker(_queue, "TestQ_Worker");
}
[TearDown]
public void TearDown()
{
_queue.Stop();
}
[Test]
public void BusyExecuteIdleEventsCalledInSequence()
{
StringBuilder sb = new StringBuilder();
FakeWorkItem work = Fakes.GetWorkItem(this, "FakeMethod");
_worker.Busy += (s, ea) => sb.Append("Busy");
work.Executed += (s, ea) => sb.Append("Exec");
_worker.Idle += (s, ea) => sb.Append("Idle");
_queue.Enqueue(work);
_worker.Start();
_queue.Start();
Assert.That(() => sb.ToString(), Is.EqualTo("BusyExecIdle").After(
delayInMilliseconds: 10_000, pollingInterval: 200));
}
private void FakeMethod()
{
}
}
}
| TestWorkerTests |
csharp | nopSolutions__nopCommerce | src/Libraries/Nop.Core/Infrastructure/SingletonDictionary.cs | {
"start": 252,
"end": 753
} | public partial class ____<TKey, TValue> : Singleton<IDictionary<TKey, TValue>>
{
static SingletonDictionary()
{
Singleton<Dictionary<TKey, TValue>>.Instance = new Dictionary<TKey, TValue>();
}
/// <summary>
/// The singleton instance for the specified type T. Only one instance (at the time) of this dictionary for each type of T.
/// </summary>
public static new IDictionary<TKey, TValue> Instance => Singleton<Dictionary<TKey, TValue>>.Instance;
} | SingletonDictionary |
csharp | grpc__grpc-dotnet | src/Grpc.Core.Api/Internal/ClientDebuggerHelpers.cs | {
"start": 1342,
"end": 3488
} | public class ____ { }
// }
if (!clientType.IsNested)
{
return null;
}
var parentType = clientType.DeclaringType;
// Check parent type is static. A C# static type is sealed and abstract.
if (parentType == null || (!parentType.IsSealed && !parentType.IsAbstract))
{
return null;
}
return parentType;
}
[UnconditionalSuppressMessage("Trimmer", "IL2075", Justification = "Only used by debugging. If trimming is enabled then missing data is not displayed in debugger.")]
internal static string? GetServiceName(Type clientType)
{
// Attempt to get the service name from the generated __ServiceName field.
// If the service name can't be resolved then it isn't displayed in the client's debugger display.
var parentType = GetParentType(clientType);
var field = parentType?.GetField("__ServiceName", BindingFlags.Static | BindingFlags.NonPublic);
if (field == null)
{
return null;
}
return field.GetValue(null)?.ToString();
}
[UnconditionalSuppressMessage("Trimmer", "IL2075", Justification = "Only used by debugging. If trimming is enabled then missing data is not displayed in debugger.")]
internal static List<IMethod>? GetServiceMethods(Type clientType)
{
// Attempt to get the service methods from generated method fields.
// If methods can't be resolved then the collection in the client type proxy is null.
var parentType = GetParentType(clientType);
if (parentType == null)
{
return null;
}
var methods = new List<IMethod>();
var fields = parentType.GetFields(BindingFlags.Static | BindingFlags.NonPublic);
foreach (var field in fields)
{
if (IsMethodField(field))
{
methods.Add((IMethod)field.GetValue(null));
}
}
return methods;
static bool IsMethodField(FieldInfo field) =>
typeof(IMethod).IsAssignableFrom(field.FieldType);
}
}
| GreeterClient |
csharp | SixLabors__ImageSharp | src/ImageSharp/Formats/Gif/GifEncoderCore.cs | {
"start": 542,
"end": 35111
} | internal sealed class ____
{
private readonly GifEncoder encoder;
/// <summary>
/// Used for allocating memory during processing operations.
/// </summary>
private readonly MemoryAllocator memoryAllocator;
/// <summary>
/// Configuration bound to the encoding operation.
/// </summary>
private readonly Configuration configuration;
/// <summary>
/// Whether to skip metadata during encode.
/// </summary>
private readonly bool skipMetadata;
/// <summary>
/// The color table mode: Global or local.
/// </summary>
private FrameColorTableMode? colorTableMode;
/// <summary>
/// The pixel sampling strategy for global quantization.
/// </summary>
private readonly IPixelSamplingStrategy pixelSamplingStrategy;
/// <summary>
/// The default background color of the canvas when animating.
/// This color may be used to fill the unused space on the canvas around the frames,
/// as well as the transparent pixels of the first frame.
/// The background color is also used when a frame disposal mode is <see cref="FrameDisposalMode.RestoreToBackground"/>.
/// </summary>
private readonly Color? backgroundColor;
/// <summary>
/// The number of times any animation is repeated.
/// </summary>
private readonly ushort? repeatCount;
/// <summary>
/// The transparent color mode.
/// </summary>
private readonly TransparentColorMode transparentColorMode;
/// <summary>
/// Initializes a new instance of the <see cref="GifEncoderCore"/> class.
/// </summary>
/// <param name="configuration">The configuration which allows altering default behavior or extending the library.</param>
/// <param name="encoder">The encoder with options.</param>
public GifEncoderCore(Configuration configuration, GifEncoder encoder)
{
this.configuration = configuration;
this.memoryAllocator = configuration.MemoryAllocator;
this.encoder = encoder;
this.skipMetadata = encoder.SkipMetadata;
this.colorTableMode = encoder.ColorTableMode;
this.pixelSamplingStrategy = encoder.PixelSamplingStrategy;
this.backgroundColor = encoder.BackgroundColor;
this.repeatCount = encoder.RepeatCount;
this.transparentColorMode = encoder.TransparentColorMode;
}
/// <summary>
/// Encodes the image to the specified stream from the <see cref="Image{TPixel}"/>.
/// </summary>
/// <typeparam name="TPixel">The pixel format.</typeparam>
/// <param name="image">The <see cref="Image{TPixel}"/> to encode from.</param>
/// <param name="stream">The <see cref="Stream"/> to encode the image data to.</param>
/// <param name="cancellationToken">The token to request cancellation.</param>
public void Encode<TPixel>(Image<TPixel> image, Stream stream, CancellationToken cancellationToken)
where TPixel : unmanaged, IPixel<TPixel>
{
Guard.NotNull(image, nameof(image));
Guard.NotNull(stream, nameof(stream));
GifMetadata gifMetadata = image.Metadata.CloneGifMetadata();
this.colorTableMode ??= gifMetadata.ColorTableMode;
bool useGlobalTable = this.colorTableMode == FrameColorTableMode.Global;
bool useGlobalTableForFirstFrame = useGlobalTable;
// Work out if there is an explicit transparent index set for the frame. We use that to ensure the
// correct value is set for the background index when quantizing.
GifFrameMetadata frameMetadata = GetGifFrameMetadata(image.Frames.RootFrame, -1);
if (frameMetadata.ColorTableMode == FrameColorTableMode.Local)
{
useGlobalTableForFirstFrame = false;
}
// Quantize the first image frame returning a palette.
IndexedImageFrame<TPixel>? quantized = null;
IQuantizer? globalQuantizer = this.encoder.Quantizer;
TransparentColorMode mode = this.transparentColorMode;
// Create a new quantizer options instance augmenting the transparent color mode to match the encoder.
QuantizerOptions options = (this.encoder.Quantizer?.Options ?? new QuantizerOptions()).DeepClone(o => o.TransparentColorMode = mode);
if (globalQuantizer is null)
{
// Is this a gif with color information. If so use that, otherwise use octree.
if (gifMetadata.ColorTableMode == FrameColorTableMode.Global && gifMetadata.GlobalColorTable?.Length > 0)
{
int ti = GetTransparentIndex(quantized, frameMetadata);
if (ti >= 0 || gifMetadata.GlobalColorTable.Value.Length < 256)
{
// We avoid dithering by default to preserve the original colors.
globalQuantizer = new PaletteQuantizer(
gifMetadata.GlobalColorTable.Value,
options.DeepClone(o => o.Dither = null),
ti,
Color.Transparent);
}
else
{
globalQuantizer = new OctreeQuantizer(options);
}
}
else
{
globalQuantizer = new OctreeQuantizer(options);
}
}
// Quantize the first frame.
IPixelSamplingStrategy strategy = this.pixelSamplingStrategy;
ImageFrame<TPixel> encodingFrame = image.Frames.RootFrame;
if (useGlobalTableForFirstFrame)
{
using IQuantizer<TPixel> firstFrameQuantizer = globalQuantizer.CreatePixelSpecificQuantizer<TPixel>(this.configuration, options);
if (useGlobalTable)
{
firstFrameQuantizer.BuildPalette(strategy, image);
}
else
{
firstFrameQuantizer.BuildPalette(strategy, encodingFrame);
}
quantized = firstFrameQuantizer.QuantizeFrame(encodingFrame, encodingFrame.Bounds);
}
else
{
quantized = this.QuantizeFrameAndUpdateMetadata(
encodingFrame,
globalQuantizer,
default,
encodingFrame.Bounds,
frameMetadata,
true,
false,
frameMetadata.HasTransparency ? frameMetadata.TransparencyIndex : -1,
Color.Transparent);
}
// Write the header.
WriteHeader(stream);
// Write the LSD.
int transparencyIndex = GetTransparentIndex(quantized, null);
if (transparencyIndex >= 0)
{
frameMetadata.HasTransparency = true;
frameMetadata.TransparencyIndex = ClampIndex(transparencyIndex);
}
byte backgroundIndex = GetBackgroundIndex(quantized, gifMetadata, this.backgroundColor);
// Get the number of bits.
int bitDepth = ColorNumerics.GetBitsNeededForColorDepth(quantized.Palette.Length);
this.WriteLogicalScreenDescriptor(image.Metadata, image.Width, image.Height, backgroundIndex, useGlobalTable, bitDepth, stream);
if (useGlobalTable)
{
this.WriteColorTable(quantized, bitDepth, stream);
}
if (!this.skipMetadata)
{
// Write the comments.
this.WriteComments(gifMetadata, stream);
// Write application extensions.
XmpProfile? xmpProfile = image.Metadata.XmpProfile ?? image.Frames.RootFrame.Metadata.XmpProfile;
this.WriteApplicationExtensions(stream, image.Frames.Count, this.repeatCount ?? gifMetadata.RepeatCount, xmpProfile);
}
// If the token is cancelled during encoding of frames we must ensure the
// quantized frame is disposed.
try
{
this.EncodeFirstFrame(stream, frameMetadata, quantized, cancellationToken);
// Capture the global palette for reuse on subsequent frames and cleanup the quantized frame.
TPixel[] globalPalette = image.Frames.Count == 1 ? [] : quantized.Palette.ToArray();
if (image.Frames.Count > 1)
{
using PaletteQuantizer<TPixel> globalFrameQuantizer = new(this.configuration, globalQuantizer.Options, quantized.Palette.ToArray());
this.EncodeAdditionalFrames(
stream,
image,
globalQuantizer,
globalFrameQuantizer,
transparencyIndex,
frameMetadata.DisposalMode,
cancellationToken);
}
}
finally
{
stream.WriteByte(GifConstants.EndIntroducer);
quantized?.Dispose();
}
}
private static GifFrameMetadata GetGifFrameMetadata<TPixel>(ImageFrame<TPixel> frame, int transparencyIndex)
where TPixel : unmanaged, IPixel<TPixel>
{
GifFrameMetadata metadata = frame.Metadata.CloneGifMetadata();
if (metadata.ColorTableMode == FrameColorTableMode.Global && transparencyIndex > -1)
{
metadata.HasTransparency = true;
metadata.TransparencyIndex = ClampIndex(transparencyIndex);
}
return metadata;
}
private void EncodeAdditionalFrames<TPixel>(
Stream stream,
Image<TPixel> image,
IQuantizer globalQuantizer,
PaletteQuantizer<TPixel> globalFrameQuantizer,
int globalTransparencyIndex,
FrameDisposalMode previousDisposalMode,
CancellationToken cancellationToken)
where TPixel : unmanaged, IPixel<TPixel>
{
// Store the first frame as a reference for de-duplication comparison.
ImageFrame<TPixel> previousFrame = image.Frames.RootFrame;
// This frame is reused to store de-duplicated pixel buffers.
using ImageFrame<TPixel> encodingFrame = new(previousFrame.Configuration, previousFrame.Size);
for (int i = 1; i < image.Frames.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
// Gather the metadata for this frame.
ImageFrame<TPixel> currentFrame = image.Frames[i];
ImageFrame<TPixel>? nextFrame = i < image.Frames.Count - 1 ? image.Frames[i + 1] : null;
GifFrameMetadata gifMetadata = GetGifFrameMetadata(currentFrame, globalTransparencyIndex);
bool useLocal = this.colorTableMode == FrameColorTableMode.Local || (gifMetadata.ColorTableMode == FrameColorTableMode.Local);
this.EncodeAdditionalFrame(
stream,
previousFrame,
currentFrame,
nextFrame,
encodingFrame,
globalQuantizer,
globalFrameQuantizer,
useLocal,
gifMetadata,
previousDisposalMode);
previousFrame = currentFrame;
previousDisposalMode = gifMetadata.DisposalMode;
}
}
private void EncodeFirstFrame<TPixel>(
Stream stream,
GifFrameMetadata metadata,
IndexedImageFrame<TPixel> quantized,
CancellationToken cancellationToken)
where TPixel : unmanaged, IPixel<TPixel>
{
cancellationToken.ThrowIfCancellationRequested();
this.WriteGraphicalControlExtension(metadata, stream);
Buffer2D<byte> indices = ((IPixelSource)quantized).PixelBuffer;
Rectangle interest = indices.FullRectangle();
bool useLocal = this.colorTableMode == FrameColorTableMode.Local || (metadata.ColorTableMode == FrameColorTableMode.Local);
int bitDepth = ColorNumerics.GetBitsNeededForColorDepth(quantized.Palette.Length);
this.WriteImageDescriptor(interest, useLocal, bitDepth, stream);
if (useLocal)
{
this.WriteColorTable(quantized, bitDepth, stream);
}
this.WriteImageData(indices, stream, quantized.Palette.Length, metadata.TransparencyIndex);
}
private void EncodeAdditionalFrame<TPixel>(
Stream stream,
ImageFrame<TPixel> previousFrame,
ImageFrame<TPixel> currentFrame,
ImageFrame<TPixel>? nextFrame,
ImageFrame<TPixel> encodingFrame,
IQuantizer globalQuantizer,
PaletteQuantizer<TPixel> globalFrameQuantizer,
bool useLocal,
GifFrameMetadata metadata,
FrameDisposalMode previousDisposalMode)
where TPixel : unmanaged, IPixel<TPixel>
{
// Capture any explicit transparency index from the metadata.
// We use it to determine the value to use to replace duplicate pixels.
bool useTransparency = metadata.HasTransparency;
int transparencyIndex = useTransparency ? metadata.TransparencyIndex : -1;
ImageFrame<TPixel>? previous = previousDisposalMode == FrameDisposalMode.RestoreToBackground
? null :
previousFrame;
// If the previous frame has a value we need to check the disposal mode of that frame
// to determine if we should use the background color to fill the encoding frame
// when de-duplicating.
FrameDisposalMode disposalMode = previous is null ?
metadata.DisposalMode :
previous.Metadata.GetGifMetadata().DisposalMode;
Color background = !useTransparency && disposalMode == FrameDisposalMode.RestoreToBackground
? this.backgroundColor ?? Color.Transparent
: Color.Transparent;
// Deduplicate and quantize the frame capturing only required parts.
(bool difference, Rectangle bounds) =
AnimationUtilities.DeDuplicatePixels(
this.configuration,
previous,
currentFrame,
nextFrame,
encodingFrame,
background,
true);
using IndexedImageFrame<TPixel> quantized = this.QuantizeFrameAndUpdateMetadata(
encodingFrame,
globalQuantizer,
globalFrameQuantizer,
bounds,
metadata,
useLocal,
difference,
transparencyIndex,
background);
this.WriteGraphicalControlExtension(metadata, stream);
int bitDepth = ColorNumerics.GetBitsNeededForColorDepth(quantized.Palette.Length);
this.WriteImageDescriptor(bounds, useLocal, bitDepth, stream);
if (useLocal)
{
this.WriteColorTable(quantized, bitDepth, stream);
}
Buffer2D<byte> indices = ((IPixelSource)quantized).PixelBuffer;
this.WriteImageData(indices, stream, quantized.Palette.Length, metadata.TransparencyIndex);
}
private IndexedImageFrame<TPixel> QuantizeFrameAndUpdateMetadata<TPixel>(
ImageFrame<TPixel> encodingFrame,
IQuantizer globalQuantizer,
PaletteQuantizer<TPixel> globalFrameQuantizer,
Rectangle bounds,
GifFrameMetadata metadata,
bool useLocal,
bool hasDuplicates,
int transparencyIndex,
Color transparentColor)
where TPixel : unmanaged, IPixel<TPixel>
{
IndexedImageFrame<TPixel> quantized;
if (useLocal)
{
// Reassign using the current frame and details.
if (metadata.LocalColorTable?.Length > 0)
{
// We can use the color data from the decoded metadata here.
// We avoid dithering by default to preserve the original colors.
ReadOnlyMemory<Color> palette = metadata.LocalColorTable.Value;
if (hasDuplicates && !metadata.HasTransparency)
{
// Duplicates were captured but the metadata does not have transparency.
metadata.HasTransparency = true;
if (palette.Length < 256)
{
// We can use the existing palette and set the transparent index as the length.
// decoders will ignore this value.
transparencyIndex = palette.Length;
metadata.TransparencyIndex = ClampIndex(transparencyIndex);
QuantizerOptions options = globalQuantizer.Options.DeepClone(o =>
{
o.MaxColors = palette.Length;
o.Dither = null;
});
PaletteQuantizer quantizer = new(palette, options, transparencyIndex, transparentColor);
using IQuantizer<TPixel> frameQuantizer = quantizer.CreatePixelSpecificQuantizer<TPixel>(this.configuration);
quantized = frameQuantizer.BuildPaletteAndQuantizeFrame(encodingFrame, bounds);
}
else
{
// We must quantize the frame to generate a local color table.
using IQuantizer<TPixel> frameQuantizer = globalQuantizer.CreatePixelSpecificQuantizer<TPixel>(this.configuration);
quantized = frameQuantizer.BuildPaletteAndQuantizeFrame(encodingFrame, bounds);
// The transparency index derived by the quantizer will differ from the index
// within the metadata. We need to update the metadata to reflect this.
int derivedTransparencyIndex = GetTransparentIndex(quantized, null);
metadata.TransparencyIndex = ClampIndex(derivedTransparencyIndex);
}
}
else
{
// Just use the local palette.
QuantizerOptions paletteOptions = globalQuantizer.Options.DeepClone(o =>
{
o.MaxColors = palette.Length;
o.Dither = null;
});
PaletteQuantizer quantizer = new(palette, paletteOptions, transparencyIndex, transparentColor);
using IQuantizer<TPixel> frameQuantizer = quantizer.CreatePixelSpecificQuantizer<TPixel>(this.configuration, quantizer.Options);
quantized = frameQuantizer.BuildPaletteAndQuantizeFrame(encodingFrame, bounds);
}
}
else
{
// We must quantize the frame to generate a local color table.
using IQuantizer<TPixel> frameQuantizer = globalQuantizer.CreatePixelSpecificQuantizer<TPixel>(this.configuration);
quantized = frameQuantizer.BuildPaletteAndQuantizeFrame(encodingFrame, bounds);
// The transparency index derived by the quantizer might differ from the index
// within the metadata. We need to update the metadata to reflect this.
int derivedTransparencyIndex = GetTransparentIndex(quantized, null);
if (derivedTransparencyIndex < 0)
{
// If no index is found set to the palette length, this trick allows us to fake transparency without an explicit index.
derivedTransparencyIndex = quantized.Palette.Length;
}
metadata.TransparencyIndex = ClampIndex(derivedTransparencyIndex);
if (hasDuplicates)
{
metadata.HasTransparency = true;
}
}
}
else
{
// Quantize the image using the global palette.
// Individual frames, though using the shared palette, can use a different transparent index
// to represent transparency.
// A difference was captured but the metadata does not have transparency.
if (hasDuplicates && !metadata.HasTransparency)
{
metadata.HasTransparency = true;
transparencyIndex = globalFrameQuantizer.Palette.Length;
metadata.TransparencyIndex = ClampIndex(transparencyIndex);
}
globalFrameQuantizer.SetTransparencyIndex(transparencyIndex, transparentColor.ToPixel<TPixel>());
quantized = globalFrameQuantizer.QuantizeFrame(encodingFrame, bounds);
}
return quantized;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static byte ClampIndex(int value) => (byte)Numerics.Clamp(value, byte.MinValue, byte.MaxValue);
/// <summary>
/// Returns the index of the transparent color in the palette.
/// </summary>
/// <param name="quantized">The current quantized frame.</param>
/// <param name="metadata">The current gif frame metadata.</param>
/// <typeparam name="TPixel">The pixel format.</typeparam>
/// <returns>The <see cref="int"/>.</returns>
private static int GetTransparentIndex<TPixel>(IndexedImageFrame<TPixel>? quantized, GifFrameMetadata? metadata)
where TPixel : unmanaged, IPixel<TPixel>
{
if (metadata?.HasTransparency == true)
{
return metadata.TransparencyIndex;
}
int index = -1;
if (quantized != null)
{
TPixel transparentPixel = TPixel.FromScaledVector4(Vector4.Zero);
ReadOnlySpan<TPixel> palette = quantized.Palette.Span;
// Transparent pixels are much more likely to be found at the end of a palette.
for (int i = palette.Length - 1; i >= 0; i--)
{
if (palette[i].Equals(transparentPixel))
{
index = i;
}
}
}
return index;
}
/// <summary>
/// Returns the index of the background color in the palette.
/// </summary>
/// <param name="quantized">The current quantized frame.</param>
/// <param name="metadata">The gif metadata</param>
/// <param name="background">The background color to match.</param>
/// <typeparam name="TPixel">The pixel format.</typeparam>
/// <returns>The <see cref="byte"/> index of the background color.</returns>
private static byte GetBackgroundIndex<TPixel>(IndexedImageFrame<TPixel>? quantized, GifMetadata metadata, Color? background)
where TPixel : unmanaged, IPixel<TPixel>
{
int match = -1;
if (quantized != null)
{
if (background.HasValue)
{
TPixel backgroundPixel = background.Value.ToPixel<TPixel>();
ReadOnlySpan<TPixel> palette = quantized.Palette.Span;
for (int i = 0; i < palette.Length; i++)
{
if (!backgroundPixel.Equals(palette[i]))
{
continue;
}
match = i;
break;
}
}
else if (metadata.BackgroundColorIndex < quantized.Palette.Length)
{
match = metadata.BackgroundColorIndex;
}
}
return ClampIndex(match);
}
/// <summary>
/// Writes the file header signature and version to the stream.
/// </summary>
/// <param name="stream">The stream to write to.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void WriteHeader(Stream stream) => stream.Write(GifConstants.MagicNumber);
/// <summary>
/// Writes the logical screen descriptor to the stream.
/// </summary>
/// <param name="metadata">The image metadata.</param>
/// <param name="width">The image width.</param>
/// <param name="height">The image height.</param>
/// <param name="backgroundIndex">The index to set the default background index to.</param>
/// <param name="useGlobalTable">Whether to use a global or local color table.</param>
/// <param name="bitDepth">The bit depth of the color palette.</param>
/// <param name="stream">The stream to write to.</param>
private void WriteLogicalScreenDescriptor(
ImageMetadata metadata,
int width,
int height,
byte backgroundIndex,
bool useGlobalTable,
int bitDepth,
Stream stream)
{
byte packedValue = GifLogicalScreenDescriptor.GetPackedValue(useGlobalTable, bitDepth - 1, false, bitDepth - 1);
// The Pixel Aspect Ratio is defined to be the quotient of the pixel's
// width over its height. The value range in this field allows
// specification of the widest pixel of 4:1 to the tallest pixel of
// 1:4 in increments of 1/64th.
//
// Values : 0 - No aspect ratio information is given.
// 1..255 - Value used in the computation.
//
// Aspect Ratio = (Pixel Aspect Ratio + 15) / 64
byte ratio = 0;
if (metadata.ResolutionUnits == PixelResolutionUnit.AspectRatio)
{
double hr = metadata.HorizontalResolution;
double vr = metadata.VerticalResolution;
if (hr != vr)
{
if (hr > vr)
{
ratio = (byte)((hr * 64) - 15);
}
else
{
ratio = (byte)((1 / vr * 64) - 15);
}
}
}
GifLogicalScreenDescriptor descriptor = new(
width: (ushort)width,
height: (ushort)height,
packed: packedValue,
backgroundColorIndex: backgroundIndex,
ratio);
Span<byte> buffer = stackalloc byte[20];
descriptor.WriteTo(buffer);
stream.Write(buffer, 0, GifLogicalScreenDescriptor.Size);
}
/// <summary>
/// Writes the application extension to the stream.
/// </summary>
/// <param name="stream">The stream to write to.</param>
/// <param name="frameCount">The frame count fo this image.</param>
/// <param name="repeatCount">The animated image repeat count.</param>
/// <param name="xmpProfile">The XMP metadata profile. Null if profile is not to be written.</param>
private void WriteApplicationExtensions(Stream stream, int frameCount, ushort repeatCount, XmpProfile? xmpProfile)
{
// Application Extension: Loop repeat count.
if (frameCount > 1 && repeatCount != 1)
{
GifNetscapeLoopingApplicationExtension loopingExtension = new(repeatCount);
this.WriteExtension(loopingExtension, stream);
}
// Application Extension: XMP Profile.
if (xmpProfile != null)
{
GifXmpApplicationExtension xmpExtension = new(xmpProfile.Data!);
this.WriteExtension(xmpExtension, stream);
}
}
/// <summary>
/// Writes the image comments to the stream.
/// </summary>
/// <param name="metadata">The metadata to be extract the comment data.</param>
/// <param name="stream">The stream to write to.</param>
private void WriteComments(GifMetadata metadata, Stream stream)
{
if (metadata.Comments.Count == 0)
{
return;
}
Span<byte> buffer = stackalloc byte[2];
for (int i = 0; i < metadata.Comments.Count; i++)
{
string comment = metadata.Comments[i];
buffer[1] = GifConstants.CommentLabel;
buffer[0] = GifConstants.ExtensionIntroducer;
stream.Write(buffer);
// Comment will be stored in chunks of 255 bytes, if it exceeds this size.
ReadOnlySpan<char> commentSpan = comment.AsSpan();
int idx = 0;
for (;
idx <= comment.Length - GifConstants.MaxCommentSubBlockLength;
idx += GifConstants.MaxCommentSubBlockLength)
{
WriteCommentSubBlock(stream, commentSpan, idx, GifConstants.MaxCommentSubBlockLength);
}
// Write the length bytes, if any, to another sub block.
if (idx < comment.Length)
{
int remaining = comment.Length - idx;
WriteCommentSubBlock(stream, commentSpan, idx, remaining);
}
stream.WriteByte(GifConstants.Terminator);
}
}
/// <summary>
/// Writes a comment sub-block to the stream.
/// </summary>
/// <param name="stream">The stream to write to.</param>
/// <param name="commentSpan">Comment as a Span.</param>
/// <param name="idx">Current start index.</param>
/// <param name="length">The length of the string to write. Should not exceed 255 bytes.</param>
private static void WriteCommentSubBlock(Stream stream, ReadOnlySpan<char> commentSpan, int idx, int length)
{
string subComment = commentSpan.Slice(idx, length).ToString();
byte[] subCommentBytes = GifConstants.Encoding.GetBytes(subComment);
stream.WriteByte((byte)length);
stream.Write(subCommentBytes, 0, length);
}
/// <summary>
/// Writes the optional graphics control extension to the stream.
/// </summary>
/// <param name="metadata">The metadata of the image or frame.</param>
/// <param name="stream">The stream to write to.</param>
private void WriteGraphicalControlExtension(GifFrameMetadata metadata, Stream stream)
{
bool hasTransparency = metadata.HasTransparency;
byte packedValue = GifGraphicControlExtension.GetPackedValue(
disposalMode: metadata.DisposalMode,
transparencyFlag: hasTransparency);
GifGraphicControlExtension extension = new(
packed: packedValue,
delayTime: (ushort)metadata.FrameDelay,
transparencyIndex: hasTransparency ? metadata.TransparencyIndex : byte.MinValue);
this.WriteExtension(extension, stream);
}
/// <summary>
/// Writes the provided extension to the stream.
/// </summary>
/// <typeparam name="TGifExtension">The type of gif extension.</typeparam>
/// <param name="extension">The extension to write to the stream.</param>
/// <param name="stream">The stream to write to.</param>
private void WriteExtension<TGifExtension>(TGifExtension extension, Stream stream)
where TGifExtension : struct, IGifExtension
{
int extensionSize = extension.ContentLength;
if (extensionSize == 0)
{
return;
}
IMemoryOwner<byte>? owner = null;
scoped Span<byte> extensionBuffer = []; // workaround compiler limitation
if (extensionSize > 128)
{
owner = this.memoryAllocator.Allocate<byte>(extensionSize + 3);
extensionBuffer = owner.GetSpan();
}
else
{
extensionBuffer = stackalloc byte[extensionSize + 3];
}
extensionBuffer[0] = GifConstants.ExtensionIntroducer;
extensionBuffer[1] = extension.Label;
extension.WriteTo(extensionBuffer[2..]);
extensionBuffer[extensionSize + 2] = GifConstants.Terminator;
stream.Write(extensionBuffer, 0, extensionSize + 3);
owner?.Dispose();
}
/// <summary>
/// Writes the image frame descriptor to the stream.
/// </summary>
/// <param name="rectangle">The frame location and size.</param>
/// <param name="hasColorTable">Whether to use the global color table.</param>
/// <param name="bitDepth">The bit depth of the color palette.</param>
/// <param name="stream">The stream to write to.</param>
private void WriteImageDescriptor(Rectangle rectangle, bool hasColorTable, int bitDepth, Stream stream)
{
byte packedValue = GifImageDescriptor.GetPackedValue(
localColorTableFlag: hasColorTable,
interfaceFlag: false,
sortFlag: false,
localColorTableSize: bitDepth - 1);
GifImageDescriptor descriptor = new(
left: (ushort)rectangle.X,
top: (ushort)rectangle.Y,
width: (ushort)rectangle.Width,
height: (ushort)rectangle.Height,
packed: packedValue);
Span<byte> buffer = stackalloc byte[20];
descriptor.WriteTo(buffer);
stream.Write(buffer, 0, GifImageDescriptor.Size);
}
/// <summary>
/// Writes the color table to the stream.
/// </summary>
/// <typeparam name="TPixel">The pixel format.</typeparam>
/// <param name="image">The <see cref="ImageFrame{TPixel}"/> to encode.</param>
/// <param name="bitDepth">The bit depth of the color palette.</param>
/// <param name="stream">The stream to write to.</param>
private void WriteColorTable<TPixel>(IndexedImageFrame<TPixel> image, int bitDepth, Stream stream)
where TPixel : unmanaged, IPixel<TPixel>
{
// The maximum number of colors for the bit depth
int colorTableLength = ColorNumerics.GetColorCountForBitDepth(bitDepth) * Unsafe.SizeOf<Rgb24>();
using IMemoryOwner<byte> colorTable = this.memoryAllocator.Allocate<byte>(colorTableLength, AllocationOptions.Clean);
Span<byte> colorTableSpan = colorTable.GetSpan();
PixelOperations<TPixel>.Instance.ToRgb24Bytes(
this.configuration,
image.Palette.Span,
colorTableSpan,
image.Palette.Length);
stream.Write(colorTableSpan);
}
/// <summary>
/// Writes the image pixel data to the stream.
/// </summary>
/// <param name="indices">The <see cref="Buffer2DRegion{Byte}"/> containing indexed pixels.</param>
/// <param name="stream">The stream to write to.</param>
/// <param name="paletteLength">The length of the frame color palette.</param>
/// <param name="transparencyIndex">The index of the color used to represent transparency.</param>
private void WriteImageData(Buffer2D<byte> indices, Stream stream, int paletteLength, int transparencyIndex)
{
// Pad the bit depth when required for encoding the image data.
// This is a common trick which allows to use out of range indexes for transparency and avoid allocating a larger color palette
// as decoders skip indexes that are out of range.
int padding = transparencyIndex >= paletteLength
? 1
: 0;
using LzwEncoder encoder = new(this.memoryAllocator, ColorNumerics.GetBitsNeededForColorDepth(paletteLength + padding));
encoder.Encode(indices, stream);
}
}
| GifEncoderCore |
csharp | files-community__Files | src/Files.App.Controls/Toolbar/Primitives/ToolbarLayout.cs | {
"start": 140,
"end": 1828
} | public partial class ____ : NonVirtualizingLayout
{
private Size m_availableSize;
public ToolbarLayout()
{
}
private int GetItemCount(NonVirtualizingLayoutContext context)
{
return context.Children.Count;
}
private UIElement GetElementAt(NonVirtualizingLayoutContext context, int index)
{
return context.Children[index];
}
// Measuring is performed in a single step, every element is measured, including the overflow button
// item, but the total amount of space needed is only composed of the Toolbar Items
protected override Size MeasureOverride(NonVirtualizingLayoutContext context, Size availableSize)
{
m_availableSize = availableSize;
Size accumulatedItemsSize = new(0, 0);
for (int i = 0; i < GetItemCount(context); ++i)
{
//var toolbarItem = (ToolbarItem)GetElementAt(context, i);
//toolbarItem.Measure( availableSize );
if (i != 0)
{
//accumulatedItemsSize.Width += toolbarItem.DesiredSize.Width;
//accumulatedItemsSize.Height = Math.Max( accumulatedItemsSize.Height , toolbarItem.DesiredSize.Height );
}
}
if (accumulatedItemsSize.Width > availableSize.Width)
{
}
else
{
}
return accumulatedItemsSize;
}
private void ArrangeItem(UIElement breadcrumbItem, ref float accumulatedWidths, float maxElementHeight)
{
}
// Arranging is performed in a single step, as many elements are tried to be drawn going from the last element
// towards the first one, if there's not enough space, then the ellipsis button is drawn
protected override Size ArrangeOverride(NonVirtualizingLayoutContext context, Size finalSize)
{
return finalSize;
}
}
}
| ToolbarLayout |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Fusion-vnext/src/Fusion.Execution/Planning/OperationPlanner.ForwardVariableRewriter.cs | {
"start": 122,
"end": 248
} | partial class ____
{
private static readonly ForwardVariableRewriter s_forwardVariableRewriter = new();
| OperationPlanner |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Media/IMediaMarker.cs | {
"start": 288,
"end": 997
} | public partial interface ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
string MediaMarkerType
{
get;
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
string Text
{
get;
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
global::System.TimeSpan Time
{
get;
}
#endif
// Forced skipping of method Windows.Media.IMediaMarker.Time.get
// Forced skipping of method Windows.Media.IMediaMarker.MediaMarkerType.get
// Forced skipping of method Windows.Media.IMediaMarker.Text.get
}
}
| IMediaMarker |
csharp | bitwarden__server | src/Api/Billing/Models/Requests/Payment/TokenizedPaymentMethodRequest.cs | {
"start": 93,
"end": 480
} | public class ____ : MinimalTokenizedPaymentMethodRequest
{
public MinimalBillingAddressRequest? BillingAddress { get; set; }
public new (TokenizedPaymentMethod, BillingAddress?) ToDomain()
{
var paymentMethod = base.ToDomain();
var billingAddress = BillingAddress?.ToDomain();
return (paymentMethod, billingAddress);
}
}
| TokenizedPaymentMethodRequest |
csharp | ServiceStack__ServiceStack | ServiceStack.Aws/src/ServiceStack.Aws/DynamoDb/DynamoDbCacheClient.cs | {
"start": 8493,
"end": 8731
} | public class ____
{
public string Id { get; set; }
public string Data { get; set; }
public DateTime? ExpiryDate { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
} | CacheEntry |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL/Introspection/ISchemaFilter.cs | {
"start": 4765,
"end": 5056
} | public class ____ : DefaultSchemaFilter
{
/// <inheritdoc/>
public override Task<bool> AllowType(IGraphType type) => Allowed;
/// <inheritdoc/>
public override Task<bool> AllowField(IGraphType parent, IFieldType field) => Allowed;
}
| ExperimentalIntrospectionFeaturesSchemaFilter |
csharp | nopSolutions__nopCommerce | src/Plugins/Nop.Plugin.Pickup.PickupInStore/Data/Migrations/LonLatUpdateMigration.cs | {
"start": 304,
"end": 1008
} | public class ____ : MigrationBase
{
#region Methods
/// <summary>
/// Collect the UP migration expressions
/// </summary>
public override void Up()
{
Alter.Table(nameof(StorePickupPoint))
.AlterColumn(nameof(StorePickupPoint.Latitude))
.AsDecimal(18, 8)
.Nullable();
Alter.Table(nameof(StorePickupPoint))
.AlterColumn(nameof(StorePickupPoint.Longitude))
.AsDecimal(18, 8)
.Nullable();
}
/// <summary>
/// Collects the DOWN migration expressions
/// </summary>
public override void Down()
{
//nothing
}
#endregion
}
| LonLatUpdateMigration |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 307357,
"end": 307577
} | public class ____
{
public int Id { get; set; }
public RelatedEntity1411 ParentEntity { get; set; }
public IEnumerable<RelatedEntity1413> ChildEntities { get; set; }
}
| RelatedEntity1412 |
csharp | dotnet__efcore | src/EFCore.Relational/Metadata/RuntimeSequence.cs | {
"start": 477,
"end": 4924
} | public class ____ : AnnotatableBase, ISequence
{
private readonly string? _schema;
private readonly Type _type;
private readonly long _startValue;
private readonly int _incrementBy;
private readonly long? _minValue;
private readonly long? _maxValue;
private readonly bool _isCyclic;
private readonly bool _modelSchemaIsNull;
/// <summary>
/// Initializes a new instance of the <see cref="RuntimeSequence" /> class.
/// </summary>
/// <param name="name">The sequence name.</param>
/// <param name="model">The model.</param>
/// <param name="type">The type of values generated.</param>
/// <param name="schema">The schema.</param>
/// <param name="startValue">The initial value.</param>
/// <param name="incrementBy">The value increment.</param>
/// <param name="cyclic">Whether the sequence is cyclic.</param>
/// <param name="minValue">The minimum value.</param>
/// <param name="maxValue">The maximum value.</param>
/// <param name="modelSchemaIsNull">A value indicating whether <see cref="ModelSchema" /> is null.</param>
public RuntimeSequence(
string name,
RuntimeModel model,
Type type,
string? schema = null,
long startValue = Sequence.DefaultStartValue,
int incrementBy = Sequence.DefaultIncrementBy,
bool cyclic = false,
long? minValue = null,
long? maxValue = null,
bool modelSchemaIsNull = false)
{
Model = model;
Name = name;
_schema = schema;
_type = type;
_startValue = startValue;
_incrementBy = incrementBy;
_isCyclic = cyclic;
_minValue = minValue;
_maxValue = maxValue;
_modelSchemaIsNull = modelSchemaIsNull;
}
/// <summary>
/// Gets the model in which this sequence is defined.
/// </summary>
public virtual RuntimeModel Model { get; }
/// <summary>
/// Gets the name of the sequence in the database.
/// </summary>
public virtual string Name { get; }
/// <summary>
/// Gets the metadata schema of the sequence.
/// </summary>
public virtual string? ModelSchema
=> _modelSchemaIsNull ? null : _schema;
/// <summary>
/// Gets the database schema that contains the sequence.
/// </summary>
public virtual string? Schema
=> _schema;
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>A string that represents the current object.</returns>
public override string ToString()
=> ((ISequence)this).ToDebugString(MetadataDebugStringOptions.SingleLineDefault);
/// <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>
[EntityFrameworkInternal]
public virtual DebugView DebugView
=> new(
() => ((ISequence)this).ToDebugString(),
() => ((ISequence)this).ToDebugString(MetadataDebugStringOptions.LongDefault));
/// <inheritdoc />
IReadOnlyModel IReadOnlySequence.Model
{
[DebuggerStepThrough]
get => Model;
}
/// <inheritdoc />
IModel ISequence.Model
{
[DebuggerStepThrough]
get => Model;
}
/// <inheritdoc />
long IReadOnlySequence.StartValue
{
[DebuggerStepThrough]
get => _startValue;
}
/// <inheritdoc />
int IReadOnlySequence.IncrementBy
{
[DebuggerStepThrough]
get => _incrementBy;
}
/// <inheritdoc />
long? IReadOnlySequence.MinValue
{
[DebuggerStepThrough]
get => _minValue;
}
/// <inheritdoc />
long? IReadOnlySequence.MaxValue
{
[DebuggerStepThrough]
get => _maxValue;
}
/// <inheritdoc />
Type IReadOnlySequence.Type
{
[DebuggerStepThrough]
get => _type;
}
/// <inheritdoc />
bool IReadOnlySequence.IsCyclic
{
[DebuggerStepThrough]
get => _isCyclic;
}
}
| RuntimeSequence |
csharp | aspnetboilerplate__aspnetboilerplate | src/Abp.AspNetCore/AspNetCore/Mvc/Results/AbpResultFilter.cs | {
"start": 327,
"end": 2155
} | public class ____ : IResultFilter, ITransientDependency
{
private readonly IAbpAspNetCoreConfiguration _configuration;
private readonly IAbpActionResultWrapperFactory _actionResultWrapperFactory;
private readonly IAbpWebCommonModuleConfiguration _abpWebCommonModuleConfiguration;
public AbpResultFilter(IAbpAspNetCoreConfiguration configuration,
IAbpActionResultWrapperFactory actionResultWrapper,
IAbpWebCommonModuleConfiguration abpWebCommonModuleConfiguration)
{
_configuration = configuration;
_actionResultWrapperFactory = actionResultWrapper;
_abpWebCommonModuleConfiguration = abpWebCommonModuleConfiguration;
}
public virtual void OnResultExecuting(ResultExecutingContext context)
{
if (!context.ActionDescriptor.IsControllerAction())
{
return;
}
var methodInfo = context.ActionDescriptor.GetMethodInfo();
var displayUrl = context.HttpContext.Request.GetDisplayUrl();
if (_abpWebCommonModuleConfiguration.WrapResultFilters.HasFilterForWrapOnSuccess(displayUrl, out var wrapOnSuccess))
{
if (!wrapOnSuccess)
{
return;
}
_actionResultWrapperFactory.CreateFor(context).Wrap(context);
return;
}
var wrapResultAttribute =
ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault(
methodInfo,
_configuration.DefaultWrapResultAttribute
);
if (!wrapResultAttribute.WrapOnSuccess)
{
return;
}
_actionResultWrapperFactory.CreateFor(context).Wrap(context);
}
public virtual void OnResultExecuted(ResultExecutedContext context)
{
//no action
}
} | AbpResultFilter |
csharp | bitwarden__server | test/Core.Test/AdminConsole/OrganizationFeatures/Policies/SavePolicyCommandTests.cs | {
"start": 742,
"end": 18012
} | public class ____
{
[Theory, BitAutoData]
public async Task SaveAsync_NewPolicy_Success([PolicyUpdate(PolicyType.SingleOrg)] PolicyUpdate policyUpdate)
{
var fakePolicyValidator = new FakeSingleOrgPolicyValidator();
fakePolicyValidator.ValidateAsyncMock(policyUpdate, null).Returns("");
var sutProvider = SutProviderFactory([fakePolicyValidator]);
ArrangeOrganization(sutProvider, policyUpdate);
sutProvider.GetDependency<IPolicyRepository>().GetManyByOrganizationIdAsync(policyUpdate.OrganizationId).Returns([]);
var creationDate = sutProvider.GetDependency<FakeTimeProvider>().Start;
await sutProvider.Sut.SaveAsync(policyUpdate);
await fakePolicyValidator.ValidateAsyncMock.Received(1).Invoke(policyUpdate, null);
fakePolicyValidator.OnSaveSideEffectsAsyncMock.Received(1).Invoke(policyUpdate, null);
await AssertPolicySavedAsync(sutProvider, policyUpdate);
await sutProvider.GetDependency<IPolicyRepository>().Received(1).UpsertAsync(Arg.Is<Policy>(p =>
p.CreationDate == creationDate &&
p.RevisionDate == creationDate));
}
[Theory, BitAutoData]
public async Task SaveAsync_ExistingPolicy_Success(
[PolicyUpdate(PolicyType.SingleOrg)] PolicyUpdate policyUpdate,
[Policy(PolicyType.SingleOrg, false)] Policy currentPolicy)
{
var fakePolicyValidator = new FakeSingleOrgPolicyValidator();
fakePolicyValidator.ValidateAsyncMock(policyUpdate, null).Returns("");
var sutProvider = SutProviderFactory([fakePolicyValidator]);
currentPolicy.OrganizationId = policyUpdate.OrganizationId;
sutProvider.GetDependency<IPolicyRepository>()
.GetByOrganizationIdTypeAsync(policyUpdate.OrganizationId, policyUpdate.Type)
.Returns(currentPolicy);
ArrangeOrganization(sutProvider, policyUpdate);
sutProvider.GetDependency<IPolicyRepository>()
.GetManyByOrganizationIdAsync(policyUpdate.OrganizationId)
.Returns([currentPolicy]);
// Store mutable properties separately to assert later
var id = currentPolicy.Id;
var organizationId = currentPolicy.OrganizationId;
var type = currentPolicy.Type;
var creationDate = currentPolicy.CreationDate;
var revisionDate = sutProvider.GetDependency<FakeTimeProvider>().Start;
await sutProvider.Sut.SaveAsync(policyUpdate);
await fakePolicyValidator.ValidateAsyncMock.Received(1).Invoke(policyUpdate, currentPolicy);
fakePolicyValidator.OnSaveSideEffectsAsyncMock.Received(1).Invoke(policyUpdate, currentPolicy);
await AssertPolicySavedAsync(sutProvider, policyUpdate);
// Additional assertions to ensure certain properties have or have not been updated
await sutProvider.GetDependency<IPolicyRepository>().Received(1).UpsertAsync(Arg.Is<Policy>(p =>
p.Id == id &&
p.OrganizationId == organizationId &&
p.Type == type &&
p.CreationDate == creationDate &&
p.RevisionDate == revisionDate));
}
[Fact]
public void Constructor_DuplicatePolicyValidators_Throws()
{
var exception = Assert.Throws<Exception>(() =>
new SavePolicyCommand(
Substitute.For<IApplicationCacheService>(),
Substitute.For<IEventService>(),
Substitute.For<IPolicyRepository>(),
[new FakeSingleOrgPolicyValidator(), new FakeSingleOrgPolicyValidator()],
Substitute.For<TimeProvider>(),
Substitute.For<IPostSavePolicySideEffect>()));
Assert.Contains("Duplicate PolicyValidator for SingleOrg policy", exception.Message);
}
[Theory, BitAutoData]
public async Task SaveAsync_OrganizationDoesNotExist_ThrowsBadRequest([PolicyUpdate(PolicyType.ActivateAutofill)] PolicyUpdate policyUpdate)
{
var sutProvider = SutProviderFactory();
sutProvider.GetDependency<IApplicationCacheService>()
.GetOrganizationAbilityAsync(policyUpdate.OrganizationId)
.Returns(Task.FromResult<OrganizationAbility?>(null));
var badRequestException = await Assert.ThrowsAsync<BadRequestException>(
() => sutProvider.Sut.SaveAsync(policyUpdate));
Assert.Contains("Organization not found", badRequestException.Message, StringComparison.OrdinalIgnoreCase);
await AssertPolicyNotSavedAsync(sutProvider);
}
[Theory, BitAutoData]
public async Task SaveAsync_OrganizationCannotUsePolicies_ThrowsBadRequest([PolicyUpdate(PolicyType.ActivateAutofill)] PolicyUpdate policyUpdate)
{
var sutProvider = SutProviderFactory();
sutProvider.GetDependency<IApplicationCacheService>()
.GetOrganizationAbilityAsync(policyUpdate.OrganizationId)
.Returns(new OrganizationAbility
{
Id = policyUpdate.OrganizationId,
UsePolicies = false
});
var badRequestException = await Assert.ThrowsAsync<BadRequestException>(
() => sutProvider.Sut.SaveAsync(policyUpdate));
Assert.Contains("cannot use policies", badRequestException.Message, StringComparison.OrdinalIgnoreCase);
await AssertPolicyNotSavedAsync(sutProvider);
}
[Theory, BitAutoData]
public async Task SaveAsync_RequiredPolicyIsNull_Throws(
[PolicyUpdate(PolicyType.RequireSso)] PolicyUpdate policyUpdate)
{
var sutProvider = SutProviderFactory([
new FakeRequireSsoPolicyValidator(),
new FakeSingleOrgPolicyValidator()
]);
ArrangeOrganization(sutProvider, policyUpdate);
sutProvider.GetDependency<IPolicyRepository>()
.GetManyByOrganizationIdAsync(policyUpdate.OrganizationId)
.Returns([]);
var badRequestException = await Assert.ThrowsAsync<BadRequestException>(
() => sutProvider.Sut.SaveAsync(policyUpdate));
Assert.Contains("Turn on the Single organization policy because it is required for the Require single sign-on authentication policy", badRequestException.Message, StringComparison.OrdinalIgnoreCase);
await AssertPolicyNotSavedAsync(sutProvider);
}
[Theory, BitAutoData]
public async Task SaveAsync_RequiredPolicyNotEnabled_Throws(
[PolicyUpdate(PolicyType.RequireSso)] PolicyUpdate policyUpdate,
[Policy(PolicyType.SingleOrg, false)] Policy singleOrgPolicy)
{
var sutProvider = SutProviderFactory([
new FakeRequireSsoPolicyValidator(),
new FakeSingleOrgPolicyValidator()
]);
ArrangeOrganization(sutProvider, policyUpdate);
sutProvider.GetDependency<IPolicyRepository>()
.GetManyByOrganizationIdAsync(policyUpdate.OrganizationId)
.Returns([singleOrgPolicy]);
var badRequestException = await Assert.ThrowsAsync<BadRequestException>(
() => sutProvider.Sut.SaveAsync(policyUpdate));
Assert.Contains("Turn on the Single organization policy because it is required for the Require single sign-on authentication policy", badRequestException.Message, StringComparison.OrdinalIgnoreCase);
await AssertPolicyNotSavedAsync(sutProvider);
}
[Theory, BitAutoData]
public async Task SaveAsync_RequiredPolicyEnabled_Success(
[PolicyUpdate(PolicyType.RequireSso)] PolicyUpdate policyUpdate,
[Policy(PolicyType.SingleOrg)] Policy singleOrgPolicy)
{
var sutProvider = SutProviderFactory([
new FakeRequireSsoPolicyValidator(),
new FakeSingleOrgPolicyValidator()
]);
ArrangeOrganization(sutProvider, policyUpdate);
sutProvider.GetDependency<IPolicyRepository>()
.GetManyByOrganizationIdAsync(policyUpdate.OrganizationId)
.Returns([singleOrgPolicy]);
await sutProvider.Sut.SaveAsync(policyUpdate);
await AssertPolicySavedAsync(sutProvider, policyUpdate);
}
[Theory, BitAutoData]
public async Task SaveAsync_DependentPolicyIsEnabled_Throws(
[PolicyUpdate(PolicyType.SingleOrg, false)] PolicyUpdate policyUpdate,
[Policy(PolicyType.SingleOrg)] Policy currentPolicy,
[Policy(PolicyType.RequireSso)] Policy requireSsoPolicy) // depends on Single Org
{
var sutProvider = SutProviderFactory([
new FakeRequireSsoPolicyValidator(),
new FakeSingleOrgPolicyValidator()
]);
ArrangeOrganization(sutProvider, policyUpdate);
sutProvider.GetDependency<IPolicyRepository>()
.GetManyByOrganizationIdAsync(policyUpdate.OrganizationId)
.Returns([currentPolicy, requireSsoPolicy]);
var badRequestException = await Assert.ThrowsAsync<BadRequestException>(
() => sutProvider.Sut.SaveAsync(policyUpdate));
Assert.Contains("Turn off the Require single sign-on authentication policy because it requires the Single organization policy", badRequestException.Message, StringComparison.OrdinalIgnoreCase);
await AssertPolicyNotSavedAsync(sutProvider);
}
[Theory, BitAutoData]
public async Task SaveAsync_MultipleDependentPoliciesAreEnabled_Throws(
[PolicyUpdate(PolicyType.SingleOrg, false)] PolicyUpdate policyUpdate,
[Policy(PolicyType.SingleOrg)] Policy currentPolicy,
[Policy(PolicyType.RequireSso)] Policy requireSsoPolicy, // depends on Single Org
[Policy(PolicyType.MaximumVaultTimeout)] Policy vaultTimeoutPolicy) // depends on Single Org
{
var sutProvider = SutProviderFactory([
new FakeRequireSsoPolicyValidator(),
new FakeSingleOrgPolicyValidator(),
new FakeVaultTimeoutPolicyValidator()
]);
ArrangeOrganization(sutProvider, policyUpdate);
sutProvider.GetDependency<IPolicyRepository>()
.GetManyByOrganizationIdAsync(policyUpdate.OrganizationId)
.Returns([currentPolicy, requireSsoPolicy, vaultTimeoutPolicy]);
var badRequestException = await Assert.ThrowsAsync<BadRequestException>(
() => sutProvider.Sut.SaveAsync(policyUpdate));
Assert.Contains("Turn off all of the policies that require the Single organization policy", badRequestException.Message, StringComparison.OrdinalIgnoreCase);
await AssertPolicyNotSavedAsync(sutProvider);
}
[Theory, BitAutoData]
public async Task SaveAsync_DependentPolicyNotEnabled_Success(
[PolicyUpdate(PolicyType.SingleOrg, false)] PolicyUpdate policyUpdate,
[Policy(PolicyType.SingleOrg)] Policy currentPolicy,
[Policy(PolicyType.RequireSso, false)] Policy requireSsoPolicy) // depends on Single Org but is not enabled
{
var sutProvider = SutProviderFactory([
new FakeRequireSsoPolicyValidator(),
new FakeSingleOrgPolicyValidator()
]);
ArrangeOrganization(sutProvider, policyUpdate);
sutProvider.GetDependency<IPolicyRepository>()
.GetManyByOrganizationIdAsync(policyUpdate.OrganizationId)
.Returns([currentPolicy, requireSsoPolicy]);
await sutProvider.Sut.SaveAsync(policyUpdate);
await AssertPolicySavedAsync(sutProvider, policyUpdate);
}
[Theory, BitAutoData]
public async Task SaveAsync_ThrowsOnValidationError([PolicyUpdate(PolicyType.SingleOrg)] PolicyUpdate policyUpdate)
{
var fakePolicyValidator = new FakeSingleOrgPolicyValidator();
fakePolicyValidator.ValidateAsyncMock(policyUpdate, null).Returns("Validation error!");
var sutProvider = SutProviderFactory([fakePolicyValidator]);
ArrangeOrganization(sutProvider, policyUpdate);
sutProvider.GetDependency<IPolicyRepository>().GetManyByOrganizationIdAsync(policyUpdate.OrganizationId).Returns([]);
var badRequestException = await Assert.ThrowsAsync<BadRequestException>(
() => sutProvider.Sut.SaveAsync(policyUpdate));
Assert.Contains("Validation error!", badRequestException.Message, StringComparison.OrdinalIgnoreCase);
await AssertPolicyNotSavedAsync(sutProvider);
}
[Theory, BitAutoData]
public async Task VNextSaveAsync_OrganizationDataOwnershipPolicy_ExecutesPostSaveSideEffects(
[PolicyUpdate(PolicyType.OrganizationDataOwnership)] PolicyUpdate policyUpdate,
[Policy(PolicyType.OrganizationDataOwnership, false)] Policy currentPolicy)
{
// Arrange
var sutProvider = SutProviderFactory();
var savePolicyModel = new SavePolicyModel(policyUpdate);
currentPolicy.OrganizationId = policyUpdate.OrganizationId;
sutProvider.GetDependency<IPolicyRepository>()
.GetByOrganizationIdTypeAsync(policyUpdate.OrganizationId, policyUpdate.Type)
.Returns(currentPolicy);
ArrangeOrganization(sutProvider, policyUpdate);
sutProvider.GetDependency<IPolicyRepository>()
.GetManyByOrganizationIdAsync(policyUpdate.OrganizationId)
.Returns([currentPolicy]);
// Act
var result = await sutProvider.Sut.VNextSaveAsync(savePolicyModel);
// Assert
await sutProvider.GetDependency<IPolicyRepository>()
.Received(1)
.UpsertAsync(result);
await sutProvider.GetDependency<IEventService>()
.Received(1)
.LogPolicyEventAsync(result, EventType.Policy_Updated);
await sutProvider.GetDependency<IPostSavePolicySideEffect>()
.Received(1)
.ExecuteSideEffectsAsync(savePolicyModel, result, currentPolicy);
}
[Theory]
[BitAutoData(PolicyType.SingleOrg)]
[BitAutoData(PolicyType.TwoFactorAuthentication)]
public async Task VNextSaveAsync_NonOrganizationDataOwnershipPolicy_DoesNotExecutePostSaveSideEffects(
PolicyType policyType,
Policy currentPolicy,
[PolicyUpdate] PolicyUpdate policyUpdate)
{
// Arrange
policyUpdate.Type = policyType;
currentPolicy.Type = policyType;
currentPolicy.OrganizationId = policyUpdate.OrganizationId;
var sutProvider = SutProviderFactory();
var savePolicyModel = new SavePolicyModel(policyUpdate);
sutProvider.GetDependency<IPolicyRepository>()
.GetByOrganizationIdTypeAsync(policyUpdate.OrganizationId, policyUpdate.Type)
.Returns(currentPolicy);
ArrangeOrganization(sutProvider, policyUpdate);
sutProvider.GetDependency<IPolicyRepository>()
.GetManyByOrganizationIdAsync(policyUpdate.OrganizationId)
.Returns([currentPolicy]);
// Act
var result = await sutProvider.Sut.VNextSaveAsync(savePolicyModel);
// Assert
await sutProvider.GetDependency<IPolicyRepository>()
.Received(1)
.UpsertAsync(result);
await sutProvider.GetDependency<IEventService>()
.Received(1)
.LogPolicyEventAsync(result, EventType.Policy_Updated);
await sutProvider.GetDependency<IPostSavePolicySideEffect>()
.DidNotReceiveWithAnyArgs()
.ExecuteSideEffectsAsync(default!, default!, default!);
}
/// <summary>
/// Returns a new SutProvider with the PolicyValidators registered in the Sut.
/// </summary>
private static SutProvider<SavePolicyCommand> SutProviderFactory(IEnumerable<IPolicyValidator>? policyValidators = null)
{
return new SutProvider<SavePolicyCommand>()
.WithFakeTimeProvider()
.SetDependency(policyValidators ?? [])
.SetDependency(Substitute.For<IPostSavePolicySideEffect>())
.Create();
}
private static void ArrangeOrganization(SutProvider<SavePolicyCommand> sutProvider, PolicyUpdate policyUpdate)
{
sutProvider.GetDependency<IApplicationCacheService>()
.GetOrganizationAbilityAsync(policyUpdate.OrganizationId)
.Returns(new OrganizationAbility
{
Id = policyUpdate.OrganizationId,
UsePolicies = true
});
}
private static async Task AssertPolicyNotSavedAsync(SutProvider<SavePolicyCommand> sutProvider)
{
await sutProvider.GetDependency<IPolicyRepository>()
.DidNotReceiveWithAnyArgs()
.UpsertAsync(default!);
await sutProvider.GetDependency<IEventService>()
.DidNotReceiveWithAnyArgs()
.LogPolicyEventAsync(default, default);
}
private static async Task AssertPolicySavedAsync(SutProvider<SavePolicyCommand> sutProvider, PolicyUpdate policyUpdate)
{
var expectedPolicy = () => Arg.Is<Policy>(p =>
p.Type == policyUpdate.Type &&
p.OrganizationId == policyUpdate.OrganizationId &&
p.Enabled == policyUpdate.Enabled &&
p.Data == policyUpdate.Data);
await sutProvider.GetDependency<IPolicyRepository>().Received(1).UpsertAsync(expectedPolicy());
await sutProvider.GetDependency<IEventService>().Received(1)
.LogPolicyEventAsync(expectedPolicy(), EventType.Policy_Updated);
}
}
| SavePolicyCommandTests |
csharp | dotnet__aspire | src/Aspire.Hosting.Azure/api/Aspire.Hosting.Azure.cs | {
"start": 19190,
"end": 19933
} | partial class ____ : AzureProvisioningResource, IAppIdentityResource
{
public AzureUserAssignedIdentityResource(string name) : base(default!, default!) { }
public BicepOutputReference ClientId { get { throw null; } }
public BicepOutputReference Id { get { throw null; } }
public BicepOutputReference NameOutputReference { get { throw null; } }
public BicepOutputReference PrincipalId { get { throw null; } }
public BicepOutputReference PrincipalName { get { throw null; } }
public override global::Azure.Provisioning.Primitives.ProvisionableResource AddAsExistingResource(AzureResourceInfrastructure infra) { throw null; }
}
public sealed | AzureUserAssignedIdentityResource |
csharp | MassTransit__MassTransit | src/Transports/MassTransit.Azure.ServiceBus.Core/AzureServiceBusTransport/Contexts/QueueClientContext.cs | {
"start": 228,
"end": 4519
} | public class ____ :
BasePipeContext,
ClientContext,
IAsyncDisposable
{
readonly IAgent _agent;
readonly ReceiveSettings _settings;
ServiceBusProcessor _processor;
ServiceBusSessionProcessor _sessionProcessor;
public QueueClientContext(ConnectionContext connectionContext, Uri inputAddress, ReceiveSettings settings, IAgent agent)
{
_settings = settings;
_agent = agent;
ConnectionContext = connectionContext;
InputAddress = inputAddress;
}
public ConnectionContext ConnectionContext { get; }
public string EntityPath => _processor?.EntityPath ?? _sessionProcessor?.EntityPath;
public bool IsClosedOrClosing => _processor?.IsClosed ?? _sessionProcessor?.IsClosed ?? false;
public Uri InputAddress { get; }
public void OnMessageAsync(Func<ProcessMessageEventArgs, ServiceBusReceivedMessage, CancellationToken, Task> callback,
Func<ProcessErrorEventArgs, Task> exceptionHandler)
{
if (_processor != null)
throw new InvalidOperationException("OnMessageAsync can only be called once");
if (_sessionProcessor != null)
throw new InvalidOperationException("OnMessageAsync cannot be called with operating on a session");
_processor = ConnectionContext.CreateQueueProcessor(_settings);
_processor.ProcessMessageAsync += args => callback(args, args.Message, args.CancellationToken);
_processor.ProcessErrorAsync += exceptionHandler;
}
public void OnSessionAsync(Func<ProcessSessionMessageEventArgs, ServiceBusReceivedMessage, CancellationToken, Task> callback,
Func<ProcessErrorEventArgs, Task> exceptionHandler)
{
if (_sessionProcessor != null)
throw new InvalidOperationException("OnSessionAsync can only be called once");
if (_processor != null)
throw new InvalidOperationException("OnSessionAsync cannot be called with operating without a session");
_sessionProcessor = ConnectionContext.CreateQueueSessionProcessor(_settings);
_sessionProcessor.ProcessMessageAsync += args => callback(args, args.Message, args.CancellationToken);
_sessionProcessor.ProcessErrorAsync += exceptionHandler;
}
public async Task StartAsync()
{
if (_processor != null)
await _processor.StartProcessingAsync(CancellationToken).ConfigureAwait(false);
if (_sessionProcessor != null)
await _sessionProcessor.StartProcessingAsync(CancellationToken).ConfigureAwait(false);
}
public async Task ShutdownAsync()
{
try
{
if (_processor is { IsClosed: false })
await _processor.StopProcessingAsync().ConfigureAwait(false);
if (_sessionProcessor is { IsClosed: false })
await _sessionProcessor.StopProcessingAsync().ConfigureAwait(false);
}
catch (Exception exception)
{
LogContext.Warning?.Log(exception, "Stop processing client faulted: {InputAddress}", InputAddress);
}
}
public async Task CloseAsync()
{
try
{
if (_processor is { IsClosed: false })
await _processor.CloseAsync().ConfigureAwait(false);
if (_sessionProcessor is { IsClosed: false })
await _sessionProcessor.CloseAsync().ConfigureAwait(false);
}
catch (Exception exception)
{
LogContext.Warning?.Log(exception, "Close client faulted: {InputAddress}", InputAddress);
}
}
public Task NotifyFaulted(Exception exception, string entityPath)
{
Task.Run(() => _agent.Stop($"Unrecoverable exception on {entityPath}"))
.IgnoreUnobservedExceptions();
return Task.CompletedTask;
}
public async ValueTask DisposeAsync()
{
await CloseAsync().ConfigureAwait(false);
}
}
}
| QueueClientContext |
csharp | dotnet__efcore | test/EFCore.InMemory.FunctionalTests/ModelBuilding/InMemoryModelBuilderGenericRelationshipStringTest.cs | {
"start": 613,
"end": 911
} | public class ____(InMemoryModelBuilderFixture fixture) : InMemoryManyToOne(fixture)
{
protected override TestModelBuilder CreateModelBuilder(Action<ModelConfigurationBuilder>? configure)
=> new GenericStringTestModelBuilder(Fixture, configure);
}
| GenericManyToOneString |
csharp | RicoSuter__NSwag | src/NSwag.CodeGeneration/Models/ParameterModelBase.cs | {
"start": 562,
"end": 11115
} | public abstract class ____
{
private readonly OpenApiParameter _parameter;
private readonly IList<OpenApiParameter> _allParameters;
private readonly CodeGeneratorSettingsBase _settings;
private readonly IClientGenerator _generator;
private readonly TypeResolverBase _typeResolver;
private readonly IEnumerable<PropertyModel> _properties;
/// <summary>Initializes a new instance of the <see cref="ParameterModelBase" /> class.</summary>
/// <param name="parameterName">Name of the parameter.</param>
/// <param name="variableName">Name of the variable.</param>
/// <param name="typeName">The type name.</param>
/// <param name="parameter">The parameter.</param>
/// <param name="allParameters">All parameters.</param>
/// <param name="settings">The settings.</param>
/// <param name="generator">The client generator base.</param>
/// <param name="typeResolver">The type resolver.</param>
protected ParameterModelBase(string parameterName, string variableName, string typeName,
OpenApiParameter parameter, IList<OpenApiParameter> allParameters, CodeGeneratorSettingsBase settings,
IClientGenerator generator, TypeResolverBase typeResolver)
{
_allParameters = allParameters;
_parameter = parameter;
_settings = settings;
_generator = generator;
_typeResolver = typeResolver;
Type = typeName;
Name = parameterName;
VariableName = variableName;
var propertyNameGenerator = settings?.PropertyNameGenerator ?? throw new InvalidOperationException("PropertyNameGenerator not set.");
_properties = _parameter.ActualSchema.ActualProperties
.Select(p => new PropertyModel(p.Key, p.Value, propertyNameGenerator.Generate(p.Value)))
.ToList();
}
/// <summary>Gets the type of the parameter.</summary>
public string Type { get; }
/// <summary>Gets the name.</summary>
public string Name { get; }
/// <summary>Gets the variable name in (usually lowercase).</summary>
public string VariableName { get; }
/// <summary>Gets a value indicating whether a default value is available.</summary>
public bool HasDefault => Default != null;
/// <summary>The default value for the variable.</summary>
public string Default
{
get
{
if (_settings.SchemaType == SchemaType.Swagger2)
{
return !_parameter.IsRequired && _parameter.Default != null ?
_settings.ValueGenerator?.GetDefaultValue(_parameter, false, _parameter.ActualTypeSchema.Id, null, true, _typeResolver) :
null;
}
else
{
return !_parameter.IsRequired && _parameter.ActualSchema.Default != null ?
_settings.ValueGenerator?.GetDefaultValue(_parameter.ActualSchema, false, _parameter.ActualTypeSchema.Id, null, true, _typeResolver) :
null;
}
}
}
/// <summary>Gets the parameter kind.</summary>
public OpenApiParameterKind Kind => _parameter.Kind;
/// <summary>Gets the parameter style.</summary>
public OpenApiParameterStyle Style => _parameter.Style;
/// <summary>Gets the the value indicating if the parameter values should be exploded when included in the query string.</summary>
public bool? Explode => _parameter.Explode;
/// <summary>Gets a value indicating whether the parameter is a deep object (OpenAPI 3).</summary>
public bool IsDeepObject => _parameter.Style == OpenApiParameterStyle.DeepObject;
/// <summary>Gets a value indicating whether the parameter has form style.</summary>
public bool IsForm => _parameter.Style == OpenApiParameterStyle.Form;
/// <summary>Gets the contained value property names (OpenAPI 3).</summary>
public IEnumerable<PropertyModel> PropertyNames => _properties.Where(p => !p.IsCollection);
/// <summary>Gets the contained collection property names (OpenAPI 3).</summary>
public IEnumerable<PropertyModel> CollectionPropertyNames => _properties.Where(p => p.IsCollection);
/// <summary>Gets a value indicating whether the parameter has a description.</summary>
public bool HasDescription => !string.IsNullOrEmpty(Description);
/// <summary>Gets the parameter description.</summary>
public string Description => ConversionUtilities.TrimWhiteSpaces(_parameter.Description);
/// <summary>Gets the schema.</summary>
public JsonSchema Schema => _parameter.ActualSchema;
/// <summary>Gets a value indicating whether the parameter is required.</summary>
public bool IsRequired => _parameter.IsRequired;
/// <summary>Gets a value indicating whether the parameter is nullable.</summary>
public bool IsNullable => _parameter.IsNullable(_settings.SchemaType);
/// <summary>Gets a value indicating whether the parameter is optional (i.e. not required).</summary>
public bool IsOptional => !_parameter.IsRequired;
/// <summary>Gets a value indicating whether the parameter has a description or is optional.</summary>
public bool HasDescriptionOrIsOptional => HasDescription || !IsRequired;
/// <summary>Gets a value indicating whether the parameter is the last parameter of the operation.</summary>
public bool IsLast => _allParameters.LastOrDefault() == _parameter;
/// <summary>Gets a value indicating whether this is an XML body parameter.</summary>
public bool IsXmlBodyParameter => _parameter.IsXmlBodyParameter;
/// <summary>Gets a value indicating whether this is an binary body parameter.</summary>
public bool IsBinaryBodyParameter => _parameter.IsBinaryBodyParameter;
/// <summary>Gets a value indicating whether the parameter is of type date.</summary>
public bool IsDate =>
Schema.Format == JsonFormatStrings.Date &&
_generator.GetTypeName(Schema, IsNullable, null) != "string";
/// <summary>Gets a value indicating whether the parameter is of type date-time</summary>
public bool IsDateTime =>
Schema.Format == JsonFormatStrings.DateTime && _generator.GetTypeName(Schema, IsNullable, null) != "string";
/// <summary>Gets a value indicating whether the parameter is of type date-time or date</summary>
public bool IsDateOrDateTime => IsDate || IsDateTime;
/// <summary>Gets a value indicating whether the parameter is of type array.</summary>
public bool IsArray => Schema.Type.HasFlag(JsonObjectType.Array) || _parameter.CollectionFormat == OpenApiParameterCollectionFormat.Multi;
/// <summary>Gets a value indicating whether the parameter is an exploded array.</summary>
public bool IsExplodedArray => IsArray && (_settings.SchemaType == SchemaType.Swagger2
? _parameter.CollectionFormat is OpenApiParameterCollectionFormat.Multi
: Explode ?? Kind is OpenApiParameterKind.Query or OpenApiParameterKind.Cookie);
/// <summary>Gets a value indicating whether the parameter is a string array.</summary>
public bool IsStringArray => IsArray && Schema.Item?.ActualSchema.Type.HasFlag(JsonObjectType.String) == true;
/// <summary>Gets a value indicating whether this is a file parameter.</summary>
public bool IsFile => Schema.IsBinary || (IsArray && Schema?.Item?.IsBinary == true);
/// <summary>Gets a value indicating whether the parameter is a binary body parameter.</summary>
public bool IsBinaryBody => _parameter.IsBinaryBodyParameter;
/// <summary>Gets a value indicating whether a binary body parameter allows multiple mime types.</summary>
public bool HasBinaryBodyWithMultipleMimeTypes => _parameter.HasBinaryBodyWithMultipleMimeTypes;
/// <summary>Gets a value indicating whether the parameter is of type dictionary.</summary>
public bool IsDictionary => Schema.IsDictionary;
/// <summary>Gets a value indicating whether the parameter is of type date-time array.</summary>
public bool IsDateTimeArray =>
IsArray &&
Schema.Item?.ActualSchema.Format == JsonFormatStrings.DateTime &&
_generator.GetTypeName(Schema.Item.ActualSchema, IsNullable, null) != "string";
/// <summary>Gets a value indicating whether the parameter is of type date-time or date array.</summary>
public bool IsDateOrDateTimeArray => IsDateArray || IsDateTimeArray;
/// <summary>Gets a value indicating whether the parameter is of type date array.</summary>
public bool IsDateArray =>
IsArray &&
Schema.Item?.ActualSchema.Format == JsonFormatStrings.Date &&
_generator.GetTypeName(Schema.Item.ActualSchema, IsNullable, null) != "string";
/// <summary>Gets a value indicating whether the parameter is of type object array.</summary>
public bool IsObjectArray => IsArray &&
(Schema.Item?.ActualSchema.Type == JsonObjectType.Object ||
Schema.Item?.ActualSchema.IsAnyType == true);
/// <summary>Gets a value indicating whether the parameter is of type object</summary>
public bool IsObject => Schema.ActualSchema.Type == JsonObjectType.Object;
/// <summary>Gets a value indicating whether the parameter is of type object.</summary>
public bool IsBody => Kind == OpenApiParameterKind.Body;
/// <summary>Gets a value indicating whether the parameter is supplied as query parameter.</summary>
public bool IsQuery => Kind == OpenApiParameterKind.Query;
/// <summary>Gets a value indicating whether the parameter is supplied through the request headers.</summary>
public bool IsHeader => Kind == OpenApiParameterKind.Header;
/// <summary>Gets a value indicating whether the parameter allows empty values.</summary>
public bool AllowEmptyValue => _parameter.AllowEmptyValue;
/// <summary>Gets the operation extension data.</summary>
public IDictionary<string, object> ExtensionData => _parameter.ExtensionData;
}
}
| ParameterModelBase |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Internal/Scaling/RootScale.h.mux.cs | {
"start": 468,
"end": 736
} | internal enum ____
{
// Parent scale is identity or it expects the root visual tree to apply system DPI scale itself.
ParentInvert,
// Parent scale already applies the system DPI scale, so need to apply in the internal root visual tree.
ParentApply,
}
| RootScaleConfig |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json.Tests/Issues/Issue1711.cs | {
"start": 1661,
"end": 2153
} | public class ____ : TestFixtureBase
{
[Test]
public void Test_Raw()
{
FooClass c = JsonConvert.DeserializeObject<FooClass>(@"{ ""Value"" : 96.014e-05 }");
Assert.AreEqual(0.00096014m, c.Value);
}
[Test]
public void Test_String()
{
FooClass c = JsonConvert.DeserializeObject<FooClass>(@"{ ""Value"" : ""96.014e-05"" }");
Assert.AreEqual(0.00096014m, c.Value);
}
| Issue1711 |
csharp | ServiceStack__ServiceStack.OrmLite | src/ServiceStack.OrmLite.Sqlite.Windows/SqliteOrmLiteDialectProvider.cs | {
"start": 162,
"end": 250
} | public class ____ : SqliteOrmLiteDialectProvider {}
| SqliteWindowsOrmLiteDialectProvider |
csharp | smartstore__Smartstore | src/Smartstore.Core/Common/Hooks/AuditableHook.cs | {
"start": 195,
"end": 1024
} | public class ____ : AsyncDbSaveHook<IAuditable>
{
protected override Task<HookResult> OnInsertingAsync(IAuditable entity, IHookedEntity entry, CancellationToken cancelToken)
{
var now = DateTime.UtcNow;
if (entity.CreatedOnUtc == DateTime.MinValue)
{
entity.CreatedOnUtc = now;
}
if (entity.UpdatedOnUtc == DateTime.MinValue)
{
entity.UpdatedOnUtc = now;
}
return Task.FromResult(HookResult.Ok);
}
protected override Task<HookResult> OnUpdatingAsync(IAuditable entity, IHookedEntity entry, CancellationToken cancelToken)
{
entity.UpdatedOnUtc = DateTime.UtcNow;
return Task.FromResult(HookResult.Ok);
}
}
}
| AuditableHook |
csharp | dotnet__aspnetcore | src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs | {
"start": 753,
"end": 6156
} | internal class ____ : IAsyncDisposable, IStartup
{
private readonly IHost _host;
private ListenOptions _listenOptions;
private readonly RequestDelegate _app;
public TestServer(RequestDelegate app)
: this(app, new TestServiceContext())
{
}
public TestServer(RequestDelegate app, TestServiceContext context)
: this(app, context, new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0)))
{
}
public TestServer(RequestDelegate app, TestServiceContext context, ListenOptions listenOptions)
: this(app, context, options => options.CodeBackedListenOptions.Add(listenOptions), _ => { })
{
}
public TestServer(RequestDelegate app, TestServiceContext context, Action<ListenOptions> configureListenOptions, Action<IServiceCollection> configureServices = null)
: this(app, context, options =>
{
var listenOptions = new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0))
{
KestrelServerOptions = options
};
configureListenOptions(listenOptions);
options.CodeBackedListenOptions.Add(listenOptions);
}, s =>
{
configureServices?.Invoke(s);
})
{
}
public TestServer(RequestDelegate app, TestServiceContext context, Action<KestrelServerOptions> configureKestrel)
: this(app, context, configureKestrel, _ => { })
{
}
public TestServer(RequestDelegate app, TestServiceContext context, Action<KestrelServerOptions> configureKestrel, Action<IServiceCollection> configureServices)
{
_app = app;
Context = context;
_host = TransportSelector.GetHostBuilder(context.ServerOptions.Limits.MaxRequestBufferSize)
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options =>
{
configureKestrel(options);
_listenOptions = options.GetListenOptions().First();
})
.ConfigureServices(services =>
{
if (context.MemoryPoolFactory != null)
{
services.AddSingleton<IMemoryPoolFactory<byte>>(context.MemoryPoolFactory);
}
services.AddSingleton<IStartup>(this);
services.AddSingleton(context.LoggerFactory);
services.AddSingleton<IHttpsConfigurationService, HttpsConfigurationService>();
services.AddSingleton<HttpsConfigurationService.IInitializer, HttpsConfigurationService.Initializer>();
services.AddSingleton<IServer>(sp =>
{
// Manually configure options on the TestServiceContext.
// We're doing this so we can use the same instance that was passed in
var configureOptions = sp.GetServices<IConfigureOptions<KestrelServerOptions>>();
foreach (var c in configureOptions)
{
c.Configure(context.ServerOptions);
}
return new KestrelServerImpl(sp.GetServices<IConnectionListenerFactory>(), Array.Empty<IMultiplexedConnectionListenerFactory>(), sp.GetRequiredService<IHttpsConfigurationService>(), context);
});
configureServices(services);
})
.UseSetting(WebHostDefaults.ApplicationKey, typeof(TestServer).Assembly.FullName)
.UseSetting(WebHostDefaults.ShutdownTimeoutKey, TestConstants.DefaultTimeout.TotalSeconds.ToString(CultureInfo.InvariantCulture))
.Configure(app => { app.Run(_app); });
})
.ConfigureServices(services =>
{
services.Configure<HostOptions>(option =>
{
option.ShutdownTimeout = TestConstants.DefaultTimeout;
});
})
.Build();
_host.Start();
Context.Log.LogDebug($"TestServer is listening on port {Port}");
}
// Avoid NullReferenceException in the CanListenToOpenTcpSocketHandle test
public int Port => _listenOptions.IPEndPoint?.Port ?? 0;
public TestServiceContext Context { get; }
void IStartup.Configure(IApplicationBuilder app)
{
app.Run(_app);
}
IServiceProvider IStartup.ConfigureServices(IServiceCollection services)
{
// Unfortunately, this needs to be replaced in IStartup.ConfigureServices
services.AddSingleton<IHostApplicationLifetime, LifetimeNotImplemented>();
return services.BuildServiceProvider();
}
public TestConnection CreateConnection()
{
return new TestConnection(Port, _listenOptions.IPEndPoint.AddressFamily);
}
public Task StopAsync(CancellationToken token = default)
{
return _host.StopAsync(token);
}
public async ValueTask DisposeAsync()
{
await _host.StopAsync().ConfigureAwait(false);
// The concrete Host implements IAsyncDisposable
await ((IAsyncDisposable)_host).DisposeAsync().ConfigureAwait(false);
}
}
| TestServer |
csharp | files-community__Files | src/Files.App/Actions/Navigation/OpenInNewTab/OpenInNewTabAction.cs | {
"start": 140,
"end": 207
} | partial class ____ : BaseOpenInNewTabAction
{
}
}
| OpenInNewTabAction |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.OpenApi.Tests/GeneratedClient/IAssignRolesOperations.cs | {
"start": 441,
"end": 4690
} | public partial interface ____
{
/// <param name='userName'>
/// </param>
/// <param name='permissions'>
/// </param>
/// <param name='roles'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AssignRolesResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<AssignRolesResponse>> GetWithHttpMessagesAsync(string userName = default(string), string permissions = default(string), string roles = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <param name='userName'>
/// </param>
/// <param name='permissions'>
/// </param>
/// <param name='roles'>
/// </param>
/// <param name='body'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AssignRolesResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<AssignRolesResponse>> CreateWithHttpMessagesAsync(string userName = default(string), string permissions = default(string), string roles = default(string), AssignRoles body = default(AssignRoles), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <param name='userName'>
/// </param>
/// <param name='permissions'>
/// </param>
/// <param name='roles'>
/// </param>
/// <param name='body'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AssignRolesResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<AssignRolesResponse>> PostWithHttpMessagesAsync(string userName = default(string), string permissions = default(string), string roles = default(string), AssignRoles body = default(AssignRoles), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <param name='userName'>
/// </param>
/// <param name='permissions'>
/// </param>
/// <param name='roles'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="AssignRolesResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<AssignRolesResponse>> DeleteWithHttpMessagesAsync(string userName = default(string), string permissions = default(string), string roles = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| IAssignRolesOperations |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore/Modules/Overrides/HttpClient/TenantHttpClientFactory.cs | {
"start": 14048,
"end": 17189
} | public static class ____
{
public static readonly EventId CleanupCycleStart = new(100, "CleanupCycleStart");
public static readonly EventId CleanupCycleEnd = new(101, "CleanupCycleEnd");
public static readonly EventId CleanupItemFailed = new(102, "CleanupItemFailed");
public static readonly EventId HandlerExpired = new(103, "HandlerExpired");
}
private static readonly Action<ILogger, int, Exception?> _cleanupCycleStart = LoggerMessage.Define<int>(
LogLevel.Debug,
EventIds.CleanupCycleStart,
"Starting HttpMessageHandler cleanup cycle with {InitialCount} items");
private static readonly Action<ILogger, double, int, int, Exception?> _cleanupCycleEnd = LoggerMessage.Define<double, int, int>(
LogLevel.Debug,
EventIds.CleanupCycleEnd,
"Ending HttpMessageHandler cleanup cycle after {ElapsedMilliseconds}ms - processed: {DisposedCount} items - remaining: {RemainingItems} items");
private static readonly Action<ILogger, string, Exception?> _cleanupItemFailed = LoggerMessage.Define<string>(
LogLevel.Error,
EventIds.CleanupItemFailed,
"HttpMessageHandler.Dispose() threw an unhandled exception for client: '{ClientName}'");
private static readonly Action<ILogger, double, string, Exception?> _handlerExpired = LoggerMessage.Define<double, string>(
LogLevel.Debug,
EventIds.HandlerExpired,
"HttpMessageHandler expired after {HandlerLifetime}ms for client '{ClientName}'");
public static void CleanupCycleStart(Lazy<ILogger> loggerLazy, int initialCount)
{
if (TryGetLogger(loggerLazy, out var logger))
{
_cleanupCycleStart(logger, initialCount, null);
}
}
public static void CleanupCycleEnd(Lazy<ILogger> loggerLazy, TimeSpan duration, int disposedCount, int finalCount)
{
if (TryGetLogger(loggerLazy, out var logger))
{
_cleanupCycleEnd(logger, duration.TotalMilliseconds, disposedCount, finalCount, null);
}
}
public static void CleanupItemFailed(Lazy<ILogger> loggerLazy, string clientName, Exception exception)
{
if (TryGetLogger(loggerLazy, out var logger))
{
_cleanupItemFailed(logger, clientName, exception);
}
}
public static void HandlerExpired(Lazy<ILogger> loggerLazy, string clientName, TimeSpan lifetime)
{
if (TryGetLogger(loggerLazy, out var logger))
{
_handlerExpired(logger, lifetime.TotalMilliseconds, clientName, null);
}
}
private static bool TryGetLogger(Lazy<ILogger> loggerLazy, [NotNullWhen(true)] out ILogger? logger)
{
logger = null;
try
{
logger = loggerLazy.Value;
}
catch { } // Not throwing in logs.
return logger is not null;
}
}
}
| EventIds |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 290857,
"end": 291077
} | public class ____
{
public int Id { get; set; }
public RelatedEntity1336 ParentEntity { get; set; }
public IEnumerable<RelatedEntity1338> ChildEntities { get; set; }
}
| RelatedEntity1337 |
csharp | dotnet__BenchmarkDotNet | tests/BenchmarkDotNet.Tests/FullNameProviderTests.cs | {
"start": 8649,
"end": 8857
} | public class ____
{
[Params(100)]
public int Field;
[Benchmark]
[Arguments("anArgument")]
public int Method(string arg) => Field;
}
| WithArgumentsAndParameters |
csharp | grandnode__grandnode2 | src/Web/Grand.Web.Admin/Validators/Vendors/VendorValidator.cs | {
"start": 249,
"end": 1081
} | public class ____ : BaseGrandValidator<VendorModel>
{
public VendorValidator(
IEnumerable<IValidatorConsumer<VendorModel>> validators,
ITranslationService translationService)
: base(validators)
{
RuleFor(x => x.Name).NotEmpty()
.WithMessage(translationService.GetResource("Admin.Vendors.Fields.Name.Required"));
RuleFor(x => x.Email).NotEmpty()
.WithMessage(translationService.GetResource("Admin.Vendors.Fields.Email.Required"));
RuleFor(x => x.Email).EmailAddress().WithMessage(translationService.GetResource("Admin.Common.WrongEmail"));
RuleFor(x => x.Commission)
.Must(CommonValid.IsCommissionValid)
.WithMessage(translationService.GetResource("Admin.Vendors.Fields.Commission.IsCommissionValid"));
}
} | VendorValidator |
csharp | dotnet__aspire | src/Aspire.Hosting.Kubernetes/Resources/PodSecurityContextV1.cs | {
"start": 372,
"end": 689
} | class ____ configuration options for controlling
/// security-related attributes of a Kubernetes Pod. These settings include user and group ID
/// management, AppArmor profiles, seccomp profiles, SELinux options, sysctl settings, Windows-specific
/// security options, and more.
/// </remarks>
[YamlSerializable]
| provides |
csharp | nopSolutions__nopCommerce | src/Presentation/Nop.Web/Models/Sitemap/SitemapUrlModel.cs | {
"start": 131,
"end": 1994
} | public partial record ____ : BaseNopModel
{
#region Ctor
/// <summary>
/// Initializes a new instance of the sitemap URL model
/// </summary>
/// <param name="location">URL of the page</param>
/// <param name="alternateLocations">List of the page urls</param>
/// <param name="frequency">Update frequency</param>
/// <param name="updatedOn">Updated on</param>
public SitemapUrlModel(string location, IList<string> alternateLocations, UpdateFrequency frequency, DateTime updatedOn)
{
Location = location;
AlternateLocations = alternateLocations ?? new List<string>();
UpdateFrequency = frequency;
UpdatedOn = updatedOn;
}
/// <summary>
/// Initializes a new instance of the sitemap URL model based on the passed model
/// </summary>
/// <param name="location">URL of the page</param>
/// <param name="sitemapUrl">The another sitemap url</param>
public SitemapUrlModel(string location, SitemapUrlModel sitemapUrl)
{
Location = location;
AlternateLocations = sitemapUrl.AlternateLocations;
UpdateFrequency = sitemapUrl.UpdateFrequency;
UpdatedOn = sitemapUrl.UpdatedOn;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets URL of the page
/// </summary>
public string Location { get; set; }
/// <summary>
/// Gets or sets localized URLs of the page
/// </summary>
public IList<string> AlternateLocations { get; set; }
/// <summary>
/// Gets or sets a value indicating how frequently the page is likely to change
/// </summary>
public UpdateFrequency UpdateFrequency { get; set; }
/// <summary>
/// Gets or sets the date of last modification of the page
/// </summary>
public DateTime UpdatedOn { get; set; }
#endregion
} | SitemapUrlModel |
csharp | louthy__language-ext | Samples/CardGame/Game.Monad/Game.Monad.cs | {
"start": 66,
"end": 598
} | public partial class ____ :
Deriving.Monad<Game, StateT<GameState, OptionT<IO>>>,
Deriving.Stateful<Game, StateT<GameState, OptionT<IO>>, GameState>,
MonadIO<Game>
{
public static K<StateT<GameState, OptionT<IO>>, A> Transform<A>(K<Game, A> fa) =>
fa.As().runGame;
public static K<Game, A> CoTransform<A>(K<StateT<GameState, OptionT<IO>>, A> fa) =>
new Game<A>(fa.As());
public static K<Game, A> LiftIO<A>(IO<A> ma) =>
new Game<A>(StateT.liftIO<GameState, OptionT<IO>, A>(ma));
}
| Game |
csharp | getsentry__sentry-dotnet | benchmarks/Sentry.Benchmarks/StackFrameBenchmarks.cs | {
"start": 15054,
"end": 15622
} | class ____.Object)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task.FinishContinuations()",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Threading.Tasks.Task`1[System.Boolean].TrySetResult(!0)",
Module ="System.Private.CoreLib.il"
},
new SentryStackFrame() {
Function ="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[System.Boolean].SetExistingTaskResult( | System |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 485488,
"end": 488951
} | public partial class ____ : global::System.IEquatable<OnClientVersionPublishUpdated_OnClientVersionPublishingUpdate_Deployment_Errors_Changes_UnionModifiedChange>, IOnClientVersionPublishUpdated_OnClientVersionPublishingUpdate_Deployment_Errors_Changes_UnionModifiedChange
{
public OnClientVersionPublishUpdated_OnClientVersionPublishingUpdate_Deployment_Errors_Changes_UnionModifiedChange(global::System.String __typename, global::ChilliCream.Nitro.CommandLine.Cloud.Client.SchemaChangeSeverity severity, global::System.String coordinate, global::System.Collections.Generic.IReadOnlyList<global::ChilliCream.Nitro.CommandLine.Cloud.Client.IOnClientVersionPublishUpdated_OnClientVersionPublishingUpdate_Deployment_Errors_Changes_Changes_6> changes)
{
this.__typename = __typename;
Severity = severity;
Coordinate = coordinate;
Changes = changes;
}
/// <summary>
/// The name of the current Object type at runtime.
/// </summary>
public global::System.String __typename { get; }
public global::ChilliCream.Nitro.CommandLine.Cloud.Client.SchemaChangeSeverity Severity { get; }
public global::System.String Coordinate { get; }
public global::System.Collections.Generic.IReadOnlyList<global::ChilliCream.Nitro.CommandLine.Cloud.Client.IOnClientVersionPublishUpdated_OnClientVersionPublishingUpdate_Deployment_Errors_Changes_Changes_6> Changes { get; }
public virtual global::System.Boolean Equals(OnClientVersionPublishUpdated_OnClientVersionPublishingUpdate_Deployment_Errors_Changes_UnionModifiedChange? other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (other.GetType() != GetType())
{
return false;
}
return (__typename.Equals(other.__typename)) && Severity.Equals(other.Severity) && Coordinate.Equals(other.Coordinate) && global::StrawberryShake.Internal.ComparisonHelper.SequenceEqual(Changes, other.Changes);
}
public override global::System.Boolean Equals(global::System.Object? obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((OnClientVersionPublishUpdated_OnClientVersionPublishingUpdate_Deployment_Errors_Changes_UnionModifiedChange)obj);
}
public override global::System.Int32 GetHashCode()
{
unchecked
{
int hash = 5;
hash ^= 397 * __typename.GetHashCode();
hash ^= 397 * Severity.GetHashCode();
hash ^= 397 * Coordinate.GetHashCode();
foreach (var Changes_elm in Changes)
{
hash ^= 397 * Changes_elm.GetHashCode();
}
return hash;
}
}
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| OnClientVersionPublishUpdated_OnClientVersionPublishingUpdate_Deployment_Errors_Changes_UnionModifiedChange |
csharp | SixLabors__Fonts | src/SixLabors.Fonts/Unicode/BidiAlgorithm.cs | {
"start": 54851,
"end": 55446
} | struct ____
{
public Status(sbyte embeddingLevel, BidiCharacterType overrideStatus, bool isolateStatus)
{
this.EmbeddingLevel = embeddingLevel;
this.OverrideStatus = overrideStatus;
this.IsolateStatus = isolateStatus;
}
public sbyte EmbeddingLevel { get; }
public BidiCharacterType OverrideStatus { get; }
public bool IsolateStatus { get; }
}
/// <summary>
/// Provides information about a level run - a continuous
/// sequence of equal levels.
/// </summary>
private readonly | Status |
csharp | jellyfin__jellyfin | Jellyfin.Server/Migrations/Routines/MoveExtractedFiles.cs | {
"start": 907,
"end": 13158
} | public class ____ : IAsyncMigrationRoutine
{
private readonly IApplicationPaths _appPaths;
private readonly ILogger _logger;
private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
private readonly IPathManager _pathManager;
private readonly IFileSystem _fileSystem;
/// <summary>
/// Initializes a new instance of the <see cref="MoveExtractedFiles"/> class.
/// </summary>
/// <param name="appPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
/// <param name="logger">The logger.</param>
/// <param name="startupLogger">The startup logger for Startup UI intigration.</param>
/// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
/// <param name="pathManager">Instance of the <see cref="IPathManager"/> interface.</param>
/// <param name="dbProvider">Instance of the <see cref="IDbContextFactory{JellyfinDbContext}"/> interface.</param>
public MoveExtractedFiles(
IApplicationPaths appPaths,
ILogger<MoveExtractedFiles> logger,
IStartupLogger<MoveExtractedFiles> startupLogger,
IPathManager pathManager,
IFileSystem fileSystem,
IDbContextFactory<JellyfinDbContext> dbProvider)
{
_appPaths = appPaths;
_logger = startupLogger.With(logger);
_pathManager = pathManager;
_fileSystem = fileSystem;
_dbProvider = dbProvider;
}
private string SubtitleCachePath => Path.Combine(_appPaths.DataPath, "subtitles");
private string AttachmentCachePath => Path.Combine(_appPaths.DataPath, "attachments");
/// <inheritdoc />
public async Task PerformAsync(CancellationToken cancellationToken)
{
const int Limit = 5000;
int itemCount = 0;
var sw = Stopwatch.StartNew();
using var context = _dbProvider.CreateDbContext();
var records = context.BaseItems.Count(b => b.MediaType == MediaType.Video.ToString() && !b.IsVirtualItem && !b.IsFolder);
_logger.LogInformation("Checking {Count} items for movable extracted files.", records);
// Make sure directories exist
Directory.CreateDirectory(SubtitleCachePath);
Directory.CreateDirectory(AttachmentCachePath);
await foreach (var result in context.BaseItems
.Include(e => e.MediaStreams!.Where(s => s.StreamType == MediaStreamTypeEntity.Subtitle && !s.IsExternal))
.Where(b => b.MediaType == MediaType.Video.ToString() && !b.IsVirtualItem && !b.IsFolder)
.Select(b => new
{
b.Id,
b.Path,
b.MediaStreams
})
.OrderBy(e => e.Id)
.WithPartitionProgress((partition) => _logger.LogInformation("Checked: {Count} - Moved: {Items} - Time: {Time}", partition * Limit, itemCount, sw.Elapsed))
.PartitionEagerAsync(Limit, cancellationToken)
.WithCancellation(cancellationToken)
.ConfigureAwait(false))
{
if (MoveSubtitleAndAttachmentFiles(result.Id, result.Path, result.MediaStreams, context))
{
itemCount++;
}
}
_logger.LogInformation("Moved files for {Count} items in {Time}", itemCount, sw.Elapsed);
// Get all subdirectories with 1 character names (those are the legacy directories)
var subdirectories = Directory.GetDirectories(SubtitleCachePath, "*", SearchOption.AllDirectories).Where(s => s.Length == SubtitleCachePath.Length + 2).ToList();
subdirectories.AddRange(Directory.GetDirectories(AttachmentCachePath, "*", SearchOption.AllDirectories).Where(s => s.Length == AttachmentCachePath.Length + 2));
// Remove all legacy subdirectories
foreach (var subdir in subdirectories)
{
Directory.Delete(subdir, true);
}
// Remove old cache path
var attachmentCachePath = Path.Join(_appPaths.CachePath, "attachments");
if (Directory.Exists(attachmentCachePath))
{
Directory.Delete(attachmentCachePath, true);
}
_logger.LogInformation("Cleaned up left over subtitles and attachments.");
}
private bool MoveSubtitleAndAttachmentFiles(Guid id, string? path, ICollection<MediaStreamInfo>? mediaStreams, JellyfinDbContext context)
{
var itemIdString = id.ToString("N", CultureInfo.InvariantCulture);
var modified = false;
if (mediaStreams is not null)
{
foreach (var mediaStream in mediaStreams)
{
if (mediaStream.Codec is null)
{
continue;
}
var mediaStreamIndex = mediaStream.StreamIndex;
var extension = GetSubtitleExtension(mediaStream.Codec);
var oldSubtitleCachePath = GetOldSubtitleCachePath(path, mediaStreamIndex, extension);
if (string.IsNullOrEmpty(oldSubtitleCachePath) || !File.Exists(oldSubtitleCachePath))
{
continue;
}
var newSubtitleCachePath = _pathManager.GetSubtitlePath(itemIdString, mediaStreamIndex, extension);
if (File.Exists(newSubtitleCachePath))
{
File.Delete(oldSubtitleCachePath);
}
else
{
var newDirectory = Path.GetDirectoryName(newSubtitleCachePath);
if (newDirectory is not null)
{
Directory.CreateDirectory(newDirectory);
File.Move(oldSubtitleCachePath, newSubtitleCachePath, false);
_logger.LogDebug("Moved subtitle {Index} for {Item} from {Source} to {Destination}", mediaStreamIndex, id, oldSubtitleCachePath, newSubtitleCachePath);
modified = true;
}
}
}
}
#pragma warning disable CA1309 // Use ordinal string comparison
var attachments = context.AttachmentStreamInfos.Where(a => a.ItemId.Equals(id) && !string.Equals(a.Codec, "mjpeg")).ToList();
#pragma warning restore CA1309 // Use ordinal string comparison
var shouldExtractOneByOne = attachments.Any(a => !string.IsNullOrEmpty(a.Filename)
&& (a.Filename.Contains('/', StringComparison.OrdinalIgnoreCase) || a.Filename.Contains('\\', StringComparison.OrdinalIgnoreCase)));
foreach (var attachment in attachments)
{
var attachmentIndex = attachment.Index;
var oldAttachmentPath = GetOldAttachmentDataPath(path, attachmentIndex);
if (string.IsNullOrEmpty(oldAttachmentPath) || !File.Exists(oldAttachmentPath))
{
oldAttachmentPath = GetOldAttachmentCachePath(itemIdString, attachment, shouldExtractOneByOne);
if (string.IsNullOrEmpty(oldAttachmentPath) || !File.Exists(oldAttachmentPath))
{
continue;
}
}
var newAttachmentPath = _pathManager.GetAttachmentPath(itemIdString, attachment.Filename ?? attachmentIndex.ToString(CultureInfo.InvariantCulture));
if (File.Exists(newAttachmentPath))
{
File.Delete(oldAttachmentPath);
}
else
{
var newDirectory = Path.GetDirectoryName(newAttachmentPath);
if (newDirectory is not null)
{
Directory.CreateDirectory(newDirectory);
File.Move(oldAttachmentPath, newAttachmentPath, false);
_logger.LogDebug("Moved attachment {Index} for {Item} from {Source} to {Destination}", attachmentIndex, id, oldAttachmentPath, newAttachmentPath);
modified = true;
}
}
}
return modified;
}
private string? GetOldAttachmentDataPath(string? mediaPath, int attachmentStreamIndex)
{
if (mediaPath is null)
{
return null;
}
string filename;
if (_fileSystem.IsPathFile(mediaPath))
{
DateTime? date;
try
{
date = File.GetLastWriteTimeUtc(mediaPath);
}
catch (IOException e)
{
_logger.LogDebug("Skipping attachment at index {Index} for {Path}: {Exception}", attachmentStreamIndex, mediaPath, e.Message);
return null;
}
catch (UnauthorizedAccessException e)
{
_logger.LogDebug("Skipping subtitle at index {Index} for {Path}: {Exception}", attachmentStreamIndex, mediaPath, e.Message);
return null;
}
catch (ArgumentOutOfRangeException e)
{
_logger.LogDebug("Skipping attachment at index {Index} for {Path}: {Exception}", attachmentStreamIndex, mediaPath, e.Message);
return null;
}
filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Value.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
}
else
{
filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
}
return Path.Join(_appPaths.DataPath, "attachments", filename[..1], filename);
}
private string? GetOldAttachmentCachePath(string mediaSourceId, AttachmentStreamInfo attachment, bool shouldExtractOneByOne)
{
var attachmentFolderPath = Path.Join(_appPaths.CachePath, "attachments", mediaSourceId);
if (shouldExtractOneByOne)
{
return Path.Join(attachmentFolderPath, attachment.Index.ToString(CultureInfo.InvariantCulture));
}
if (string.IsNullOrEmpty(attachment.Filename))
{
return null;
}
return Path.Join(attachmentFolderPath, attachment.Filename);
}
private string? GetOldSubtitleCachePath(string? path, int streamIndex, string outputSubtitleExtension)
{
if (path is null)
{
return null;
}
DateTime? date;
try
{
date = File.GetLastWriteTimeUtc(path);
}
catch (ArgumentOutOfRangeException e)
{
_logger.LogDebug("Skipping subtitle at index {Index} for {Path}: {Exception}", streamIndex, path, e.Message);
return null;
}
catch (UnauthorizedAccessException e)
{
_logger.LogDebug("Skipping subtitle at index {Index} for {Path}: {Exception}", streamIndex, path, e.Message);
return null;
}
catch (IOException e)
{
_logger.LogDebug("Skipping subtitle at index {Index} for {Path}: {Exception}", streamIndex, path, e.Message);
return null;
}
var ticksParam = string.Empty;
ReadOnlySpan<char> filename = new Guid(MD5.HashData(Encoding.Unicode.GetBytes(path + "_" + streamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Value.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam))) + outputSubtitleExtension;
return Path.Join(SubtitleCachePath, filename[..1], filename);
}
private static string GetSubtitleExtension(string codec)
{
if (codec.ToLower(CultureInfo.InvariantCulture).Equals("ass", StringComparison.OrdinalIgnoreCase)
|| codec.ToLower(CultureInfo.InvariantCulture).Equals("ssa", StringComparison.OrdinalIgnoreCase))
{
return "." + codec;
}
else if (codec.Contains("pgs", StringComparison.OrdinalIgnoreCase))
{
return ".sup";
}
else
{
return ".srt";
}
}
}
| MoveExtractedFiles |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Input/DoubleTappedRoutedEventArgs.cs | {
"start": 214,
"end": 1752
} | partial class ____ : RoutedEventArgs, IHandleableRoutedEventArgs
{
private readonly UIElement _originalSource;
private readonly Point _position;
public DoubleTappedRoutedEventArgs() { }
/// <param name="originalSource">The original source of the PointerUp event causing the Tapped event (i.e. the top-most element that hit-tests positively).</param>
/// <param name="gestureRecognizerOwner">The element that subscribes to the Tapped event and initiates then propagates the event. This element is the owner of the GestureRecognizer that recognizes this Tap event.</param>
internal DoubleTappedRoutedEventArgs(UIElement originalSource, TappedEventArgs args, UIElement gestureRecognizerOwner)
: base(originalSource)
{
_originalSource = originalSource;
PointerDeviceType = args.PointerDeviceType;
// The TappedEventArgs position is relative to the GestureRecognizer owner, not the original source of the pointer event.
_position = gestureRecognizerOwner.GetPosition(args.Position, originalSource);
PointerId = args.PointerId;
}
internal uint PointerId { get; }
public bool Handled { get; set; }
public PointerDeviceType PointerDeviceType { get; }
public Point GetPosition(UIElement relativeTo)
{
if (_originalSource == null)
{
return default; // Required for the default public ctor ...
}
else if (relativeTo == _originalSource)
{
return _position;
}
else
{
return _originalSource.GetPosition(_position, relativeTo);
}
}
}
}
| DoubleTappedRoutedEventArgs |
csharp | microsoft__PowerToys | src/modules/cmdpal/ext/Microsoft.CmdPal.Ext.Apps/Storage/Win32ProgramFileSystemWatchers.cs | {
"start": 558,
"end": 2592
} | class ____ the list of directories to watch and initializes the File System Watchers
public Win32ProgramFileSystemWatchers()
{
PathsToWatch = GetPathsToWatch();
FileSystemWatchers = new List<FileSystemWatcherWrapper>();
for (var index = 0; index < PathsToWatch.Length; index++)
{
FileSystemWatchers.Add(new FileSystemWatcherWrapper());
}
}
// Returns an array of paths to be watched
private static string[] GetPathsToWatch()
{
var paths = new string[]
{
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu),
Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu),
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory),
};
var invalidPaths = new List<string>();
foreach (var path in paths)
{
try
{
Directory.GetFiles(path);
}
catch (Exception e)
{
Logger.LogError(e.Message);
invalidPaths.Add(path);
}
}
var validPaths = new List<string>();
foreach (var path in paths)
{
if (!invalidPaths.Contains(path))
{
validPaths.Add(path);
}
}
return validPaths.ToArray();
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
for (var index = 0; index < PathsToWatch.Length; index++)
{
FileSystemWatchers[index].Dispose();
}
_disposed = true;
}
}
}
}
| contains |
csharp | dotnet__maui | src/Graphics/src/Graphics/Platforms/Windows/PlatformGraphicsService.cs | {
"start": 318,
"end": 951
} | internal class ____
#endif
{
private static ICanvasResourceCreator _globalCreator;
private static readonly ThreadLocal<ICanvasResourceCreator> _threadLocalCreator = new ThreadLocal<ICanvasResourceCreator>();
public static ICanvasResourceCreator GlobalCreator
{
get => _globalCreator ?? CanvasDevice.GetSharedDevice();
set => _globalCreator = value;
}
public static ICanvasResourceCreator ThreadLocalCreator
{
get => _threadLocalCreator.Value;
set => _threadLocalCreator.Value = value;
}
public static ICanvasResourceCreator Creator =>
ThreadLocalCreator ?? GlobalCreator;
}
}
| PlatformGraphicsService |
csharp | nopSolutions__nopCommerce | src/Presentation/Nop.Web/Areas/Admin/Controllers/ScheduleTaskController.cs | {
"start": 476,
"end": 4766
} | public partial class ____ : BaseAdminController
{
#region Fields
protected readonly ICustomerActivityService _customerActivityService;
protected readonly ILocalizationService _localizationService;
protected readonly INotificationService _notificationService;
protected readonly IPermissionService _permissionService;
protected readonly IScheduleTaskModelFactory _scheduleTaskModelFactory;
protected readonly IScheduleTaskService _scheduleTaskService;
protected readonly IScheduleTaskRunner _taskRunner;
#endregion
#region Ctor
public ScheduleTaskController(ICustomerActivityService customerActivityService,
ILocalizationService localizationService,
INotificationService notificationService,
IPermissionService permissionService,
IScheduleTaskModelFactory scheduleTaskModelFactory,
IScheduleTaskService scheduleTaskService,
IScheduleTaskRunner taskRunner)
{
_customerActivityService = customerActivityService;
_localizationService = localizationService;
_notificationService = notificationService;
_permissionService = permissionService;
_scheduleTaskModelFactory = scheduleTaskModelFactory;
_scheduleTaskService = scheduleTaskService;
_taskRunner = taskRunner;
}
#endregion
#region Methods
public virtual IActionResult Index()
{
return RedirectToAction("List");
}
[CheckPermission(StandardPermission.System.MANAGE_SCHEDULE_TASKS)]
public virtual async Task<IActionResult> List()
{
//prepare model
var model = await _scheduleTaskModelFactory.PrepareScheduleTaskSearchModelAsync(new ScheduleTaskSearchModel());
return View(model);
}
[HttpPost]
[CheckPermission(StandardPermission.System.MANAGE_SCHEDULE_TASKS)]
public virtual async Task<IActionResult> List(ScheduleTaskSearchModel searchModel)
{
//prepare model
var model = await _scheduleTaskModelFactory.PrepareScheduleTaskListModelAsync(searchModel);
return Json(model);
}
[HttpPost]
[CheckPermission(StandardPermission.System.MANAGE_SCHEDULE_TASKS)]
public virtual async Task<IActionResult> TaskUpdate(ScheduleTaskModel model)
{
//try to get a schedule task with the specified id
var scheduleTask = await _scheduleTaskService.GetTaskByIdAsync(model.Id)
?? throw new ArgumentException("Schedule task cannot be loaded");
//To prevent inject the XSS payload in Schedule tasks ('Name' field), we must disable editing this field,
//but since it is required, we need to get its value before updating the entity.
if (!string.IsNullOrEmpty(scheduleTask.Name))
{
model.Name = scheduleTask.Name;
ModelState.Remove(nameof(model.Name));
}
if (!ModelState.IsValid)
return ErrorJson(ModelState.SerializeErrors());
if (!scheduleTask.Enabled && model.Enabled)
scheduleTask.LastEnabledUtc = DateTime.UtcNow;
scheduleTask = model.ToEntity(scheduleTask);
await _scheduleTaskService.UpdateTaskAsync(scheduleTask);
//activity log
await _customerActivityService.InsertActivityAsync("EditTask",
string.Format(await _localizationService.GetResourceAsync("ActivityLog.EditTask"), scheduleTask.Id), scheduleTask);
return new NullJsonResult();
}
[CheckPermission(StandardPermission.System.MANAGE_SCHEDULE_TASKS)]
public virtual async Task<IActionResult> RunNow(int id)
{
try
{
//try to get a schedule task with the specified id
var scheduleTask = await _scheduleTaskService.GetTaskByIdAsync(id)
?? throw new ArgumentException("Schedule task cannot be loaded", nameof(id));
await _taskRunner.ExecuteAsync(scheduleTask, true, true, false);
_notificationService.SuccessNotification(await _localizationService.GetResourceAsync("Admin.System.ScheduleTasks.RunNow.Done"));
}
catch (Exception exc)
{
await _notificationService.ErrorNotificationAsync(exc);
}
return RedirectToAction("List");
}
#endregion
} | ScheduleTaskController |
csharp | JoshClose__CsvHelper | src/CsvHelper/IReader.cs | {
"start": 437,
"end": 526
} | public interface ____ : IReaderRow, IDisposable
{
/// <summary>
/// Reads the header | IReader |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.