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 | icsharpcode__ILSpy | ICSharpCode.Decompiler/CSharp/Syntax/IAnnotatable.cs | {
"start": 2713,
"end": 2840
} | class ____ to implement the IAnnotatable interface.
/// This implementation is thread-safe.
/// </summary>
[Serializable]
| used |
csharp | jellyfin__jellyfin | src/Jellyfin.Extensions/Json/Utf8JsonExtensions.cs | {
"start": 145,
"end": 983
} | public static class ____
{
/// <summary>
/// Determines if the reader contains an empty string.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>Whether the reader contains an empty string.</returns>
public static bool IsEmptyString(this Utf8JsonReader reader)
=> reader.TokenType == JsonTokenType.String
&& ((reader.HasValueSequence && reader.ValueSequence.IsEmpty)
|| (!reader.HasValueSequence && reader.ValueSpan.IsEmpty));
/// <summary>
/// Determines if the reader contains a null value.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>Whether the reader contains null.</returns>
public static bool IsNull(this Utf8JsonReader reader)
=> reader.TokenType == JsonTokenType.Null;
}
| Utf8JsonExtensions |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/VirtualPathProviderTests.cs | {
"start": 715,
"end": 1207
} | public class ____ : AppendVirtualFilesTests
{
private static string RootDir = "~/App_Data/files".MapProjectPath();
public FileSystemVirtualPathProviderTests()
{
if (Directory.Exists(RootDir))
Directory.Delete(RootDir, recursive:true);
Directory.CreateDirectory(RootDir);
}
public override IVirtualPathProvider GetPathProvider()
{
return new FileSystemVirtualFiles(RootDir);
}
}
| FileSystemVirtualPathProviderTests |
csharp | dotnet__aspire | src/Aspire.Hosting.Kubernetes/Resources/SELinuxOptionsV1.cs | {
"start": 795,
"end": 2061
} | public sealed class ____
{
/// <summary>
/// Gets or sets the SELinux role for the resource.
/// This property represents the SELinux role element, which is part of the SELinux
/// security policy used to define fine-grained access control.
/// </summary>
[YamlMember(Alias = "role")]
public string Role { get; set; } = null!;
/// <summary>
/// Gets or sets the SELinux type associated with the SELinuxOptions.
/// This property specifies the SELinux type of the object. It is
/// a security attribute used to define the security policy for a resource.
/// </summary>
[YamlMember(Alias = "type")]
public string Type { get; set; } = null!;
/// <summary>
/// Gets or sets the SELinux level for the policy.
/// This property specifies the SELinux level to apply.
/// </summary>
[YamlMember(Alias = "level")]
public string Level { get; set; } = null!;
/// <summary>
/// Gets or sets the SELinux user associated with the security context.
/// The SELinux user is a required field and specifies the security user policy
/// applied to the container or process.
/// </summary>
[YamlMember(Alias = "user")]
public string User { get; set; } = null!;
}
| SeLinuxOptionsV1 |
csharp | dotnet__maui | src/SingleProject/Resizetizer/src/SkiaSharpRasterTools.cs | {
"start": 99,
"end": 982
} | internal class ____ : SkiaSharpTools, IDisposable
{
SKImage img;
public SkiaSharpRasterTools(ResizeImageInfo info, ILogger logger)
: this(info.Filename, info.BaseSize, info.Color, info.TintColor, logger)
{
}
public SkiaSharpRasterTools(string filename, SKSize? baseSize, SKColor? backgroundColor, SKColor? tintColor, ILogger logger)
: base(filename, baseSize, backgroundColor, tintColor, logger)
{
var sw = new Stopwatch();
sw.Start();
img = SKImage.FromEncodedData(filename);
sw.Stop();
Logger?.Log($"Open RASTER took {sw.ElapsedMilliseconds}ms ({filename})");
}
public override SKSize GetOriginalSize() =>
img.Info.Size;
public override void DrawUnscaled(SKCanvas canvas, float scale) =>
canvas.DrawImage(img, 0, 0, SamplingOptions, Paint);
public void Dispose()
{
img?.Dispose();
img = null;
}
}
}
| SkiaSharpRasterTools |
csharp | abpframework__abp | modules/cms-kit/src/Volo.CmsKit.Public.Application/Volo/CmsKit/Public/CmsKitPublicApplicationMappers.cs | {
"start": 1266,
"end": 1877
} | public partial class ____ : MapperBase<Comment, CommentWithDetailsDto>
{
[MapperIgnoreTarget(nameof(CommentWithDetailsDto.Replies))]
[MapperIgnoreTarget(nameof(CommentWithDetailsDto.Author))]
public override partial CommentWithDetailsDto Map(Comment source);
[MapperIgnoreTarget(nameof(CommentWithDetailsDto.Replies))]
[MapperIgnoreTarget(nameof(CommentWithDetailsDto.Author))]
public override partial void Map(Comment source, CommentWithDetailsDto destination);
}
[Mapper(RequiredMappingStrategy = RequiredMappingStrategy.Target)]
[MapExtraProperties]
| CommentToCommentWithDetailsDtoMapper |
csharp | abpframework__abp | framework/src/Volo.Abp.Http/Volo/Abp/Http/Modeling/ParameterApiDescriptionModel.cs | {
"start": 92,
"end": 1521
} | public class ____
{
public string NameOnMethod { get; set; } = default!;
public string Name { get; set; } = default!;
public string? JsonName { get; set; }
public string? Type { get; set; }
public string? TypeSimple { get; set; }
public bool IsOptional { get; set; }
public object? DefaultValue { get; set; }
public string[]? ConstraintTypes { get; set; }
public string? BindingSourceId { get; set; }
public string? DescriptorName { get; set; }
public ParameterApiDescriptionModel()
{
}
public static ParameterApiDescriptionModel Create(string name, string? jsonName, string nameOnMethod, Type type, bool isOptional = false, object? defaultValue = null, string[]? constraintTypes = null, string? bindingSourceId = null, string? descriptorName = null)
{
return new ParameterApiDescriptionModel
{
Name = name,
JsonName = jsonName,
NameOnMethod = nameOnMethod,
Type = type != null ? TypeHelper.GetFullNameHandlingNullableAndGenerics(type) : null,
TypeSimple = type != null ? ApiTypeNameHelper.GetSimpleTypeName(type) : null,
IsOptional = isOptional,
DefaultValue = defaultValue,
ConstraintTypes = constraintTypes,
BindingSourceId = bindingSourceId,
DescriptorName = descriptorName
};
}
}
| ParameterApiDescriptionModel |
csharp | microsoft__garnet | libs/server/Resp/AsyncProcessor.cs | {
"start": 358,
"end": 6204
} | partial class ____ : ServerSessionBase
{
/// <summary>
/// Whether async mode is turned on for the session
/// </summary>
bool useAsync = false;
/// <summary>
/// How many async operations are started and completed
/// </summary>
long asyncStarted = 0, asyncCompleted = 0;
/// <summary>
/// Async waiter for async operations
/// </summary>
SingleWaiterAutoResetEvent asyncWaiter = null;
/// <summary>
/// Cancellation token source for async waiter
/// </summary>
CancellationTokenSource asyncWaiterCancel = null;
/// <summary>
/// Semaphore for barrier command to wait for async operations to complete
/// </summary>
SemaphoreSlim asyncDone = null;
/// <summary>
/// Handle a async network GET command that goes pending
/// </summary>
/// <typeparam name="TGarnetApi"></typeparam>
/// <param name="storageApi"></param>
void NetworkGETPending<TGarnetApi>(ref TGarnetApi storageApi)
where TGarnetApi : IGarnetApi
{
unsafe
{
while (!RespWriteUtils.TryWriteError($"ASYNC {asyncStarted}", ref dcurr, dend))
SendAndReset();
}
if (++asyncStarted == 1) // first async operation on the session, create the IO continuation processor
{
asyncWaiterCancel = new();
asyncWaiter = new()
{
RunContinuationsAsynchronously = true
};
var _storageApi = storageApi;
_ = Task.Run(async () => await AsyncGetProcessor(_storageApi));
}
else
{
Debug.Assert(asyncWaiter != null);
asyncWaiter.Signal();
}
}
/// <summary>
/// Background processor for async IO continuations. This is created only when async is turned on for the session.
/// It handles all the IO completions and takes over the network sender to send async responses when ready.
/// Note that async responses are not guaranteed to be in the same order that they are issued.
/// </summary>
async Task AsyncGetProcessor<TGarnetApi>(TGarnetApi storageApi)
where TGarnetApi : IGarnetApi
{
while (!asyncWaiterCancel.Token.IsCancellationRequested)
{
while (asyncCompleted < asyncStarted)
{
// First complete all pending ops
storageApi.GET_CompletePending(out var completedOutputs, true);
try
{
unsafe
{
// We are ready to send responses so we take over the network sender from the main ProcessMessage thread
// Note that we cannot take over while ProcessMessage is in progress because partial responses may have been
// sent at that point. For sync responses that span multiple ProcessMessage calls (e.g., MGET), we need the
// main thread to hold the sender lock until the response is done.
networkSender.EnterAndGetResponseObject(out dcurr, out dend);
// Send async replies with completed outputs
while (completedOutputs.Next())
{
// This is the only thread that updates asyncCompleted so we do not need atomics here
asyncCompleted++;
var o = completedOutputs.Current.Output;
// We write async push response as an array: [ "async", "<token_id>", "<result_string>" ]
while (!RespWriteUtils.TryWritePushLength(3, ref dcurr, dend))
SendAndReset();
while (!RespWriteUtils.TryWriteBulkString(CmdStrings.async, ref dcurr, dend))
SendAndReset();
while (!RespWriteUtils.TryWriteInt32AsBulkString((int)completedOutputs.Current.Context, ref dcurr, dend))
SendAndReset();
if (completedOutputs.Current.Status.Found)
{
Debug.Assert(!o.IsSpanByte);
sessionMetrics?.incr_total_found();
SendAndReset(o.Memory, o.Length);
}
else
{
sessionMetrics?.incr_total_notfound();
WriteNull();
}
}
if (dcurr > networkSender.GetResponseObjectHead())
Send(networkSender.GetResponseObjectHead());
}
}
finally
{
completedOutputs.Dispose();
networkSender.ExitAndReturnResponseObject();
}
}
// Let ongoing barrier command know that all async operations are done
asyncDone?.Release();
// Wait for next async operation
// We do not need to cancel the wait - it should get garbage collected when the session ends
await asyncWaiter.WaitAsync();
}
}
}
} | RespServerSession |
csharp | dotnetcore__Util | src/Util.Ui.NgZorro/Components/Badges/Renders/BadgeRender.cs | {
"start": 193,
"end": 824
} | public class ____ : RenderBase {
/// <summary>
/// 配置
/// </summary>
private readonly Config _config;
/// <summary>
/// 初始化徽标渲染器
/// </summary>
/// <param name="config">配置</param>
public BadgeRender( Config config ) {
_config = config;
}
/// <summary>
/// 获取标签生成器
/// </summary>
protected override TagBuilder GetTagBuilder() {
var builder = new BadgeBuilder( _config );
builder.Config();
return builder;
}
/// <inheritdoc />
public override IHtmlContent Clone() {
return new BadgeRender( _config.Copy() );
}
} | BadgeRender |
csharp | dotnet__maui | src/Controls/tests/TestCases.HostApp/Issues/GroupListViewHeaderIndexOutOfRange.cs | {
"start": 190,
"end": 2517
} | public class ____ : TestContentPage
{
const string ButtonId = "button";
public static ObservableCollection<SamplePack> Samples { get; set; }
public static ObservableCollection<Grouping<string, SamplePack>> Testing { get; set; }
public static void ResetList()
{
Testing.Clear();
}
protected override void Init()
{
Samples = new ObservableCollection<SamplePack>
{
new SamplePack {Info = "1"},
new SamplePack {Info = "2"},
new SamplePack {Info = "3"}
};
var sorted = from sampleData in Samples
orderby sampleData.Info
group sampleData by sampleData.Info
into sampleGroup
select new Grouping<string, SamplePack>(sampleGroup.Key, sampleGroup);
Testing = new ObservableCollection<Grouping<string, SamplePack>>(sorted);
ListView TestingList = new ListView()
{
IsPullToRefreshEnabled = true,
IsGroupingEnabled = true,
GroupHeaderTemplate = new DataTemplate(() =>
{
var groupLabel = new Label { FontSize = 18, TextColor = Color.FromArgb("#1f1f1f"), HorizontalOptions = LayoutOptions.Start, HorizontalTextAlignment = TextAlignment.Start };
groupLabel.SetBinding(Label.TextProperty, new Binding("Key", stringFormat: "{0} Music"));
return new ViewCell
{
Height = 283,
View = new StackLayout
{
Spacing = 0,
Padding = 10,
BackgroundColor = Colors.Blue,
Children = {
new StackLayout{ Padding = 5, BackgroundColor=Colors.White, HeightRequest=30, Children = { groupLabel } }
}
}
};
}),
ItemTemplate = new DataTemplate(() =>
{
var itemLabel = new Label { TextColor = Colors.Black };
itemLabel.SetBinding(Label.TextProperty, new Binding("Info"));
return new ViewCell
{
View = itemLabel
};
})
};
TestingList.ItemsSource = Testing;
TestingList.BindingContext = Testing;
TestingList.RefreshCommand = new Command(() =>
{
TestingList.IsRefreshing = true;
ResetList();
TestingList.IsRefreshing = false;
});
Button button = new Button { Text = "Click here to cause crash. Pass if no crash!", Command = new Command(() => ResetList()), AutomationId = ButtonId };
Content = new StackLayout { Children = { button, TestingList } };
}
| GroupListViewHeaderIndexOutOfRange |
csharp | aspnetboilerplate__aspnetboilerplate | test/Abp.ZeroCore.SampleApp/EntityFramework/Seed/Host/DefaultSettingsCreator.cs | {
"start": 150,
"end": 1035
} | public class ____
{
private readonly SampleAppDbContext _context;
public DefaultSettingsCreator(SampleAppDbContext context)
{
_context = context;
}
public void Create()
{
//Emailing
AddSettingIfNotExists(EmailSettingNames.DefaultFromAddress, "admin@mydomain.com");
AddSettingIfNotExists(EmailSettingNames.DefaultFromDisplayName, "mydomain.com mailer");
//Languages
AddSettingIfNotExists(LocalizationSettingNames.DefaultLanguage, "en");
}
private void AddSettingIfNotExists(string name, string value, int? tenantId = null)
{
if (_context.Settings.Any(s => s.Name == name && s.TenantId == tenantId && s.UserId == null))
{
return;
}
_context.Settings.Add(new Setting(tenantId, null, name, value));
_context.SaveChanges();
}
} | DefaultSettingsCreator |
csharp | pythonnet__pythonnet | tests/domain_tests/TestRunner.cs | {
"start": 22221,
"end": 22541
} | public class ____
{
static public int Field = 2;
}
}",
DotNetAfter = @"
namespace TestNamespace
{
[System.Serializable]
| Cls |
csharp | protobuf-net__protobuf-net | assorted/LateLoaded/FooBar.cs | {
"start": 100,
"end": 224
} | public class ____
{
[ProtoMember(1)]
public string BaseProp { get; set; }
}
[ProtoContract]
| Foo |
csharp | bchavez__Bogus | Examples/ExtendingBogus/FoodDataSet.cs | {
"start": 198,
"end": 549
} | public static class ____
{
public static Food Food(this Faker faker)
{
return ContextHelper.GetOrSet(faker, () => new Food());
}
}
/// <summary>
/// This DatSet can be created manually using `new Candy()`, or by fluent extension method via <seealso cref="ExtensionsForFood"/>.
/// </summary>
| ExtensionsForFood |
csharp | abpframework__abp | modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AbpIdentityServerDbProperties.cs | {
"start": 59,
"end": 338
} | public static class ____
{
public static string DbTablePrefix { get; set; } = "IdentityServer";
public static string DbSchema { get; set; } = AbpCommonDbProperties.DbSchema;
public const string ConnectionStringName = "AbpIdentityServer";
}
| AbpIdentityServerDbProperties |
csharp | dotnetcore__FreeSql | Providers/FreeSql.Provider.Oracle/OracleAdo/OracleAdo.cs | {
"start": 326,
"end": 5482
} | class ____ : FreeSql.Internal.CommonProvider.AdoProvider
{
public OracleAdo() : base(DataType.Oracle, null, null) { }
public OracleAdo(CommonUtils util, string masterConnectionString, string[] slaveConnectionStrings, Func<DbConnection> connectionFactory) : base(DataType.Oracle, masterConnectionString, slaveConnectionStrings)
{
base._util = util;
if (connectionFactory != null)
{
var pool = new FreeSql.Internal.CommonProvider.DbConnectionPool(DataType.Oracle, connectionFactory);
ConnectionString = pool.TestConnection?.ConnectionString;
MasterPool = pool;
return;
}
var isAdoPool = masterConnectionString?.StartsWith("AdoConnectionPool,") ?? false;
if (isAdoPool) masterConnectionString = masterConnectionString.Substring("AdoConnectionPool,".Length);
if (!string.IsNullOrEmpty(masterConnectionString))
MasterPool = isAdoPool ?
new DbConnectionStringPool(base.DataType, CoreErrorStrings.S_MasterDatabase, () => OracleConnectionPool.CreateConnection(masterConnectionString)) as IObjectPool<DbConnection> :
new OracleConnectionPool(CoreErrorStrings.S_MasterDatabase, masterConnectionString, null, null);
slaveConnectionStrings?.ToList().ForEach(slaveConnectionString =>
{
var slavePool = isAdoPool ?
new DbConnectionStringPool(base.DataType, $"{CoreErrorStrings.S_SlaveDatabase}{SlavePools.Count + 1}", () => OracleConnectionPool.CreateConnection(slaveConnectionString)) as IObjectPool<DbConnection> :
new OracleConnectionPool($"{CoreErrorStrings.S_SlaveDatabase}{SlavePools.Count + 1}", slaveConnectionString, () => Interlocked.Decrement(ref slaveUnavailables), () => Interlocked.Increment(ref slaveUnavailables));
SlavePools.Add(slavePool);
});
}
public override object AddslashesProcessParam(object param, Type mapType, ColumnInfo mapColumn)
{
if (param == null) return "NULL";
if (mapType != null && mapType != param.GetType() && (param is IEnumerable == false))
param = Utils.GetDataReaderValue(mapType, param);
if (param is byte[])
return $"hextoraw('{CommonUtils.BytesSqlRaw(param as byte[])}')";
else if (param is bool || param is bool?)
return (bool)param ? 1 : 0;
else if (param is string)
{
#if oledb
if (mapColumn?.Table != null && mapColumn.Table.Properties.TryGetValue(mapColumn.CsName, out var prop))
{
var us7attr = prop.GetCustomAttributes(typeof(OracleUS7AsciiAttribute), false)?.FirstOrDefault() as OracleUS7AsciiAttribute;
if (us7attr != null) return OracleUtils.StringToAscii(param as string, us7attr.Encoding);
}
#endif
return string.Concat("'", param.ToString().Replace("'", "''"), "'");
}
else if (param is char)
return string.Concat("'", param.ToString().Replace("'", "''").Replace('\0', ' '), "'");
else if (param is Enum)
return AddslashesTypeHandler(param.GetType(), param) ?? ((Enum)param).ToInt64();
else if (decimal.TryParse(string.Concat(param), out var trydec))
return param;
else if (param is DateTime)
return AddslashesTypeHandler(typeof(DateTime), param) ?? string.Concat("to_timestamp('", ((DateTime)param).ToString("yyyy-MM-dd HH:mm:ss.ffffff"), "','YYYY-MM-DD HH24:MI:SS.FF6')");
else if (param is DateTime?)
return AddslashesTypeHandler(typeof(DateTime?), param) ?? string.Concat("to_timestamp('", ((DateTime)param).ToString("yyyy-MM-dd HH:mm:ss.ffffff"), "','YYYY-MM-DD HH24:MI:SS.FF6')");
else if (param is TimeSpan || param is TimeSpan?)
return $"numtodsinterval({((TimeSpan)param).Ticks * 1.0 / 10000000},'second')";
else if (param is IEnumerable)
return AddslashesIEnumerable(param, mapType, mapColumn);
return string.Concat("'", param.ToString().Replace("'", "''"), "'");
//if (param is string) return string.Concat('N', nparms[a]);
}
public override DbCommand CreateCommand()
{
var cmd =
#if oledb
new System.Data.OleDb.OleDbCommand();
#else
new global::Oracle.ManagedDataAccess.Client.OracleCommand();
cmd.BindByName = true;
#endif
return cmd;
}
public override void ReturnConnection(IObjectPool<DbConnection> pool, Object<DbConnection> conn, Exception ex)
{
var rawPool = pool as OracleConnectionPool;
if (rawPool != null) rawPool.Return(conn, ex);
else pool.Return(conn);
}
public override DbParameter[] GetDbParamtersByObject(string sql, object obj) => _util.GetDbParamtersByObject(sql, obj);
}
}
| OracleAdo |
csharp | dotnet__maui | src/Controls/samples/Controls.Sample/MauiProgram.cs | {
"start": 1153,
"end": 13946
} | enum ____ { Main, Blazor, Shell, Template, FlyoutPage, TabbedPage }
readonly static PageType _pageType = PageType.Main;
public static MauiApp CreateMauiApp()
{
var appBuilder = MauiApp.CreateBuilder();
appBuilder.ConfigureContainer(new DefaultServiceProviderFactory(new ServiceProviderOptions
{
ValidateOnBuild = true,
ValidateScopes = true,
}));
#if __ANDROID__ || __IOS__
appBuilder.UseMauiMaps();
#endif
appBuilder.UseMauiApp<XamlApp>();
var services = appBuilder.Services;
if (UseCollectionView2)
{
#if IOS || MACCATALYST
appBuilder.ConfigureMauiHandlers(handlers =>
{
handlers.AddHandler<Microsoft.Maui.Controls.CollectionView, Microsoft.Maui.Controls.Handlers.Items2.CollectionViewHandler2>();
handlers.AddHandler<Microsoft.Maui.Controls.CarouselView, Microsoft.Maui.Controls.Handlers.Items2.CarouselViewHandler2>();
});
#endif
}
// Diagnostics
{
appBuilder.Services.AddMetrics();
ActivitySource.AddActivityListener(new ActivityListener
{
ShouldListenTo = source => source.Name is "Microsoft.Maui",
Sample = (ref ActivityCreationOptions<ActivityContext> options) => ActivitySamplingResult.AllDataAndRecorded,
ActivityStarted = activity => Console.WriteLine("Started: {0,-15} {1,-60} [{2}]", activity.OperationName, activity.Id, GetTags(activity.TagObjects)),
ActivityStopped = activity => Console.WriteLine("Stopped: {0,-15} {1,-60} {2,-15} [{3}]", activity.OperationName, activity.Id, activity.Duration, GetTags(activity.TagObjects)),
});
MeterListener meterListener = new();
meterListener.InstrumentPublished = (instrument, listener) =>
{
if (instrument.Meter.Name is "Microsoft.Maui")
{
listener.EnableMeasurementEvents(instrument);
}
};
meterListener.SetMeasurementEventCallback<int>((instrument, measurement, tags, state) =>
{
Console.WriteLine($"{instrument.Name} recorded measurement {measurement} [{GetTags(tags.ToArray())}]");
});
meterListener.Start();
static string GetTags(IEnumerable<KeyValuePair<string, object?>> tags) =>
string.Join(", ", tags.Where(t => t.Value is not null).Select(t => t.Key));
}
if (UseMauiGraphicsSkia)
{
/*
appBuilder.ConfigureMauiHandlers(handlers =>
{
handlers.AddHandler<GraphicsView, SkiaGraphicsViewHandler>();
handlers.AddHandler<BoxView, SkiaShapeViewHandler>();
handlers.AddHandler<Microsoft.Maui.Controls.Shapes.Ellipse, SkiaShapeViewHandler>();
handlers.AddHandler<Microsoft.Maui.Controls.Shapes.Line, SkiaShapeViewHandler>();
handlers.AddHandler<Microsoft.Maui.Controls.Shapes.Path, SkiaShapeViewHandler>();
handlers.AddHandler<Microsoft.Maui.Controls.Shapes.Polygon, SkiaShapeViewHandler>();
handlers.AddHandler<Microsoft.Maui.Controls.Shapes.Polyline, SkiaShapeViewHandler>();
handlers.AddHandler<Microsoft.Maui.Controls.Shapes.Rectangle, SkiaShapeViewHandler>();
handlers.AddHandler<Microsoft.Maui.Controls.Shapes.RoundRectangle, SkiaShapeViewHandler>();
});
*/
}
// appBuilder
// .ConfigureMauiHandlers(handlers =>
// {
//#pragma warning disable CS0618 // Type or member is obsolete
//#if __ANDROID__
// handlers.AddCompatibilityRenderer(typeof(CustomButton),
// typeof(Microsoft.Maui.Controls.Compatibility.Platform.Android.AppCompat.ButtonRenderer));
//#elif __IOS__
// handlers.AddCompatibilityRenderer(typeof(CustomButton),
// typeof(Microsoft.Maui.Controls.Compatibility.Platform.iOS.ButtonRenderer));
//#elif WINDOWS
// handlers.AddCompatibilityRenderer(typeof(CustomButton),
// typeof(Microsoft.Maui.Controls.Compatibility.Platform.UWP.ButtonRenderer));
// #elif TIZEN
// handlers.AddCompatibilityRenderer(typeof(CustomButton),
// typeof(Microsoft.Maui.Controls.Compatibility.Platform.Tizen.ButtonRenderer));
// #endif
//#pragma warning restore CS0618 // Type or member is obsolete
// });
// Use a "third party" library that brings in a massive amount of controls
appBuilder.UseBordelessEntry();
appBuilder.ConfigureEffects(builder =>
{
builder.Add<FocusRoutingEffect, FocusPlatformEffect>();
});
appBuilder.Configuration.AddInMemoryCollection(
new Dictionary<string, string?>
{
{"MyKey", "Dictionary MyKey Value"},
{":Title", "Dictionary_Title"},
{"Position:Name", "Dictionary_Name" },
{"Logging:LogLevel:Default", "Warning"}
});
services.AddMauiBlazorWebView();
#if DEBUG
services.AddBlazorWebViewDeveloperTools();
services.AddHybridWebViewDeveloperTools();
#endif
services.AddLogging(logging =>
{
#if WINDOWS
logging.AddDebug();
#else
logging.AddConsole();
#endif
// Enable maximum logging for BlazorWebView
logging.AddFilter("Microsoft.AspNetCore.Components.WebView", LogLevel.Trace);
});
services.AddSingleton<ITextService, TextService>();
services.AddTransient<MainViewModel>();
services.AddTransient<IWindow, Window>();
services.AddTransient<CustomFlyoutPage, CustomFlyoutPage>();
services.AddTransient<CustomNavigationPage, CustomNavigationPage>();
services.AddTransient(
serviceType: typeof(Page),
implementationType: _pageType switch
{
PageType.Template => typeof(TemplatePage),
PageType.Shell => typeof(AppShell),
PageType.Main => typeof(CustomNavigationPage),
PageType.FlyoutPage => typeof(CustomFlyoutPage),
PageType.TabbedPage => typeof(Pages.TabbedPageGallery),
PageType.Blazor => typeof(BlazorPage),
_ => throw new Exception(),
});
appBuilder
.ConfigureFonts(fonts =>
{
fonts.AddFont("Dokdo-Regular.ttf", "Dokdo");
fonts.AddFont("LobsterTwo-Regular.ttf", "Lobster Two");
fonts.AddFont("LobsterTwo-Bold.ttf", "Lobster Two Bold");
fonts.AddFont("LobsterTwo-Italic.ttf", "Lobster Two Italic");
fonts.AddFont("LobsterTwo-BoldItalic.ttf", "Lobster Two BoldItalic");
fonts.AddFont("ionicons.ttf", "Ionicons");
fonts.AddFont("SegoeUI.ttf", "Segoe UI");
fonts.AddFont("SegoeUI-Bold.ttf", "Segoe UI Bold");
fonts.AddFont("SegoeUI-Italic.ttf", "Segoe UI Italic");
fonts.AddFont("SegoeUI-Bold-Italic.ttf", "Segoe UI Bold Italic");
})
.ConfigureEssentials(essentials =>
{
essentials
.UseMapServiceToken("YOUR-KEY-HERE")
.AddAppAction("test_action", "Test App Action")
.AddAppAction("second_action", "Second App Action")
.OnAppAction(appAction =>
{
Debug.WriteLine($"You seem to have arrived from a special place: {appAction.Title} ({appAction.Id})");
});
// TODO: Unpackaged apps need to know the package ID and local data locations
if (AppInfo.PackagingModel == AppPackagingModel.Packaged)
essentials.UseVersionTracking();
})
.ConfigureLifecycleEvents(events =>
{
events.AddEvent<Action<string>>("CustomEventName", value => LogEvent("CustomEventName"));
#if __ANDROID__
// Log everything in this one
events.AddAndroid(android => android
.OnActivityResult((a, b, c, d) => LogEvent(nameof(AndroidLifecycle.OnActivityResult), b.ToString()))
.OnBackPressed((a) => LogEvent(nameof(AndroidLifecycle.OnBackPressed)) && false)
.OnConfigurationChanged((a, b) => LogEvent(nameof(AndroidLifecycle.OnConfigurationChanged)))
.OnCreate((a, b) => LogEvent(nameof(AndroidLifecycle.OnCreate)))
.OnDestroy((a) => LogEvent(nameof(AndroidLifecycle.OnDestroy)))
.OnNewIntent((a, b) => LogEvent(nameof(AndroidLifecycle.OnNewIntent)))
.OnPause((a) => LogEvent(nameof(AndroidLifecycle.OnPause)))
.OnPostCreate((a, b) => LogEvent(nameof(AndroidLifecycle.OnPostCreate)))
.OnPostResume((a) => LogEvent(nameof(AndroidLifecycle.OnPostResume)))
.OnRequestPermissionsResult((a, b, c, d) => LogEvent(nameof(AndroidLifecycle.OnRequestPermissionsResult)))
.OnRestart((a) => LogEvent(nameof(AndroidLifecycle.OnRestart)))
.OnRestoreInstanceState((a, b) => LogEvent(nameof(AndroidLifecycle.OnRestoreInstanceState)))
.OnResume((a) => LogEvent(nameof(AndroidLifecycle.OnResume)))
.OnSaveInstanceState((a, b) => LogEvent(nameof(AndroidLifecycle.OnSaveInstanceState)))
.OnStart((a) => LogEvent(nameof(AndroidLifecycle.OnStart)))
.OnStop((a) => LogEvent(nameof(AndroidLifecycle.OnStop))));
// Add some cool features/things
var shouldPreventBack = 1;
events.AddAndroid(android => android
.OnResume(a =>
{
LogEvent(nameof(AndroidLifecycle.OnResume), "shortcut");
})
.OnBackPressed(a => LogEvent(nameof(AndroidLifecycle.OnBackPressed), "shortcut") && (shouldPreventBack-- > 0))
.OnRestoreInstanceState((a, b) =>
{
LogEvent(nameof(AndroidLifecycle.OnRestoreInstanceState), "shortcut");
Debug.WriteLine($"{b.GetString("test2", "fail")} == {b.GetBoolean("test", false)}");
})
.OnSaveInstanceState((a, b) =>
{
LogEvent(nameof(AndroidLifecycle.OnSaveInstanceState), "shortcut");
b.PutBoolean("test", true);
b.PutString("test2", "yay");
}));
#elif __IOS__
// Log everything in this one
events.AddiOS(ios => ios
.ContinueUserActivity((a, b, c) => LogEvent(nameof(iOSLifecycle.ContinueUserActivity)) && false)
.DidEnterBackground((a) => LogEvent(nameof(iOSLifecycle.DidEnterBackground)))
.FinishedLaunching((a, b) => LogEvent(nameof(iOSLifecycle.FinishedLaunching)) && true)
.OnActivated((a) => LogEvent(nameof(iOSLifecycle.OnActivated)))
.OnResignActivation((a) => LogEvent(nameof(iOSLifecycle.OnResignActivation)))
.OpenUrl((a, b, c) => LogEvent(nameof(iOSLifecycle.OpenUrl)) && false)
.PerformActionForShortcutItem((a, b, c) => LogEvent(nameof(iOSLifecycle.PerformActionForShortcutItem)))
.WillEnterForeground((a) => LogEvent(nameof(iOSLifecycle.WillEnterForeground)))
.ApplicationSignificantTimeChange((a) => LogEvent(nameof(iOSLifecycle.ApplicationSignificantTimeChange)))
.WillTerminate((a) => LogEvent(nameof(iOSLifecycle.WillTerminate))));
#elif WINDOWS
// Log everything in this one
events.AddWindows(windows => windows
// .OnPlatformMessage((a, b) =>
// LogEvent(nameof(WindowsLifecycle.OnPlatformMessage)))
.OnActivated((a, b) => LogEvent(nameof(WindowsLifecycle.OnActivated)))
.OnClosed((a, b) => LogEvent(nameof(WindowsLifecycle.OnClosed)))
.OnLaunched((a, b) => LogEvent(nameof(WindowsLifecycle.OnLaunched)))
.OnVisibilityChanged((a, b) => LogEvent(nameof(WindowsLifecycle.OnVisibilityChanged))));
#elif TIZEN
events.AddTizen(tizen => tizen
.OnAppControlReceived((a, b) => LogEvent(nameof(TizenLifecycle.OnAppControlReceived)))
.OnCreate((a) => LogEvent(nameof(TizenLifecycle.OnCreate)))
.OnDeviceOrientationChanged((a, b) => LogEvent(nameof(TizenLifecycle.OnDeviceOrientationChanged)))
.OnLocaleChanged((a, b) => LogEvent(nameof(TizenLifecycle.OnLocaleChanged)))
.OnLowBattery((a, b) => LogEvent(nameof(TizenLifecycle.OnLowBattery)))
.OnLowMemory((a, b) => LogEvent(nameof(TizenLifecycle.OnLowMemory)))
.OnPause((a) => LogEvent(nameof(TizenLifecycle.OnPause)))
.OnPreCreate((a) => LogEvent(nameof(TizenLifecycle.OnPreCreate)))
.OnRegionFormatChanged((a, b) => LogEvent(nameof(TizenLifecycle.OnRegionFormatChanged)))
.OnResume((a) => LogEvent(nameof(TizenLifecycle.OnResume)))
.OnTerminate((a) => LogEvent(nameof(TizenLifecycle.OnTerminate))));
#endif
static bool LogEvent(string eventName, string? type = null)
{
Debug.WriteLine($"Lifecycle event: {eventName}{(type == null ? "" : $" ({type})")}");
return true;
}
});
// Adapt to dual-screen and foldable Android devices like Surface Duo, includes TwoPaneView layout control
appBuilder.UseFoldable();
// If someone wanted to completely turn off the CascadeInputTransparent behavior in their application, this next line would be an easy way to do it
// Microsoft.Maui.Controls.Layout.ControlsLayoutMapper.ModifyMapping(nameof(Microsoft.Maui.Controls.Layout.CascadeInputTransparent), (_, _, _) => { });
Microsoft.Maui.Handlers.EntryHandler.Mapper.AppendToMapping(nameof(TransparentEntry), (handler, view) =>
{
if (view is TransparentEntry)
{
#if ANDROID
handler.PlatformView.Background = null;
handler.PlatformView.SetBackgroundColor(Android.Graphics.Color.Transparent);
#elif IOS
handler.PlatformView.BackgroundColor = UIKit.UIColor.Clear;
handler.PlatformView.Layer.BorderWidth = 0;
handler.PlatformView.BorderStyle = UIKit.UITextBorderStyle.None;
#endif
}
});
return appBuilder.Build();
}
}
}
| PageType |
csharp | dotnet__maui | src/Controls/tests/TestCases.Shared.Tests/Tests/FeatureMatrix/CarouselViewFeatureTests.cs | {
"start": 107,
"end": 49388
} | public class ____ : UITest
{
public const string CarouselViewFeatureMatrix = "CarouselView Feature Matrix";
private const string CarouselViewControl = "CarouselViewControl";
private const string Options = "Options";
private const string Apply = "Apply";
private const string ItemTemplateGrid = "ItemTemplateGrid";
private const string ItemTemplateCustomView = "ItemTemplateCustomView";
private const string EmptyViewString = "EmptyViewString";
private const string EmptyViewCustomView = "EmptyViewCustomView";
private const string EmptyViewDataTemplate = "EmptyViewDataTemplate";
private const string ItemsSourceNone = "ItemsSourceNone";
private const string ItemsLayoutVertical = "ItemsLayoutVertical";
private const string KeepItemsInView = "KeepItemsInView";
private const string KeepScrollOffset = "KeepScrollOffset";
private const string KeepLastItemInView = "KeepLastItemInView";
private const string LoopLabel = "LoopLabel";
private const string SwipeLabel = "SwipeLabel";
private const string AddButton = "AddButton";
private const string PositionEntry = "PositionEntry";
private const string CurrentPositionLabel = "CurrentPositionLabel";
private const string PreviousPositionLabel = "PreviousPositionLabel";
private const string CurrentItemLabel = "CurrentItemLabel";
private const string PreviousItemLabel = "PreviousItemLabel";
private const string ScrollToIndexEntry = "ScrollToIndexEntry";
private const string ScrollToButton = "ScrollToButton";
public CarouselViewFeatureTests(TestDevice device) : base(device)
{
}
protected override void FixtureSetup()
{
base.FixtureSetup();
App.NavigateToGallery(CarouselViewFeatureMatrix);
}
[Test, Order(1)]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithKeepItemInView()
{
App.WaitForElement("CarouselViewButton");
App.Tap("CarouselViewButton");
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepItemsInView);
App.Tap(KeepItemsInView);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
}
#if TEST_FAILS_ON_WINDOWS //In windows related issue link: https://github.com/dotnet/maui/issues/29529
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithKeepItemInViewAndCurrentItem()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepItemsInView);
App.Tap(KeepItemsInView);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 1"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 6"));
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithKeepItemInViewAndCurrentPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepItemsInView);
App.Tap(KeepItemsInView);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(CurrentPositionLabel).GetText(), Is.EqualTo("0"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
Assert.That(App.WaitForElement(CurrentPositionLabel).GetText(), Is.EqualTo("0"));
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithKeepItemInViewAndPreviousItem()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepItemsInView);
App.Tap(KeepItemsInView);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("No previous item"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("Item 1"));
}
#if TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS //In CV2 related issue link: https://github.com/dotnet/maui/issues/29524
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithKeepItemInViewAndPreviousPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepItemsInView);
App.Tap(KeepItemsInView);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("No previous position"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 7");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("1"));
}
#endif
#endif
#if TEST_FAILS_ON_WINDOWS //In windows related issue link: https://github.com/dotnet/maui/issues/29462
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithGridLayout()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemTemplateGrid);
App.Tap(ItemTemplateGrid);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1 (Grid Template)");
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithImageView()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemTemplateCustomView);
App.Tap(ItemTemplateCustomView);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1 (Image View)");
}
#endif
#if TEST_FAILS_ON_WINDOWS //related issue link: https://github.com/dotnet/maui/issues/28334 && https://github.com/dotnet/maui/issues/28022 && https://github.com/dotnet/maui/issues/29463 && https://github.com/dotnet/maui/issues/29472
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithEmptyViewString()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsSourceNone);
App.Tap(ItemsSourceNone);
App.WaitForElement(EmptyViewString);
App.Tap(EmptyViewString);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("No items available");
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithEmptyViewImageView()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsSourceNone);
App.Tap(ItemsSourceNone);
App.WaitForElement(EmptyViewCustomView);
App.Tap(EmptyViewCustomView);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("No items available(Custom View)");
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithEmptyViewTemplate()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsSourceNone);
App.Tap(ItemsSourceNone);
App.WaitForElement(EmptyViewDataTemplate);
App.Tap(EmptyViewDataTemplate);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("No items available (DataTemplate)");
}
#endif
#if TEST_FAILS_ON_ANDROID //In android related issue: https://github.com/dotnet/maui/issues/29415
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithKeepScrollOffset()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepScrollOffset);
App.Tap(KeepScrollOffset);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 1");
}
#if TEST_FAILS_ON_WINDOWS //In CV2 related issue link: https://github.com/dotnet/maui/issues/29524 && In windows related issue link: https://github.com/dotnet/maui/issues/29529
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithKeepScrollOffsetAndCurrentItem()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepScrollOffset);
App.Tap(KeepScrollOffset);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 1"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 1"));
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithKeepScrollOffsetAndCurrentPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepScrollOffset);
App.Tap(KeepScrollOffset);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(CurrentPositionLabel).GetText(), Is.EqualTo("0"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(CurrentPositionLabel).GetText(), Is.EqualTo("1"));
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithKeepScrollOffsetAndPreviousItem()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepScrollOffset);
App.Tap(KeepScrollOffset);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("No previous item"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("Item 6"));
}
#if TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS //In CV2 related issue link: https://github.com/dotnet/maui/issues/29524
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithKeepScrollOffsetAndPreviousPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepScrollOffset);
App.Tap(KeepScrollOffset);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("No previous position"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("0"));
}
#endif
#endif
#endif
#if TEST_FAILS_ON_WINDOWS //related issue link: https://github.com/dotnet/maui/issues/29420 && https://github.com/dotnet/maui/issues/29529
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithKeepLastItemInView()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepLastItemInView);
App.Tap(KeepLastItemInView);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 5");
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithKeepLastItemInViewAndCurrentItem()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepLastItemInView);
App.Tap(KeepLastItemInView);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 1"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 5");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 5"));
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithKeepLastItemInViewAndCurrentPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepLastItemInView);
App.Tap(KeepLastItemInView);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(CurrentPositionLabel).GetText(), Is.EqualTo("0"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 5");
Assert.That(App.WaitForElement(CurrentPositionLabel).GetText(), Is.EqualTo("5"));
}
#if TEST_FAILS_ON_ANDROID // Issue link: https://github.com/dotnet/maui/issues/29544
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithKeepLastItemInViewAndPreviousItem()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepLastItemInView);
App.Tap(KeepLastItemInView);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("No previous item"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 5");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("Item 6"));
}
#endif
#if TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS && TEST_FAILS_ON_ANDROID//In CV2 related issue link: https://github.com/dotnet/maui/issues/29529 Android related issue link: https://github.com/dotnet/maui/issues/29544
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithKeepLastItemInViewAndPreviousPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepLastItemInView);
App.Tap(KeepLastItemInView);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("No previous position"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 5");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("0"));
}
#endif
#endif
#if TEST_FAILS_ON_ANDROID && TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS && TEST_FAILS_ON_WINDOWS //In windows related issue : https://github.com/dotnet/maui/issues/29420 && In android related issue: https://github.com/dotnet/maui/issues/29415 && In CV2 related issue:https://github.com/dotnet/maui/issues/29449
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithIsLoopEnabledAndKeepItemInView()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepItemsInView);
App.Tap(KeepItemsInView);
App.WaitForElement(LoopLabel);
App.Tap(LoopLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithIsLoopEnabledAndKeepScrollOffset()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepScrollOffset);
App.Tap(KeepScrollOffset);
App.WaitForElement(LoopLabel);
App.Tap(LoopLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 1");
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithIsLoopEnabledAndKeepLastItemInView()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(KeepLastItemInView);
App.Tap(KeepLastItemInView);
App.WaitForElement(LoopLabel);
App.Tap(LoopLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 5");
}
#endif
#if TEST_FAILS_ON_ANDROID && TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS && TEST_FAILS_ON_WINDOWS //In android related issue link: https://github.com/dotnet/maui/issues/29411, In Windows related issue link:https://github.com/dotnet/maui/issues/29412 && CV2 related issue:https://github.com/dotnet/maui/issues/29449 && https://github.com/dotnet/maui/issues/29261
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithIsLoopEnabled()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(LoopLabel);
App.Tap(LoopLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
for (int i = 1; i < 7; i++)
{
App.ScrollRight(CarouselViewControl, ScrollStrategy.Gesture, 0.9, 500);
}
App.WaitForElement("Item 2");
}
#endif
#if TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS // related issue link:https://github.com/dotnet/maui/issues/29391
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithIsSwipeDisable()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(SwipeLabel);
App.Tap(SwipeLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
for (int i = 1; i < 2; i++)
{
App.ScrollRight(CarouselViewControl, ScrollStrategy.Gesture, 0.9, 500);
}
App.WaitForElement("Item 1");
}
#endif
#if TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS && TEST_FAILS_ON_WINDOWS//In CV2 related issue link: https://github.com/dotnet/maui/issues/29312 and In windows related issue link: https://github.com/dotnet/maui/issues/15443
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(PositionEntry);
App.Tap(PositionEntry);
App.ClearText(PositionEntry);
App.EnterText(PositionEntry, "2");
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 3");
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithPositionAndCurrentItem()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(PositionEntry);
App.Tap(PositionEntry);
App.ClearText(PositionEntry);
App.EnterText(PositionEntry, "1");
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 2");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 2"));
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithPositionAndCurrentPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(PositionEntry);
App.Tap(PositionEntry);
App.ClearText(PositionEntry);
App.EnterText(PositionEntry, "1");
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 2");
Assert.That(App.WaitForElement(CurrentPositionLabel).GetText(), Is.EqualTo("1"));
}
#if TEST_FAILS_ON_ANDROID //In android related issue link: https://github.com/dotnet/maui/issues/29544
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithPositionAndPreviousItem()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(PositionEntry);
App.Tap(PositionEntry);
App.ClearText(PositionEntry);
App.EnterText(PositionEntry, "1");
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 2");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("Item 1"));
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithPositionAndPreviousPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(PositionEntry);
App.Tap(PositionEntry);
App.ClearText(PositionEntry);
App.EnterText(PositionEntry, "1");
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 2");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("0"));
}
#endif
#endif
#if TEST_FAILS_ON_WINDOWS //In windows related issue link: https://github.com/dotnet/maui/issues/15443
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithScrollToAndCurrentItem()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(ScrollToIndexEntry);
App.ClearText(ScrollToIndexEntry);
App.EnterText(ScrollToIndexEntry, "1");
App.WaitForElement(ScrollToButton);
App.Tap(ScrollToButton);
App.WaitForElement("Item 2");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 2"));
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithScrollToAndCurrentPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(ScrollToIndexEntry);
App.ClearText(ScrollToIndexEntry);
App.EnterText(ScrollToIndexEntry, "1");
App.WaitForElement(ScrollToButton);
App.Tap(ScrollToButton);
App.WaitForElement("Item 2");
Assert.That(App.WaitForElement(CurrentPositionLabel).GetText(), Is.EqualTo("1"));
}
#if TEST_FAILS_ON_ANDROID //In android related issue link: https://github.com/dotnet/maui/issues/29544
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithScrollToAndPreviousItem()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(ScrollToIndexEntry);
App.ClearText(ScrollToIndexEntry);
App.EnterText(ScrollToIndexEntry, "1");
App.WaitForElement(ScrollToButton);
App.Tap(ScrollToButton);
App.WaitForElement("Item 2");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("Item 1"));
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithScrollToAndPreviousPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(ScrollToIndexEntry);
App.ClearText(ScrollToIndexEntry);
App.EnterText(ScrollToIndexEntry, "1");
App.WaitForElement(ScrollToButton);
App.Tap(ScrollToButton);
App.WaitForElement("Item 2");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("0"));
}
#endif
#endif
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithPeekAreaInsets()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement("PeekAreaInsetsEntry");
App.Tap("PeekAreaInsetsEntry");
App.ClearText("PeekAreaInsetsEntry");
App.EnterText("PeekAreaInsetsEntry", "120");
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement("Item 2");
}
#if TEST_FAILS_ON_WINDOWS //In windows related issue link: https://github.com/dotnet/maui/issues/29529
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithCurrentItems()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 1"));
App.ScrollRight(CarouselViewControl, ScrollStrategy.Gesture, 0.9, 500);
App.WaitForElement("Item 2");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 2"));
}
#if TEST_FAILS_ON_ANDROID && TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS && TEST_FAILS_ON_WINDOWS //In android related issue link: https://github.com/dotnet/maui/issues/29411, In Windows related issue link: https://github.com/dotnet/maui/issues/29412 && CV2 related issue link:https://github.com/dotnet/maui/issues/29449 && https://github.com/dotnet/maui/issues/29261
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithEnableLoopAndCurrentItem()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(LoopLabel);
App.Tap(LoopLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 1"));
App.ScrollLeft(CarouselViewControl, ScrollStrategy.Gesture, 0.9, 500);
App.WaitForElement("Item 5");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 5"));
}
#endif
#if TEST_FAILS_ON_WINDOWS //In windows related issue link:https://github.com/dotnet/maui/issues/29529
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithCurrentPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
Assert.That(App.WaitForElement(CurrentPositionLabel).GetText(), Is.EqualTo("0"));
}
#endif
#if TEST_FAILS_ON_ANDROID && TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS && TEST_FAILS_ON_WINDOWS //In android related issue link: https://github.com/dotnet/maui/issues/29411, In Windows related issue link:https://github.com/dotnet/maui/issues/29412 && In CV2 related issue link:https://github.com/dotnet/maui/issues/29449
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithEnableLoopAndCurrentPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(LoopLabel);
App.Tap(LoopLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(CurrentPositionLabel).GetText(), Is.EqualTo("0"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
Assert.That(App.WaitForElement(CurrentPositionLabel).GetText(), Is.EqualTo("0"));
}
#endif
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithPreviousItem()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("No previous item"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("Item 1"));
}
#if TEST_FAILS_ON_ANDROID && TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS && TEST_FAILS_ON_WINDOWS //In android related issue link: https://github.com/dotnet/maui/issues/29411, In Windows related issue link:https://github.com/dotnet/maui/issues/29412 && CV2 related issue link:https://github.com/dotnet/maui/issues/29449
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithEnableLoopAndPreviousItem()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(LoopLabel);
App.Tap(LoopLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("No previous item"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("Item 1"));
}
#endif
#if TEST_FAILS_ON_IOS && TEST_FAILS_ON_CATALYST //In CV2 related issue link: https://github.com/dotnet/maui/issues/29524
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithPreviousPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("No previous position"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("1"));
}
#endif
#endif
#if TEST_FAILS_ON_ANDROID && TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS && TEST_FAILS_ON_WINDOWS //In android related issue link: https://github.com/dotnet/maui/issues/29411, In Windows related issue link:https://github.com/dotnet/maui/issues/29412 && CV2 related issue link: https://github.com/dotnet/maui/issues/29449 && https://github.com/dotnet/maui/issues/29524
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithEnableLoopAndPreviousPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(LoopLabel);
App.Tap(LoopLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("No previous position"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("1"));
}
#endif
#if TEST_FAILS_ON_WINDOWS //In windows related issue link: https://github.com/dotnet/maui/issues/29448
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithScrollTo()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(ScrollToIndexEntry);
App.ClearText(ScrollToIndexEntry);
App.EnterText(ScrollToIndexEntry, "3");
App.WaitForElement(ScrollToButton);
App.Tap(ScrollToButton);
App.WaitForElement("Item 4");
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithIsSwipeDisableAndScrollTo()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(SwipeLabel);
App.Tap(SwipeLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(ScrollToIndexEntry);
App.ClearText(ScrollToIndexEntry);
App.EnterText(ScrollToIndexEntry, "3");
App.WaitForElement(ScrollToButton);
App.Tap(ScrollToButton);
App.WaitForElement("Item 4");
}
#endif
#if TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS //In CV2 related issue link: https://github.com/dotnet/maui/issues/27711
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithRTLFlowDirection()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement("FlowDirectionRTL");
App.Tap("FlowDirectionRTL");
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.ScrollRight(CarouselViewControl, ScrollStrategy.Gesture, 0.9, 500);
App.WaitForElement("Item 1");
}
#endif
#if TEST_FAILS_ON_ANDROID && TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS && TEST_FAILS_ON_WINDOWS // related issue link: https://github.com/dotnet/maui/issues/29372
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayout()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
for (int i = 1; i < 5; i++)
{
App.ScrollDown(CarouselViewControl, ScrollStrategy.Gesture, 0.9, 500);
}
App.WaitForElement("Item 5");
}
#if TEST_FAILS_ON_ANDROID && TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS && TEST_FAILS_ON_WINDOWS
// Android related issue link: https://github.com/dotnet/maui/issues/29544 In CV2 related issue link: https://github.com/dotnet/maui/issues/29312 and In windows related issue link: https://github.com/dotnet/maui/issues/15443
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(PositionEntry);
App.Tap(PositionEntry);
App.ClearText(PositionEntry);
App.EnterText(PositionEntry, "1");
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 2");
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewCurrentItemWithVerticalLayoutAndPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(PositionEntry);
App.Tap(PositionEntry);
App.ClearText(PositionEntry);
App.EnterText(PositionEntry, "1");
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 2");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 2"));
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewPreviousItemWithVerticalLayoutAndPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(PositionEntry);
App.Tap(PositionEntry);
App.ClearText(PositionEntry);
App.EnterText(PositionEntry, "1");
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 2");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("Item 1"));
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewPreviousPositionWithVerticalLayoutAndPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(PositionEntry);
App.Tap(PositionEntry);
App.ClearText(PositionEntry);
App.EnterText(PositionEntry, "1");
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 2");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("0"));
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewCurrentPositionWithVerticalLayoutAndPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(PositionEntry);
App.Tap(PositionEntry);
App.ClearText(PositionEntry);
App.EnterText(PositionEntry, "1");
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 2");
Assert.That(App.WaitForElement(CurrentPositionLabel).GetText(), Is.EqualTo("1"));
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewCurrentItemWithVerticalLayoutAndScrollTo()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(ScrollToIndexEntry);
App.ClearText(ScrollToIndexEntry);
App.EnterText(ScrollToIndexEntry, "1");
App.WaitForElement(ScrollToButton);
App.Tap(ScrollToButton);
App.WaitForElement("Item 2");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 2"));
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewPreviousItemWithVerticalLayoutAndScrollTo()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(ScrollToIndexEntry);
App.ClearText(ScrollToIndexEntry);
App.EnterText(ScrollToIndexEntry, "1");
App.WaitForElement(ScrollToButton);
App.Tap(ScrollToButton);
App.WaitForElement("Item 2");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("Item 1"));
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewCurrentPositionWithVerticalLayoutAndScrollTo()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(ScrollToIndexEntry);
App.ClearText(ScrollToIndexEntry);
App.EnterText(ScrollToIndexEntry, "1");
App.WaitForElement(ScrollToButton);
App.Tap(ScrollToButton);
App.WaitForElement("Item 2");
Assert.That(App.WaitForElement(CurrentPositionLabel).GetText(), Is.EqualTo("1"));
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewPreviousPositionWithVerticalLayoutAndScrollTo()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(ScrollToIndexEntry);
App.ClearText(ScrollToIndexEntry);
App.EnterText(ScrollToIndexEntry, "1");
App.WaitForElement(ScrollToButton);
App.Tap(ScrollToButton);
App.WaitForElement("Item 2");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("0"));
}
#endif
#if TEST_FAILS_ON_ANDROID && TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS && TEST_FAILS_ON_WINDOWS //In android related issue link: https://github.com/dotnet/maui/issues/29411, In Windows related issue link:https://github.com/dotnet/maui/issues/29412 && CV2 related issue link: https://github.com/dotnet/maui/issues/29449 && https://github.com/dotnet/maui/issues/29524
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndEnableLoop()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(LoopLabel);
App.Tap(LoopLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
for (int i = 1; i < 7; i++)
{
App.ScrollDown(CarouselViewControl, ScrollStrategy.Gesture, 0.9, 500);
}
App.WaitForElement("Item 2");
}
#endif
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndKeepItemInView()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(KeepItemsInView);
App.Tap(KeepItemsInView);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndKeepScrollOffset()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(KeepScrollOffset);
App.Tap(KeepScrollOffset);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 1");
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndKeepLastItemInView()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(KeepLastItemInView);
App.Tap(KeepLastItemInView);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 5");
}
#if TEST_FAILS_ON_ANDROID && TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS && TEST_FAILS_ON_WINDOWS //In android related issue link: https://github.com/dotnet/maui/issues/29411, In Windows related issue link:https://github.com/dotnet/maui/issues/29412 && CV2 related issue link: https://github.com/dotnet/maui/issues/29449 && https://github.com/dotnet/maui/issues/29524
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndIsLoopEnabled()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(LoopLabel);
App.Tap(LoopLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
for (int i = 1; i < 7; i++)
{
App.ScrollDown(CarouselViewControl, ScrollStrategy.Gesture, 0.9, 500);
}
App.WaitForElement("Item 2");
}
#endif
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndIsSwipeEnabled()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(SwipeLabel);
App.Tap(SwipeLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
for (int i = 1; i < 2; i++)
{
App.ScrollDown(CarouselViewControl, ScrollStrategy.Gesture, 0.9, 500);
}
App.WaitForElement("Item 1");
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndPeekAreaInsets()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement("PeekAreaInsetsEntry");
App.Tap("PeekAreaInsetsEntry");
App.ClearText("PeekAreaInsetsEntry");
App.EnterText("PeekAreaInsetsEntry", "120");
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement("Item 2");
}
#if TEST_FAILS_ON_WINDOWS //In windows related issue link: https://github.com/dotnet/maui/issues/29529
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndCurrentItems()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 1"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 6"));
}
#if TEST_FAILS_ON_ANDROID && TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS && TEST_FAILS_ON_WINDOWS //In android related issue link: https://github.com/dotnet/maui/issues/29411, In Windows related issue link:https://github.com/dotnet/maui/issues/29412 && CV2 related issue link: https://github.com/dotnet/maui/issues/29449 && https://github.com/dotnet/maui/issues/29524
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndEnableLoopAndCurrentItem()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(LoopLabel);
App.Tap(LoopLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 1"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
Assert.That(App.WaitForElement(CurrentItemLabel).GetText(), Is.EqualTo("Item 6"));
}
#endif
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndCurrentPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(CurrentPositionLabel).GetText(), Is.EqualTo("0"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
Assert.That(App.WaitForElement(CurrentPositionLabel).GetText(), Is.EqualTo("0"));
}
#if TEST_FAILS_ON_ANDROID && TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS && TEST_FAILS_ON_WINDOWS //In android related issue link: https://github.com/dotnet/maui/issues/29411, In Windows related issue link:https://github.com/dotnet/maui/issues/29412 && CV2 related issue link: https://github.com/dotnet/maui/issues/29449 && https://github.com/dotnet/maui/issues/29524
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndEnableLoopAndCurrentPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(LoopLabel);
App.Tap(LoopLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(CurrentPositionLabel).GetText(), Is.EqualTo("0"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
Assert.That(App.WaitForElement(CurrentPositionLabel).GetText(), Is.EqualTo("0"));
}
#endif
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndPreviousItem()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("No previous item"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("Item 1"));
}
#endif
#if TEST_FAILS_ON_ANDROID && TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS && TEST_FAILS_ON_WINDOWS //In android related issue link: https://github.com/dotnet/maui/issues/29411, In Windows related issue link:https://github.com/dotnet/maui/issues/29412 && CV2 related issue link: https://github.com/dotnet/maui/issues/29449 && https://github.com/dotnet/maui/issues/29524
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndEnableLoopAndPreviousItem()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(LoopLabel);
App.Tap(LoopLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("No previous item"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
Assert.That(App.WaitForElement(PreviousItemLabel).GetText(), Is.EqualTo("Item 1"));
}
#endif
#if TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS //In CV2 related issue link: https://github.com/dotnet/maui/issues/29524
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndPreviousPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("No previous position"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("1"));
}
#if TEST_FAILS_ON_ANDROID && TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS && TEST_FAILS_ON_WINDOWS //In android related issue link: https://github.com/dotnet/maui/issues/29411, In Windows related issue link:https://github.com/dotnet/maui/issues/29412 && CV2 related issue link: https://github.com/dotnet/maui/issues/29449 && https://github.com/dotnet/maui/issues/29524
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndEnableLoopAndPreviousPosition()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(LoopLabel);
App.Tap(LoopLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("No previous position"));
App.WaitForElement(AddButton);
App.Tap(AddButton);
App.WaitForElement("Item 6");
Assert.That(App.WaitForElement(PreviousPositionLabel).GetText(), Is.EqualTo("1"));
}
#endif
#endif
#if TEST_FAILS_ON_WINDOWS //In windows related issue link: https://github.com/dotnet/maui/issues/29448
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndScrollTo()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(ScrollToIndexEntry);
App.ClearText(ScrollToIndexEntry);
App.EnterText(ScrollToIndexEntry, "3");
App.WaitForElement(ScrollToButton);
App.Tap(ScrollToButton);
App.WaitForElement("Item 4");
}
#if TEST_FAILS_ON_ANDROID && TEST_FAILS_ON_CATALYST && TEST_FAILS_ON_IOS && TEST_FAILS_ON_WINDOWS //In android related issue link: https://github.com/dotnet/maui/issues/29411, In Windows related issue link:https://github.com/dotnet/maui/issues/29412 && CV2 related issue link: https://github.com/dotnet/maui/issues/29449 && https://github.com/dotnet/maui/issues/29524
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndIsLoopEnableAndScrollTo()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(LoopLabel);
App.Tap(LoopLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(ScrollToIndexEntry);
App.ClearText(ScrollToIndexEntry);
App.EnterText(ScrollToIndexEntry, "3");
App.WaitForElement(ScrollToButton);
App.Tap(ScrollToButton);
App.WaitForElement("Item 4");
}
[Test]
[Category(UITestCategories.CarouselView)]
public void VerifyCarouselViewWithVerticalLayoutAndIsSwipeDisableAndScrollTo()
{
App.WaitForElement(Options);
App.Tap(Options);
App.WaitForElement(ItemsLayoutVertical);
App.Tap(ItemsLayoutVertical);
App.WaitForElement(SwipeLabel);
App.Tap(SwipeLabel);
App.WaitForElement(Apply);
App.Tap(Apply);
App.WaitForElement("Item 1");
App.WaitForElement(ScrollToIndexEntry);
App.ClearText(ScrollToIndexEntry);
App.EnterText(ScrollToIndexEntry, "3");
App.WaitForElement(ScrollToButton);
App.Tap(ScrollToButton);
App.WaitForElement("Item 4");
}
#endif
#endif
#endif
} | CarouselViewFeatureTests |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/Query/AdHocQueryFiltersQueryTestBase.cs | {
"start": 10900,
"end": 11088
} | public class ____
{
public bool Exists { get; set; }
public virtual OptionalChangePoint12170 RemovedPoint { get; set; }
}
| MasterChangeInfo12170 |
csharp | dotnet__maui | src/Controls/src/Core/PropertyChangedEventArgsExtensions.cs | {
"start": 124,
"end": 2154
} | internal static class ____
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool Is(this PropertyChangedEventArgs args, BindableProperty property)
{
if (string.IsNullOrEmpty(args.PropertyName))
return true;
return args.PropertyName == property.PropertyName;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsOneOf(this PropertyChangedEventArgs args, BindableProperty p0, BindableProperty p1)
{
if (string.IsNullOrEmpty(args.PropertyName))
return true;
return args.PropertyName == p0.PropertyName ||
args.PropertyName == p1.PropertyName;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsOneOf(this PropertyChangedEventArgs args, BindableProperty p0, BindableProperty p1, BindableProperty p2)
{
if (string.IsNullOrEmpty(args.PropertyName))
return true;
return args.PropertyName == p0.PropertyName ||
args.PropertyName == p1.PropertyName ||
args.PropertyName == p2.PropertyName;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsOneOf(this PropertyChangedEventArgs args, BindableProperty p0, BindableProperty p1, BindableProperty p2, BindableProperty p3)
{
if (string.IsNullOrEmpty(args.PropertyName))
return true;
return args.PropertyName == p0.PropertyName ||
args.PropertyName == p1.PropertyName ||
args.PropertyName == p2.PropertyName ||
args.PropertyName == p3.PropertyName;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsOneOf(this PropertyChangedEventArgs args, BindableProperty p0, BindableProperty p1, BindableProperty p2, BindableProperty p3, BindableProperty p4)
{
if (string.IsNullOrEmpty(args.PropertyName))
return true;
return args.PropertyName == p0.PropertyName ||
args.PropertyName == p1.PropertyName ||
args.PropertyName == p2.PropertyName ||
args.PropertyName == p3.PropertyName ||
args.PropertyName == p4.PropertyName;
}
}
} | PropertyChangedEventArgsExtensions |
csharp | dotnet__aspnetcore | src/OpenApi/gen/XmlCommentGenerator.Emitter.cs | {
"start": 2529,
"end": 2866
} | record ____(
string? Summary,
string? Description,
string? Remarks,
string? Returns,
string? Value,
bool Deprecated,
List<string>? Examples,
List<XmlParameterComment>? Parameters,
List<XmlResponseComment>? Responses);
{{GeneratedCodeAttribute}}
file | XmlComment |
csharp | jellyfin__jellyfin | MediaBrowser.Model/Dto/TrickplayInfoDto.cs | {
"start": 158,
"end": 1656
} | public record ____
{
/// <summary>
/// Initializes a new instance of the <see cref="TrickplayInfoDto"/> class.
/// </summary>
/// <param name="info">The trickplay info.</param>
public TrickplayInfoDto(TrickplayInfo info)
{
ArgumentNullException.ThrowIfNull(info);
Width = info.Width;
Height = info.Height;
TileWidth = info.TileWidth;
TileHeight = info.TileHeight;
ThumbnailCount = info.ThumbnailCount;
Interval = info.Interval;
Bandwidth = info.Bandwidth;
}
/// <summary>
/// Gets the width of an individual thumbnail.
/// </summary>
public int Width { get; init; }
/// <summary>
/// Gets the height of an individual thumbnail.
/// </summary>
public int Height { get; init; }
/// <summary>
/// Gets the amount of thumbnails per row.
/// </summary>
public int TileWidth { get; init; }
/// <summary>
/// Gets the amount of thumbnails per column.
/// </summary>
public int TileHeight { get; init; }
/// <summary>
/// Gets the total amount of non-black thumbnails.
/// </summary>
public int ThumbnailCount { get; init; }
/// <summary>
/// Gets the interval in milliseconds between each trickplay thumbnail.
/// </summary>
public int Interval { get; init; }
/// <summary>
/// Gets the peak bandwidth usage in bits per second.
/// </summary>
public int Bandwidth { get; init; }
}
| TrickplayInfoDto |
csharp | MassTransit__MassTransit | src/MassTransit.Newtonsoft/Serialization/NewtonsoftXmlMessageSerializer.cs | {
"start": 317,
"end": 3070
} | public class ____ :
IMessageSerializer
{
public const string ContentTypeHeaderValue = "application/vnd.masstransit+xml";
public static readonly ContentType XmlContentType = new ContentType(ContentTypeHeaderValue);
static readonly Lazy<JsonSerializer> _xmlSerializer;
static readonly JsonSerializerSettings XmlSerializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Include,
DefaultValueHandling = DefaultValueHandling.Include,
MissingMemberHandling = MissingMemberHandling.Ignore,
ObjectCreationHandling = ObjectCreationHandling.Auto,
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
Converters = new List<JsonConverter>(new[]
{
new XmlNodeConverter
{
DeserializeRootElementName = "envelope",
WriteArrayAttribute = false,
OmitRootObject = true
}
})
};
static NewtonsoftXmlMessageSerializer()
{
_xmlSerializer = new Lazy<JsonSerializer>(() => JsonSerializer.Create(XmlSerializerSettings));
}
public static JsonSerializer XmlSerializer => _xmlSerializer.Value;
public ContentType ContentType => XmlContentType;
public MessageBody GetMessageBody<T>(SendContext<T> context)
where T : class
{
return new NewtonsoftXmlMessageBody<T>(context);
}
public static void Serialize(Stream stream, object message, Type messageType)
{
var json = new StringBuilder(1024);
using (var stringWriter = new StringWriter(json, CultureInfo.InvariantCulture))
using (var jsonWriter = new JsonTextWriter(stringWriter) { Formatting = Newtonsoft.Json.Formatting.None })
{
NewtonsoftXmlJsonMessageSerializer.Serializer.Serialize(jsonWriter, message, messageType);
jsonWriter.Flush();
stringWriter.Flush();
}
using (var stringReader = new StringReader(json.ToString()))
using (var jsonReader = new JsonTextReader(stringReader))
{
var document = (XDocument)XmlSerializer.Deserialize(jsonReader, typeof(XDocument));
using (var writer = new StreamWriter(stream, MessageDefaults.Encoding, 1024, true))
using (var xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings { CheckCharacters = false }))
{
document.WriteTo(xmlWriter);
}
}
}
}
}
| NewtonsoftXmlMessageSerializer |
csharp | dotnet__aspnetcore | src/Validation/src/ValidationOptions.cs | {
"start": 339,
"end": 3402
} | public class ____
{
/// <summary>
/// Gets the list of resolvers that provide validation metadata for types and parameters.
/// Resolvers are processed in order, with the first resolver that provides a non-null result being used.
/// </summary>
/// <remarks>
/// Source-generated resolvers are typically inserted at the beginning of this list
/// to ensure they are checked before any runtime-based resolvers.
/// </remarks>
[Experimental("ASP0029", UrlFormat = "https://aka.ms/aspnet/analyzer/{0}")]
public IList<IValidatableInfoResolver> Resolvers { get; } = [];
/// <summary>
/// Gets or sets the maximum depth for validation of nested objects.
/// </summary>
/// <value>
/// The default is 32.
/// </value>
/// <remarks>
/// A maximum depth prevents stack overflows from circular references or extremely deep object graphs.
/// </remarks>
public int MaxDepth { get; set; } = 32;
/// <summary>
/// Attempts to get validation information for the specified type.
/// </summary>
/// <param name="type">The type to get validation information for.</param>
/// <param name="validatableTypeInfo">When this method returns, contains the validation information for the specified type,
/// if the type was found; otherwise, <see langword="null" />.</param>
/// <returns><see langword="true" /> if validation information was found for the specified type; otherwise, <see langword="false" />.</returns>
[Experimental("ASP0029", UrlFormat = "https://aka.ms/aspnet/analyzer/{0}")]
public bool TryGetValidatableTypeInfo(Type type, [NotNullWhen(true)] out IValidatableInfo? validatableTypeInfo)
{
foreach (var resolver in Resolvers)
{
if (resolver.TryGetValidatableTypeInfo(type, out validatableTypeInfo))
{
return true;
}
}
validatableTypeInfo = null;
return false;
}
/// <summary>
/// Attempts to get validation information for the specified parameter.
/// </summary>
/// <param name="parameterInfo">The parameter to get validation information for.</param>
/// <param name="validatableInfo">When this method returns, contains the validation information for the specified parameter,
/// if validation information was found; otherwise, <see langword="null" />.</param>
/// <returns><see langword="true" /> if validation information was found for the specified parameter; otherwise, <see langword="false" />.</returns>
[Experimental("ASP0029", UrlFormat = "https://aka.ms/aspnet/analyzer/{0}")]
public bool TryGetValidatableParameterInfo(ParameterInfo parameterInfo, [NotNullWhen(true)] out IValidatableInfo? validatableInfo)
{
foreach (var resolver in Resolvers)
{
if (resolver.TryGetValidatableParameterInfo(parameterInfo, out validatableInfo))
{
return true;
}
}
validatableInfo = null;
return false;
}
}
| ValidationOptions |
csharp | dotnet__aspire | src/Aspire.Hosting.GitHub.Models/GitHubModelsExtensions.cs | {
"start": 492,
"end": 4794
} | public static class ____
{
/// <summary>
/// Adds a GitHub Model resource to the application model.
/// </summary>
/// <param name="builder">The <see cref="IDistributedApplicationBuilder"/>.</param>
/// <param name="name">The name of the resource. This name will be used as the connection string name when referenced in a dependency.</param>
/// <param name="model">The model name to use with GitHub Models.</param>
/// <param name="organization">The organization login associated with the organization to which the request is to be attributed.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
public static IResourceBuilder<GitHubModelResource> AddGitHubModel(this IDistributedApplicationBuilder builder, [ResourceName] string name, string model, IResourceBuilder<ParameterResource>? organization = null)
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentException.ThrowIfNullOrEmpty(name);
ArgumentException.ThrowIfNullOrEmpty(model);
var defaultApiKeyParameter = builder.AddParameter($"{name}-gh-apikey", () =>
{
var configKey = $"Parameters:{name}-gh-apikey";
var value = builder.Configuration.GetValueWithNormalizedKey(configKey);
return value ??
Environment.GetEnvironmentVariable("GITHUB_TOKEN") ??
throw new MissingParameterValueException($"GitHub API key parameter '{name}-gh-apikey' is missing and GITHUB_TOKEN environment variable is not set.");
},
secret: true);
defaultApiKeyParameter.Resource.Description = """
The API key used to authenticate requests to the GitHub Models API.
A [fine-grained personal access token](https://github.com/settings/tokens) with the `models: read` scope is recommended.
See [GitHub documentation for more details](https://docs.github.com/en/rest/models/inference).
""";
defaultApiKeyParameter.Resource.EnableDescriptionMarkdown = true;
var resource = new GitHubModelResource(name, model, organization?.Resource, defaultApiKeyParameter.Resource);
defaultApiKeyParameter.WithParentRelationship(resource);
return builder.AddResource(resource)
.WithInitialState(new()
{
ResourceType = "GitHubModel",
CreationTimeStamp = DateTime.UtcNow,
State = KnownResourceStates.Waiting,
Properties =
[
new(CustomResourceKnownProperties.Source, "GitHub Models")
]
})
.OnInitializeResource(async (r, evt, ct) =>
{
// Connection string resolution is dependent on parameters being resolved
// We use this to wait for the parameters to be resolved before we can compute the connection string.
var cs = await r.ConnectionStringExpression.GetValueAsync(ct).ConfigureAwait(false);
// Publish the update with the connection string value and the state as running.
// This will allow health checks to start running.
await evt.Notifications.PublishUpdateAsync(r, s => s with
{
State = KnownResourceStates.Running,
Properties = [.. s.Properties, new(CustomResourceKnownProperties.ConnectionString, cs) { IsSensitive = true }]
}).ConfigureAwait(false);
// Publish the connection string available event for other resources that may depend on this resource.
await evt.Eventing.PublishAsync(new ConnectionStringAvailableEvent(r, evt.Services), ct)
.ConfigureAwait(false);
});
}
/// <summary>
/// Adds a GitHub Model resource to the application model using a <see cref="GitHubModel"/>.
/// </summary>
/// <param name="builder">The <see cref="IDistributedApplicationBuilder"/>.</param>
/// <param name="name">The name of the resource. This name will be used as the connection string name when referenced in a dependency.</param>
/// <param name="model">The model descriptor, using the <see cref="GitHubModel"/> | GitHubModelsExtensions |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 148579,
"end": 148796
} | public class ____
{
public int Id { get; set; }
public RelatedEntity685 ParentEntity { get; set; }
public IEnumerable<RelatedEntity687> ChildEntities { get; set; }
}
| RelatedEntity686 |
csharp | ServiceStack__ServiceStack.OrmLite | tests/ServiceStack.OrmLite.Tests/OrmLiteTestBase.cs | {
"start": 229,
"end": 3727
} | public class ____
// {
// public static Dialect DefaultDialect = Dialect.Sqlite;
// public const bool EnableDebugLogging = false;
//
// public static string SqliteFileDir = "~/App_Data/".MapAbsolutePath();
// public static string SqliteFileDb = "~/App_Data/db.sqlite".MapAbsolutePath();
// public static string SqlServerDb = "~/App_Data/Database1.mdf".MapAbsolutePath();
// //public static string SqlServerBuildDb = "Data Source=localhost;Initial Catalog=TestDb;Integrated Security=SSPI;Connect Timeout=120;MultipleActiveResultSets=True";
//
// public static string SqliteMemoryDb = Environment.GetEnvironmentVariable("SQLITE_CONNECTION") ?? ":memory:";
// public static string SqlServerBuildDb = Environment.GetEnvironmentVariable("MSSQL_CONNECTION") ?? "Data Source=tcp:localhost,48501\\SQLExpress;Initial Catalog=master;User Id=sa;Password=Test!tesT;Connect Timeout=120;MultipleActiveResultSets=True;";
// public static string OracleDb = Environment.GetEnvironmentVariable("ORACLE_CONNECTION") ?? "Data Source=localhost:48401/XE;User ID=system;Password=test";
// public static string MySqlDb_5_5 = Environment.GetEnvironmentVariable("MYSQL_CONNECTION") ?? "Server=localhost;Port=48201;Database=test;UID=root;Password=test;SslMode=none";
// public static string MySqlDb_10_1 = Environment.GetEnvironmentVariable("MYSQL_CONNECTION") ?? "Server=localhost;Port=48202;Database=test;UID=root;Password=test;SslMode=none";
// public static string MySqlDb_10_2 = Environment.GetEnvironmentVariable("MYSQL_CONNECTION") ?? "Server=localhost;Port=48203;Database=test;UID=root;Password=test;SslMode=none";
// public static string MySqlDb_10_3 = Environment.GetEnvironmentVariable("MYSQL_CONNECTION") ?? "Server=localhost;Port=48204;Database=test;UID=root;Password=test;SslMode=none";
// public static string MySqlDb_10_4 = Environment.GetEnvironmentVariable("MYSQL_CONNECTION") ?? "Server=localhost;Port=48205;Database=test;UID=root;Password=test;SslMode=none";
// public static string PostgresDb_9 = Environment.GetEnvironmentVariable("PGSQL_CONNECTION") ?? "Server=localhost;Port=48301;User Id=test;Password=test;Database=test;Pooling=true;MinPoolSize=0;MaxPoolSize=200";
// public static string PostgresDb_10 = Environment.GetEnvironmentVariable("PGSQL_CONNECTION") ?? "Server=localhost;Port=48302;User Id=test;Password=test;Database=test;Pooling=true;MinPoolSize=0;MaxPoolSize=200";
// public static string PostgresDb_11 = Environment.GetEnvironmentVariable("PGSQL_CONNECTION") ?? "Server=localhost;Port=48303;User Id=test;Password=test;Database=test;Pooling=true;MinPoolSize=0;MaxPoolSize=200";
// public static string FirebirdDb_3 = Environment.GetEnvironmentVariable("FIREBIRD_CONNECTION") ?? @"User=SYSDBA;Password=masterkey;Database=/firebird/data/test.gdb;DataSource=localhost;Port=48101;Dialect=3;charset=ISO8859_1;MinPoolSize=0;MaxPoolSize=100;";
//
// public static IOrmLiteDialectProvider DefaultProvider = SqlServerDialect.Provider;
// public static string DefaultConnection = SqlServerBuildDb;
//
// public static string GetDefaultConnection()
// {
// OrmLiteConfig.DialectProvider = DefaultProvider;
// return DefaultConnection;
// }
//
// public static IDbConnection OpenDbConnection()
// {
// return GetDefaultConnection().OpenDbConnection();
// }
// }
| Config |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 2337472,
"end": 2337739
} | public partial interface ____ : IUpdateStages_UpdateStages_Api_Stages_Conditions, IAfterStageCondition
{
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| IUpdateStages_UpdateStages_Api_Stages_Conditions_AfterStageCondition |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/TypedFilterTests.cs | {
"start": 477,
"end": 525
} | private class ____ : IDependency { }
| Dependency |
csharp | fluentassertions__fluentassertions | Tests/FluentAssertions.Equivalency.Specs/TestTypes.cs | {
"start": 11582,
"end": 11770
} | public class ____
{
public string Text { get; set; }
public CyclicRootDto Root { get; set; }
}
#endregion
#region Interfaces for verifying inheritance of properties
| CyclicLevel1Dto |
csharp | files-community__Files | src/Files.App/UserControls/FileIcon.xaml.cs | {
"start": 301,
"end": 2146
} | partial class ____ : UserControl
{
private SelectedItemsPropertiesViewModel viewModel;
public SelectedItemsPropertiesViewModel ViewModel
{
get => viewModel;
set
{
viewModel = value;
if (value is null)
{
return;
}
if (ViewModel?.CustomIconSource is not null)
{
CustomIconImageSource = new SvgImageSource(ViewModel.CustomIconSource);
}
}
}
private double itemSize;
public double ItemSize
{
get => itemSize;
set
{
itemSize = value;
LargerItemSize = itemSize + 2.0;
}
}
private double LargerItemSize { get; set; }
private static DependencyProperty FileIconImageSourceProperty { get; } = DependencyProperty.Register(nameof(FileIconImageSource), typeof(BitmapImage), typeof(FileIcon), null);
private BitmapImage FileIconImageSource
{
get => GetValue(FileIconImageSourceProperty) as BitmapImage;
set => SetValue(FileIconImageSourceProperty, value);
}
public static DependencyProperty FileIconImageDataProperty { get; } = DependencyProperty.Register(nameof(FileIconImageData), typeof(byte[]), typeof(FileIcon), null);
public byte[] FileIconImageData
{
get => GetValue(FileIconImageDataProperty) as byte[];
set
{
SetValue(FileIconImageDataProperty, value);
if (value is not null)
{
UpdateImageSourceAsync();
}
}
}
private SvgImageSource CustomIconImageSource { get; set; }
public FileIcon()
{
InitializeComponent();
}
public async Task UpdateImageSourceAsync()
{
if (FileIconImageData is not null)
{
FileIconImageSource = new BitmapImage();
using InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
await stream.WriteAsync(FileIconImageData.AsBuffer());
stream.Seek(0);
await FileIconImageSource.SetSourceAsync(stream);
}
}
}
} | FileIcon |
csharp | spectreconsole__spectre.console | src/Spectre.Console/Widgets/Align.cs | {
"start": 1395,
"end": 1927
} | class ____ is left aligned.
/// </summary>
/// <param name="renderable">The <see cref="IRenderable"/> to align.</param>
/// <param name="vertical">The vertical alignment, or <c>null</c> if none.</param>
/// <returns>A new <see cref="Align"/> object.</returns>
public static Align Left(IRenderable renderable, VerticalAlignment? vertical = null)
{
return new Align(renderable, HorizontalAlignment.Left, vertical);
}
/// <summary>
/// Initializes a new instance of the <see cref="Align"/> | that |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Controls/DockPanel.cs | {
"start": 605,
"end": 9172
} | public class ____ : Panel
{
/// <summary>
/// Defines the Dock attached property.
/// </summary>
public static readonly AttachedProperty<Dock> DockProperty =
AvaloniaProperty.RegisterAttached<DockPanel, Control, Dock>("Dock");
/// <summary>
/// Defines the <see cref="LastChildFill"/> property.
/// </summary>
public static readonly StyledProperty<bool> LastChildFillProperty =
AvaloniaProperty.Register<DockPanel, bool>(
nameof(LastChildFill),
defaultValue: true);
/// <summary>
/// Identifies the HorizontalSpacing dependency property.
/// </summary>
/// <returns>The identifier for the <see cref="HorizontalSpacing"/> dependency property.</returns>
public static readonly StyledProperty<double> HorizontalSpacingProperty =
AvaloniaProperty.Register<DockPanel, double>(
nameof(HorizontalSpacing));
/// <summary>
/// Identifies the VerticalSpacing dependency property.
/// </summary>
/// <returns>The identifier for the <see cref="VerticalSpacing"/> dependency property.</returns>
public static readonly StyledProperty<double> VerticalSpacingProperty =
AvaloniaProperty.Register<DockPanel, double>(
nameof(VerticalSpacing));
/// <summary>
/// Initializes static members of the <see cref="DockPanel"/> class.
/// </summary>
static DockPanel()
{
AffectsParentMeasure<DockPanel>(DockProperty);
AffectsMeasure<DockPanel>(LastChildFillProperty, HorizontalSpacingProperty, VerticalSpacingProperty);
}
/// <summary>
/// Gets the value of the Dock attached property on the specified control.
/// </summary>
/// <param name="control">The control.</param>
/// <returns>The Dock attached property.</returns>
public static Dock GetDock(Control control)
{
return control.GetValue(DockProperty);
}
/// <summary>
/// Sets the value of the Dock attached property on the specified control.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="value">The value of the Dock property.</param>
public static void SetDock(Control control, Dock value)
{
control.SetValue(DockProperty, value);
}
/// <summary>
/// Gets or sets a value which indicates whether the last child of the
/// <see cref="DockPanel"/> fills the remaining space in the panel.
/// </summary>
public bool LastChildFill
{
get => GetValue(LastChildFillProperty);
set => SetValue(LastChildFillProperty, value);
}
/// <summary>
/// Gets or sets the horizontal distance between the child objects.
/// </summary>
public double HorizontalSpacing
{
get => GetValue(HorizontalSpacingProperty);
set => SetValue(HorizontalSpacingProperty, value);
}
/// <summary>
/// Gets or sets the vertical distance between the child objects.
/// </summary>
public double VerticalSpacing
{
get => GetValue(VerticalSpacingProperty);
set => SetValue(VerticalSpacingProperty, value);
}
/// <summary>
/// Updates DesiredSize of the DockPanel. Called by parent Control. This is the first pass of layout.
/// </summary>
/// <remarks>
/// Children are measured based on their sizing properties and <see cref="Dock" />.
/// Each child is allowed to consume all the space on the side on which it is docked; Left/Right docked
/// children are granted all vertical space for their entire width, and Top/Bottom docked children are
/// granted all horizontal space for their entire height.
/// </remarks>
/// <param name="availableSize">Constraint size is an "upper limit" that the return value should not exceed.</param>
/// <returns>The Panel's desired size.</returns>
protected override Size MeasureOverride(Size availableSize)
{
var parentWidth = 0d;
var parentHeight = 0d;
var accumulatedWidth = 0d;
var accumulatedHeight = 0d;
var horizontalSpacing = false;
var verticalSpacing = false;
var childrenCount = LastChildFill ? Children.Count - 1 : Children.Count;
for (var index = 0; index < childrenCount; ++index)
{
var child = Children[index];
var childConstraint = new Size(
Math.Max(0, availableSize.Width - accumulatedWidth),
Math.Max(0, availableSize.Height - accumulatedHeight));
child.Measure(childConstraint);
var childDesiredSize = child.DesiredSize;
// Now, we adjust:
// 1. Size consumed by children (accumulatedSize). This will be used when computing subsequent
// children to determine how much space is remaining for them.
// 2. Parent size implied by this child (parentSize) when added to the current children (accumulatedSize).
// This is different from the size above in one respect: A Dock.Left child implies a height, but does
// not actually consume any height for subsequent children.
// If we accumulate size in a given dimension, the next child (or the end conditions after the child loop)
// will deal with computing our minimum size (parentSize) due to that accumulation.
// Therefore, we only need to compute our minimum size (parentSize) in dimensions that this child does
// not accumulate: Width for Top/Bottom, Height for Left/Right.
switch (child.GetValue(DockProperty))
{
case Dock.Left:
case Dock.Right:
parentHeight = Math.Max(parentHeight, accumulatedHeight + childDesiredSize.Height);
if (child.IsVisible)
{
accumulatedWidth += HorizontalSpacing;
horizontalSpacing = true;
}
accumulatedWidth += childDesiredSize.Width;
break;
case Dock.Top:
case Dock.Bottom:
parentWidth = Math.Max(parentWidth, accumulatedWidth + childDesiredSize.Width);
if (child.IsVisible)
{
accumulatedHeight += VerticalSpacing;
verticalSpacing = true;
}
accumulatedHeight += childDesiredSize.Height;
break;
}
}
if (LastChildFill && Children.Count > 0)
{
var child = Children[Children.Count - 1];
var childConstraint = new Size(
Math.Max(0, availableSize.Width - accumulatedWidth),
Math.Max(0, availableSize.Height - accumulatedHeight));
child.Measure(childConstraint);
var childDesiredSize = child.DesiredSize;
parentHeight = Math.Max(parentHeight, accumulatedHeight + childDesiredSize.Height);
parentWidth = Math.Max(parentWidth, accumulatedWidth + childDesiredSize.Width);
accumulatedHeight += childDesiredSize.Height;
accumulatedWidth += childDesiredSize.Width;
}
else
{
if (horizontalSpacing)
accumulatedWidth -= HorizontalSpacing;
if (verticalSpacing)
accumulatedHeight -= VerticalSpacing;
}
// Make sure the final accumulated size is reflected in parentSize.
parentWidth = Math.Max(parentWidth, accumulatedWidth);
parentHeight = Math.Max(parentHeight, accumulatedHeight);
return new Size(parentWidth, parentHeight);
}
/// <summary>
/// DockPanel computes a position and final size for each of its children based upon their
/// <see cref="Dock" /> | DockPanel |
csharp | serilog__serilog | src/Serilog/Policies/ByteMemoryScalarConversionPolicy.cs | {
"start": 848,
"end": 2360
} | sealed class ____ : IScalarConversionPolicy
{
const int MaximumByteArrayLength = 1024;
const int MaxTake = 16;
public bool TryConvertToScalar(object value, [NotNullWhen(true)] out ScalarValue? result)
{
if (value is ReadOnlyMemory<byte> x)
{
result = new(ConvertToHexString(x));
return true;
}
if (value is Memory<byte> y)
{
result = new(ConvertToHexString(y));
return true;
}
result = null;
return false;
}
static string ConvertToHexString(ReadOnlyMemory<byte> bytes)
{
if (bytes.Length > MaximumByteArrayLength)
{
return ConvertToHexString(bytes[..MaxTake], $"... ({bytes.Length} bytes)");
}
return ConvertToHexString(bytes, tail: "");
}
static string ConvertToHexString(ReadOnlyMemory<byte> src, string tail)
{
var stringLength = src.Length * 2 + tail.Length;
return string.Create(stringLength, (src, tail), (dest, state) =>
{
var (src, tail) = state;
var byteSpan = src.Span;
foreach (var b in byteSpan)
{
if (b.TryFormat(dest, out var written, "X2"))
{
dest = dest[written..];
}
}
for (var i = 0; i < tail.Length; ++i)
{
dest[i] = tail[i];
}
});
}
}
#endif
| ByteMemoryScalarConversionPolicy |
csharp | CommunityToolkit__WindowsCommunityToolkit | Microsoft.Toolkit.Uwp.UI.Animations/Xaml/Activities/Activity.cs | {
"start": 472,
"end": 1468
} | public abstract class ____ : DependencyObject, IActivity
{
/// <summary>
/// Gets or sets the <see cref="TimeSpan"/> to wait before running the activity.
/// </summary>
public TimeSpan? Delay
{
get => (TimeSpan?)GetValue(DelayProperty);
set => SetValue(DelayProperty, value);
}
/// <summary>
/// Identifies the <seealso cref="Delay"/> dependency property.
/// </summary>
public static readonly DependencyProperty DelayProperty = DependencyProperty.Register(
nameof(Delay),
typeof(TimeSpan?),
typeof(Activity),
new PropertyMetadata(null));
/// <inheritdoc/>
public virtual Task InvokeAsync(UIElement element, CancellationToken token)
{
if (Delay is not null)
{
return Task.Delay(Delay.Value, token);
}
return Task.CompletedTask;
}
}
} | Activity |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.Tests/Validation/ArgumentsOfCorrectTypeTests.cs | {
"start": 24305,
"end": 24973
} | public static class ____
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "'rule' parameter works as 'this' anchor")]
public static void badValue(
this ArgumentsOfCorrectType rule,
ValidationTestConfig config,
string argName,
string typeName,
string value,
int line,
int column,
string? errors = null)
{
errors ??= $"Expected type '{typeName}', found {value}.";
config.Error(
ArgumentsOfCorrectTypeError.BadValueMessage(argName, errors),
line,
column);
}
}
| ValidationExtensions |
csharp | microsoft__PowerToys | src/modules/launcher/Plugins/Community.PowerToys.Run.Plugin.ValueGenerator/Generators/GUID/GUIDGenerator.cs | {
"start": 406,
"end": 5626
} | internal sealed class ____
{
// As defined in https://datatracker.ietf.org/doc/html/rfc4122#appendix-C
public static readonly Dictionary<string, Guid> PredefinedNamespaces = new Dictionary<string, Guid>()
{
{ "ns:dns", new Guid(0x6ba7b810, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8) },
{ "ns:url", new Guid(0x6ba7b811, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8) },
{ "ns:oid", new Guid(0x6ba7b812, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8) },
{ "ns:x500", new Guid(0x6ba7b814, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8) },
};
public static Guid V1()
{
GUIDDATA guiddata;
int uuidCreateResult = NativeMethods.UuidCreateSequential(out guiddata);
if (uuidCreateResult != Win32Constants.RPC_S_OK && uuidCreateResult != Win32Constants.RPC_S_UUID_LOCAL_ONLY)
{
throw new InvalidOperationException("Failed to create GUID version 1");
}
return new Guid(guiddata.Data1, guiddata.Data2, guiddata.Data3, guiddata.Data4);
}
public static Guid V3(Guid uuidNamespace, string uuidName)
{
return V3AndV5(uuidNamespace, uuidName, 3);
}
public static Guid V4()
{
return Guid.NewGuid();
}
public static Guid V5(Guid uuidNamespace, string uuidName)
{
return V3AndV5(uuidNamespace, uuidName, 5);
}
public static Guid V7()
{
return Guid.CreateVersion7();
}
private static Guid V3AndV5(Guid uuidNamespace, string uuidName, short version)
{
byte[] namespaceBytes = uuidNamespace.ToByteArray();
byte[] networkEndianNamespaceBytes = namespaceBytes;
// Convert time_low, time_mid and time_hi_and_version to network order
int time_low = IPAddress.HostToNetworkOrder(BitConverter.ToInt32(networkEndianNamespaceBytes.AsSpan()[0..4]));
short time_mid = IPAddress.HostToNetworkOrder(BitConverter.ToInt16(networkEndianNamespaceBytes.AsSpan()[4..6]));
short time_hi_and_version = IPAddress.HostToNetworkOrder(BitConverter.ToInt16(networkEndianNamespaceBytes.AsSpan()[6..8]));
Buffer.BlockCopy(BitConverter.GetBytes(time_low), 0, networkEndianNamespaceBytes, 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(time_mid), 0, networkEndianNamespaceBytes, 4, 2);
Buffer.BlockCopy(BitConverter.GetBytes(time_hi_and_version), 0, networkEndianNamespaceBytes, 6, 2);
byte[] nameBytes = Encoding.ASCII.GetBytes(uuidName);
byte[] namespaceAndNameBytes = new byte[networkEndianNamespaceBytes.Length + nameBytes.Length];
Buffer.BlockCopy(networkEndianNamespaceBytes, 0, namespaceAndNameBytes, 0, namespaceBytes.Length);
Buffer.BlockCopy(nameBytes, 0, namespaceAndNameBytes, networkEndianNamespaceBytes.Length, nameBytes.Length);
byte[] hash;
if (version == 3)
{
#pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms
hash = MD5.HashData(namespaceAndNameBytes);
#pragma warning restore CA5351 // Do Not Use Broken Cryptographic Algorithms
}
else if (version == 5)
{
#pragma warning disable CA5350 // Do Not Use Weak Cryptographic Algorithms
hash = SHA1.HashData(namespaceAndNameBytes);
#pragma warning restore CA5350 // Do Not Use Weak Cryptographic Algorithms
}
else
{
throw new InvalidOperationException($"GUID version {version} does not exist");
}
byte[] result = new byte[16];
// Copy first 16-bytes of the hash into our Uuid result
Buffer.BlockCopy(hash, 0, result, 0, 16);
// Convert put time_low, time_mid and time_hi_and_version back to host order
time_low = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(result.AsSpan()[0..4]));
time_mid = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(result.AsSpan()[4..6]));
time_hi_and_version = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(result.AsSpan()[6..8]));
// Set version 'version' in time_hi_and_version field according to https://datatracker.ietf.org/doc/html/rfc4122#section-4.1.3
time_hi_and_version &= 0x0FFF;
#pragma warning disable CS0675 // Bitwise-or operator used on a sign-extended operand
time_hi_and_version = (short)(time_hi_and_version | (version << 12));
#pragma warning restore CS0675 // Bitwise-or operator used on a sign-extended operand
Buffer.BlockCopy(BitConverter.GetBytes(time_low), 0, result, 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(time_mid), 0, result, 4, 2);
Buffer.BlockCopy(BitConverter.GetBytes(time_hi_and_version), 0, result, 6, 2);
// Set upper two bits to "10"
result[8] &= 0x3F;
result[8] |= 0x80;
return new Guid(result);
}
}
}
| GUIDGenerator |
csharp | bitwarden__server | src/Admin/Controllers/HomeController.cs | {
"start": 325,
"end": 3341
} | public class ____ : Controller
{
private readonly GlobalSettings _globalSettings;
private readonly HttpClient _httpClient = new HttpClient();
private readonly ILogger<HomeController> _logger;
public HomeController(GlobalSettings globalSettings, ILogger<HomeController> logger)
{
_globalSettings = globalSettings;
_logger = logger;
}
[Authorize]
public IActionResult Index()
{
return View(new HomeModel
{
GlobalSettings = _globalSettings,
CurrentVersion = Core.Utilities.AssemblyHelpers.GetVersion()
});
}
public IActionResult Error()
{
return View(new ErrorViewModel
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
});
}
public async Task<IActionResult> GetLatestVersion(ProjectType project, CancellationToken cancellationToken)
{
var requestUri = $"https://selfhost.bitwarden.com/version.json";
try
{
var response = await _httpClient.GetAsync(requestUri, cancellationToken);
if (response.IsSuccessStatusCode)
{
var latestVersions = JsonConvert.DeserializeObject<LatestVersions>(await response.Content.ReadAsStringAsync());
return project switch
{
ProjectType.Core => new JsonResult(latestVersions.Versions.CoreVersion),
ProjectType.Web => new JsonResult(latestVersions.Versions.WebVersion),
_ => throw new System.NotImplementedException(),
};
}
}
catch (HttpRequestException e)
{
_logger.LogError(e, "Error encountered while sending GET request to {RequestUri}", requestUri);
return new JsonResult("Unable to fetch latest version") { StatusCode = StatusCodes.Status500InternalServerError };
}
return new JsonResult("-");
}
public async Task<IActionResult> GetInstalledWebVersion(CancellationToken cancellationToken)
{
var requestUri = $"{_globalSettings.BaseServiceUri.InternalVault}/version.json";
try
{
var response = await _httpClient.GetAsync(requestUri, cancellationToken);
if (response.IsSuccessStatusCode)
{
using var jsonDocument = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(cancellationToken), cancellationToken: cancellationToken);
var root = jsonDocument.RootElement;
return new JsonResult(root.GetProperty("version").GetString());
}
}
catch (HttpRequestException e)
{
_logger.LogError(e, "Error encountered while sending GET request to {RequestUri}", requestUri);
return new JsonResult("Unable to fetch installed version") { StatusCode = StatusCodes.Status500InternalServerError };
}
return new JsonResult("-");
}
| HomeController |
csharp | EventStore__EventStore | src/KurrentDB.SecondaryIndexing/Indexes/Default/DefaultSql.cs | {
"start": 2765,
"end": 3348
} | public struct ____ : IQuery<ReadDefaultIndexQueryArgs, IndexQueryRecord> {
public static BindingContext Bind(in ReadDefaultIndexQueryArgs args, PreparedStatement statement)
=> new(statement) { args.StartPosition, args.Count };
public static ReadOnlySpan<byte> CommandText =>
"select log_position, commit_position, event_number from idx_all where log_position<=$1 and is_deleted=false order by rowid desc limit $2"u8;
public static IndexQueryRecord Parse(ref DataChunk.Row row) => new(row.ReadInt64(), row.TryReadInt64(), row.ReadInt64());
}
| ReadDefaultIndexBackQueryIncl |
csharp | smartstore__Smartstore | src/Smartstore.Web/Areas/Admin/Controllers/ExternalAuthenticationController.cs | {
"start": 189,
"end": 2978
} | public partial class ____ : AdminController
{
private readonly IWidgetService _widgetService;
private readonly IProviderManager _providerManager;
private readonly ExternalAuthenticationSettings _externalAuthenticationSettings;
private readonly ModuleManager _moduleManager;
public ExternalAuthenticationController(
IWidgetService widgetService,
IProviderManager providerManager,
ExternalAuthenticationSettings externalAuthenticationSettings,
ModuleManager moduleManager)
{
_widgetService = widgetService;
_providerManager = providerManager;
_externalAuthenticationSettings = externalAuthenticationSettings;
_moduleManager = moduleManager;
}
public IActionResult Index()
{
return RedirectToAction(nameof(Providers));
}
[Permission(Permissions.Configuration.Authentication.Read)]
public IActionResult Providers()
{
var widgetsModel = new List<AuthenticationMethodModel>();
var methods = _providerManager.GetAllProviders<IExternalAuthenticationMethod>();
foreach (var method in methods)
{
var model = _moduleManager.ToProviderModel<IExternalAuthenticationMethod, AuthenticationMethodModel>(method);
model.IsActive = method.IsMethodActive(_externalAuthenticationSettings);
widgetsModel.Add(model);
}
return View(widgetsModel);
}
[HttpPost]
[Permission(Permissions.Configuration.Authentication.Activate)]
public async Task<IActionResult> ActivateProvider(string systemName, bool activate)
{
await _widgetService.ActivateWidgetAsync(systemName, activate);
var provider = _providerManager.GetProvider<IExternalAuthenticationMethod>(systemName);
var dirty = provider.IsMethodActive(_externalAuthenticationSettings) != activate;
if (dirty)
{
if (!activate)
{
_externalAuthenticationSettings.ActiveAuthenticationMethodSystemNames.Remove(x => x.EqualsNoCase(provider.Metadata.SystemName));
}
else
{
_externalAuthenticationSettings.ActiveAuthenticationMethodSystemNames.Add(provider.Metadata.SystemName);
}
await Services.SettingFactory.SaveSettingsAsync(_externalAuthenticationSettings);
await _widgetService.ActivateWidgetAsync(provider.Metadata.SystemName, activate);
}
return RedirectToAction(nameof(Providers));
}
}
}
| ExternalAuthenticationController |
csharp | smartstore__Smartstore | src/Smartstore.Core/Checkout/Cart/Domain/ShoppingCart.cs | {
"start": 334,
"end": 4613
} | public partial class ____ : IEquatable<ShoppingCart>
{
public ShoppingCart(Customer customer, int storeId, IEnumerable<OrganizedShoppingCartItem> items)
{
Customer = Guard.NotNull(customer);
Items = Guard.NotNull(items?.ToArray());
StoreId = storeId;
}
/// <summary>
/// Constructor that applies the properties of another <see cref="ShoppingCart"/> instance.
/// </summary>
/// <param name="other">Other instance whose properties are applied.</param>
/// <param name="items">Items to apply. If <c>null</c> items of <paramref name="other"/> are applied.</param>
/// <example>new ShoppingCart(otherCart, otherCart.Items.Where(x => x.Active))</example>
public ShoppingCart(ShoppingCart other, IEnumerable<OrganizedShoppingCartItem> items = null)
{
Guard.NotNull(other);
Customer = other.Customer;
Items = items?.ToArray() ?? other.Items;
StoreId = other.StoreId;
CartType = other.CartType;
Requirements = other.Requirements;
}
/// <summary>
/// Array of cart items.
/// </summary>
public OrganizedShoppingCartItem[] Items { get; }
/// <summary>
/// A value indicating whether the cart contains cart items.
/// </summary>
public bool HasItems
=> Items.Length > 0;
/// <summary>
/// Shopping cart type.
/// </summary>
public ShoppingCartType CartType { get; init; } = ShoppingCartType.ShoppingCart;
/// <summary>
/// Customer of the cart.
/// </summary>
public Customer Customer { get; }
/// <summary>
/// Store identifier.
/// </summary>
public int StoreId { get; }
/// <summary>
/// Gets a value indicating whether the cart requires shipping.
/// </summary>
public bool IsShippingRequired
=> Requirements.HasFlag(CheckoutRequirements.Shipping) && Items.Any(x => x.Item.IsShippingEnabled);
/// <summary>
/// Checkout requirements.
/// </summary>
public CheckoutRequirements Requirements { get; init; } = CheckoutRequirements.All;
/// <summary>
/// Returns a cart that only contains active items of this cart.
/// </summary>
public ShoppingCart WithActiveItemsOnly()
=> Items.Any(x => !x.Active) ? new(this, Items.Where(x => x.Active)) : this;
#region Compare
public override bool Equals(object obj)
=> Equals(obj as ShoppingCart);
bool IEquatable<ShoppingCart>.Equals(ShoppingCart other)
=> Equals(other);
protected virtual bool Equals(ShoppingCart other)
{
if (other == null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (CartType != other.CartType
|| Customer.Id != other.Customer.Id
|| StoreId != other.StoreId
|| Items.Length != other.Items.Length)
{
return false;
}
return GetHashCode() == other.GetHashCode();
}
public override int GetHashCode()
{
var attributes = Customer.GenericAttributes;
// INFO: the hash must be recreated for each call because modified customer attributes
// like DiscountCouponCode can affect the same cart object.
var combiner = HashCodeCombiner
.Start()
.Add(StoreId)
.Add(CartType)
.Add(Customer.Id)
.Add(attributes?.DiscountCouponCode)
.Add(attributes?.RawGiftCardCouponCodes)
.Add(attributes?.RawCheckoutAttributes)
.Add(attributes?.VatNumber)
.Add(attributes?.UseRewardPointsDuringCheckout)
.Add(attributes?.UseCreditBalanceDuringCheckout)
.AddSequence(Items.Select(x => x.Item));
return combiner.CombinedHash;
}
#endregion
}
}
| ShoppingCart |
csharp | ServiceStack__ServiceStack | ServiceStack.OrmLite/tests/ServiceStack.OrmLite.Tests/UseCase/SimpleUseCase.cs | {
"start": 249,
"end": 1322
} | public class ____
{
public long Id { get; set; }
[DataAnnotations.Index]
public string Name { get; set; }
public DateTime CreatedDate { get; set; }
}
[Test]
public void Simple_CRUD_example()
{
using (var db = OpenDbConnection())
{
db.DropAndCreateTable<User>();
db.Insert(new User { Id = 1, Name = "A", CreatedDate = DateTime.Now });
db.Insert(new User { Id = 2, Name = "B", CreatedDate = DateTime.Now });
db.Insert(new User { Id = 3, Name = "B", CreatedDate = DateTime.Now });
var rowsB = db.Select<User>("Name = @name".PreNormalizeSql(db), new { name = "B" });
Assert.That(rowsB, Has.Count.EqualTo(2));
var rowIds = rowsB.ConvertAll(x => x.Id);
Assert.That(rowIds, Is.EquivalentTo(new List<long> { 2, 3 }));
rowsB.ForEach(x => db.Delete(x));
rowsB = db.Select<User>("Name = @name".PreNormalizeSql(db), new { name = "B" });
Assert.That(rowsB, Has.Count.EqualTo(0));
var rowsLeft = db.Select<User>();
Assert.That(rowsLeft, Has.Count.EqualTo(1));
Assert.That(rowsLeft[0].Name, Is.EqualTo("A"));
}
}
} | User |
csharp | spectreconsole__spectre.console | src/Spectre.Console.Tests/Unit/ColorTests.cs | {
"start": 6456,
"end": 7618
} | public sealed class ____
{
[Theory]
[InlineData(ConsoleColor.Black, 0)]
[InlineData(ConsoleColor.DarkRed, 1)]
[InlineData(ConsoleColor.DarkGreen, 2)]
[InlineData(ConsoleColor.DarkYellow, 3)]
[InlineData(ConsoleColor.DarkBlue, 4)]
[InlineData(ConsoleColor.DarkMagenta, 5)]
[InlineData(ConsoleColor.DarkCyan, 6)]
[InlineData(ConsoleColor.Gray, 7)]
[InlineData(ConsoleColor.DarkGray, 8)]
[InlineData(ConsoleColor.Red, 9)]
[InlineData(ConsoleColor.Green, 10)]
[InlineData(ConsoleColor.Yellow, 11)]
[InlineData(ConsoleColor.Blue, 12)]
[InlineData(ConsoleColor.Magenta, 13)]
[InlineData(ConsoleColor.Cyan, 14)]
[InlineData(ConsoleColor.White, 15)]
public void Should_Return_Expected_Color(ConsoleColor color, int expected)
{
// Given, When
var result = (Color)color;
// Then
result.ShouldBe(Color.FromInt32(expected));
}
}
| ConsoleColorToColor |
csharp | Cysharp__ZLogger | tests/ZLogger.Tests/TestHelpers.cs | {
"start": 706,
"end": 778
} | class ____
{
public int X { get; set; }
}
file | TestState |
csharp | FoundatioFx__Foundatio | src/Foundatio/Extensions/CacheClientExtensions.cs | {
"start": 154,
"end": 7732
} | public static class ____
{
public static async Task<T> GetAsync<T>(this ICacheClient client, string key, T defaultValue)
{
var cacheValue = await client.GetAsync<T>(key).AnyContext();
return cacheValue.HasValue ? cacheValue.Value : defaultValue;
}
public static Task<IDictionary<string, CacheValue<T>>> GetAllAsync<T>(this ICacheClient client, params string[] keys)
{
return client.GetAllAsync<T>(keys.ToArray());
}
public static Task<long> IncrementAsync(this ICacheClient client, string key, long amount, DateTime? expiresAtUtc)
{
return client.IncrementAsync(key, amount, expiresAtUtc?.Subtract(client.GetTimeProvider().GetUtcNow().UtcDateTime));
}
public static Task<double> IncrementAsync(this ICacheClient client, string key, double amount, DateTime? expiresAtUtc)
{
return client.IncrementAsync(key, amount, expiresAtUtc?.Subtract(client.GetTimeProvider().GetUtcNow().UtcDateTime));
}
public static Task<long> IncrementAsync(this ICacheClient client, string key, TimeSpan? expiresIn = null)
{
return client.IncrementAsync(key, 1, expiresIn);
}
public static Task<long> DecrementAsync(this ICacheClient client, string key, TimeSpan? expiresIn = null)
{
return client.IncrementAsync(key, -1, expiresIn);
}
public static Task<long> DecrementAsync(this ICacheClient client, string key, long amount, TimeSpan? expiresIn = null)
{
return client.IncrementAsync(key, -amount, expiresIn);
}
public static Task<long> DecrementAsync(this ICacheClient client, string key, long amount, DateTime? expiresAtUtc)
{
return client.IncrementAsync(key, -amount, expiresAtUtc?.Subtract(client.GetTimeProvider().GetUtcNow().UtcDateTime));
}
public static Task<double> DecrementAsync(this ICacheClient client, string key, double amount, DateTime? expiresAtUtc)
{
return client.IncrementAsync(key, -amount, expiresAtUtc?.Subtract(client.GetTimeProvider().GetUtcNow().UtcDateTime));
}
public static Task<bool> AddAsync<T>(this ICacheClient client, string key, T value, DateTime? expiresAtUtc)
{
return client.AddAsync(key, value, expiresAtUtc?.Subtract(client.GetTimeProvider().GetUtcNow().UtcDateTime));
}
public static Task<bool> SetAsync<T>(this ICacheClient client, string key, T value, DateTime? expiresAtUtc)
{
return client.SetAsync(key, value, expiresAtUtc?.Subtract(client.GetTimeProvider().GetUtcNow().UtcDateTime));
}
public static Task<bool> ReplaceAsync<T>(this ICacheClient client, string key, T value, DateTime? expiresAtUtc)
{
return client.ReplaceAsync(key, value, expiresAtUtc?.Subtract(client.GetTimeProvider().GetUtcNow().UtcDateTime));
}
public static Task<bool> ReplaceIfEqualAsync<T>(this ICacheClient client, string key, T value, T expected, DateTime? expiresAtUtc)
{
return client.ReplaceIfEqualAsync(key, value, expected, expiresAtUtc?.Subtract(client.GetTimeProvider().GetUtcNow().UtcDateTime));
}
public static Task<int> SetAllAsync(this ICacheClient client, IDictionary<string, object> values, DateTime? expiresAtUtc)
{
return client.SetAllAsync(values, expiresAtUtc?.Subtract(client.GetTimeProvider().GetUtcNow().UtcDateTime));
}
public static Task SetExpirationAsync(this ICacheClient client, string key, DateTime expiresAtUtc)
{
return client.SetExpirationAsync(key, expiresAtUtc.Subtract(client.GetTimeProvider().GetUtcNow().UtcDateTime));
}
public static async Task<bool> ListAddAsync<T>(this ICacheClient client, string key, T value, TimeSpan? expiresIn = null)
{
return await client.ListAddAsync(key, [value], expiresIn).AnyContext() > 0;
}
public static async Task<bool> ListRemoveAsync<T>(this ICacheClient client, string key, T value, TimeSpan? expiresIn = null)
{
return await client.ListRemoveAsync(key, [value], expiresIn).AnyContext() > 0;
}
[Obsolete("Use ListAddAsync instead")]
public static async Task<bool> SetAddAsync<T>(this ICacheClient client, string key, T value, TimeSpan? expiresIn = null)
{
return await client.ListAddAsync(key, [value], expiresIn).AnyContext() > 0;
}
[Obsolete("Use ListRemoveAsync instead")]
public static async Task<bool> SetRemoveAsync<T>(this ICacheClient client, string key, T value, TimeSpan? expiresIn = null)
{
return await client.ListRemoveAsync(key, [value], expiresIn).AnyContext() > 0;
}
[Obsolete("Use ListAddAsync instead")]
public static Task<long> SetAddAsync<T>(this ICacheClient client, string key, IEnumerable<T> value, TimeSpan? expiresIn = null)
{
return client.ListAddAsync(key, [value], expiresIn);
}
[Obsolete("Use ListRemoveAsync instead")]
public static Task<long> SetRemoveAsync<T>(this ICacheClient client, string key, IEnumerable<T> value, TimeSpan? expiresIn = null)
{
return client.ListRemoveAsync(key, value, expiresIn);
}
[Obsolete("Use ListAddAsync instead")]
public static Task<CacheValue<ICollection<T>>> GetSetAsync<T>(this ICacheClient client, string key)
{
return client.GetListAsync<T>(key);
}
public static Task<long> SetIfHigherAsync(this ICacheClient client, string key, DateTime value, TimeSpan? expiresIn = null)
{
long unixTime = value.ToUnixTimeMilliseconds();
return client.SetIfHigherAsync(key, unixTime, expiresIn);
}
public static Task<long> SetIfLowerAsync(this ICacheClient client, string key, DateTime value, TimeSpan? expiresIn = null)
{
long unixTime = value.ToUnixTimeMilliseconds();
return client.SetIfLowerAsync(key, unixTime, expiresIn);
}
public static async Task<DateTime> GetUnixTimeMillisecondsAsync(this ICacheClient client, string key, DateTime? defaultValue = null)
{
var unixTime = await client.GetAsync<long>(key).AnyContext();
if (!unixTime.HasValue)
return defaultValue ?? DateTime.MinValue;
return unixTime.Value.FromUnixTimeMilliseconds();
}
public static Task<bool> SetUnixTimeMillisecondsAsync(this ICacheClient client, string key, DateTime value, TimeSpan? expiresIn = null)
{
return client.SetAsync(key, value.ToUnixTimeMilliseconds(), expiresIn);
}
public static Task<bool> SetUnixTimeMillisecondsAsync(this ICacheClient client, string key, DateTime value, DateTime? expiresAtUtc)
{
return client.SetAsync(key, value.ToUnixTimeMilliseconds(), expiresAtUtc?.Subtract(client.GetTimeProvider().GetUtcNow().UtcDateTime));
}
public static async Task<DateTimeOffset> GetUnixTimeSecondsAsync(this ICacheClient client, string key, DateTime? defaultValue = null)
{
var unixTime = await client.GetAsync<long>(key).AnyContext();
if (!unixTime.HasValue)
return defaultValue ?? DateTime.MinValue;
return unixTime.Value.FromUnixTimeSeconds();
}
public static Task<bool> SetUnixTimeSecondsAsync(this ICacheClient client, string key, DateTime value, TimeSpan? expiresIn = null)
{
return client.SetAsync(key, value.ToUnixTimeSeconds(), expiresIn);
}
public static Task<bool> SetUnixTimeSecondsAsync(this ICacheClient client, string key, DateTime value, DateTime? expiresAtUtc)
{
return client.SetAsync(key, value.ToUnixTimeSeconds(), expiresAtUtc?.Subtract(client.GetTimeProvider().GetUtcNow().UtcDateTime));
}
}
| CacheClientExtensions |
csharp | dotnetcore__FreeSql | Providers/FreeSql.Provider.Custom/SqlServer/CustomSqlServerCodeFirst.cs | {
"start": 264,
"end": 33585
} | class ____ : Internal.CommonProvider.CodeFirstProvider
{
public override bool IsNoneCommandParameter { get => true; set => base.IsNoneCommandParameter = true; }
public CustomSqlServerCodeFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) : base(orm, commonUtils, commonExpression) { }
static object _dicCsToDbLock = new object();
static Dictionary<string, CsToDb<DbType>> _dicCsToDb = new Dictionary<string, CsToDb<DbType>>() {
{ typeof(bool).FullName, CsToDb.New(DbType.Boolean, "bit","bit NOT NULL", null, false, false) },{ typeof(bool?).FullName, CsToDb.New(DbType.Boolean, "bit","bit", null, true, null) },
{ typeof(sbyte).FullName, CsToDb.New(DbType.SByte, "smallint", "smallint NOT NULL", false, false, 0) },{ typeof(sbyte?).FullName, CsToDb.New(DbType.SByte, "smallint", "smallint", false, true, null) },
{ typeof(short).FullName, CsToDb.New(DbType.Int16, "smallint","smallint NOT NULL", false, false, 0) },{ typeof(short?).FullName, CsToDb.New(DbType.Int16, "smallint", "smallint", false, true, null) },
{ typeof(int).FullName, CsToDb.New(DbType.Int32, "int", "int NOT NULL", false, false, 0) },{ typeof(int?).FullName, CsToDb.New(DbType.Int32, "int", "int", false, true, null) },
{ typeof(long).FullName, CsToDb.New(DbType.Int64, "bigint","bigint NOT NULL", false, false, 0) },{ typeof(long?).FullName, CsToDb.New(DbType.Int64, "bigint","bigint", false, true, null) },
{ typeof(byte).FullName, CsToDb.New(DbType.Byte, "tinyint","tinyint NOT NULL", true, false, 0) },{ typeof(byte?).FullName, CsToDb.New(DbType.Byte, "tinyint","tinyint", true, true, null) },
{ typeof(ushort).FullName, CsToDb.New(DbType.UInt16, "int","int NOT NULL", true, false, 0) },{ typeof(ushort?).FullName, CsToDb.New(DbType.UInt16, "int", "int", true, true, null) },
{ typeof(uint).FullName, CsToDb.New(DbType.UInt32, "bigint", "bigint NOT NULL", true, false, 0) },{ typeof(uint?).FullName, CsToDb.New(DbType.UInt32, "bigint", "bigint", true, true, null) },
{ typeof(ulong).FullName, CsToDb.New(DbType.UInt64, "decimal", "decimal(20,0) NOT NULL", true, false, 0) },{ typeof(ulong?).FullName, CsToDb.New(DbType.UInt64, "decimal", "decimal(20,0)", true, true, null) },
{ typeof(double).FullName, CsToDb.New(DbType.Double, "float", "float NOT NULL", false, false, 0) },{ typeof(double?).FullName, CsToDb.New(DbType.Double, "float", "float", false, true, null) },
{ typeof(float).FullName, CsToDb.New(DbType.Single, "real","real NOT NULL", false, false, 0) },{ typeof(float?).FullName, CsToDb.New(DbType.Single, "real","real", false, true, null) },
{ typeof(decimal).FullName, CsToDb.New(DbType.Decimal, "decimal", "decimal(10,2) NOT NULL", false, false, 0) },{ typeof(decimal?).FullName, CsToDb.New(DbType.Decimal, "decimal", "decimal(10,2)", false, true, null) },
{ typeof(TimeSpan).FullName, CsToDb.New(DbType.Time, "time","time NOT NULL", false, false, 0) },{ typeof(TimeSpan?).FullName, CsToDb.New(DbType.Time, "time", "time",false, true, null) },
{ typeof(DateTime).FullName, CsToDb.New(DbType.DateTime, "datetime", "datetime NOT NULL", false, false, new DateTime(1970,1,1)) },{ typeof(DateTime?).FullName, CsToDb.New(DbType.DateTime, "datetime", "datetime", false, true, null) },
{ typeof(DateTimeOffset).FullName, CsToDb.New(DbType.DateTimeOffset, "datetimeoffset", "datetimeoffset NOT NULL", false, false, new DateTimeOffset(new DateTime(1970,1,1), TimeSpan.Zero)) },{ typeof(DateTimeOffset?).FullName, CsToDb.New(DbType.DateTimeOffset, "datetimeoffset", "datetimeoffset", false, true, null) },
{ typeof(byte[]).FullName, CsToDb.New(DbType.Binary, "varbinary", "varbinary(255)", false, null, new byte[0]) },
{ typeof(string).FullName, CsToDb.New(DbType.String, "nvarchar", "nvarchar(255)", false, null, "") },
{ typeof(char).FullName, CsToDb.New(DbType.AnsiString, "char", "char(1) NULL", false, null, '\0') },
{ typeof(Guid).FullName, CsToDb.New(DbType.Guid, "uniqueidentifier", "uniqueidentifier NOT NULL", false, false, Guid.Empty) },{ typeof(Guid?).FullName, CsToDb.New(DbType.Guid, "uniqueidentifier", "uniqueidentifier", false, true, null) },
};
public override DbInfoResult GetDbInfo(Type type)
{
if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new DbInfoResult((int)trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue);
if (type.IsArray) return null;
var enumType = type.IsEnum ? type : null;
if (enumType == null && type.IsNullableType())
{
var genericTypes = type.GetGenericArguments();
if (genericTypes.Length == 1 && genericTypes.First().IsEnum) enumType = genericTypes.First();
}
if (enumType != null)
{
var newItem = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any() ?
CsToDb.New(DbType.Int32, "bigint", $"bigint{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, enumType.CreateInstanceGetDefaultValue()) :
CsToDb.New(DbType.Int64, "int", $"int{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, enumType.CreateInstanceGetDefaultValue());
if (_dicCsToDb.ContainsKey(type.FullName) == false)
{
lock (_dicCsToDbLock)
{
if (_dicCsToDb.ContainsKey(type.FullName) == false)
_dicCsToDb.Add(type.FullName, newItem);
}
}
return new DbInfoResult((int)newItem.type, newItem.dbtype, newItem.dbtypeFull, newItem.isnullable, newItem.defaultValue);
}
return null;
}
void AddOrUpdateMS_Description(StringBuilder sb, string schema, string table, string comment)
{
if (string.IsNullOrEmpty(comment))
{
sb.AppendFormat(@"
IF ((SELECT COUNT(1) from fn_listextendedproperty('MS_Description',
'SCHEMA', N'{0}',
'TABLE', N'{1}',
NULL, NULL)) > 0)
EXEC sp_dropextendedproperty @name = N'MS_Description'
, @level0type = 'SCHEMA', @level0name = N'{0}'
, @level1type = 'TABLE', @level1name = N'{1}'
", schema.Replace("'", "''"), table.Replace("'", "''"));
return;
}
sb.AppendFormat(@"
IF ((SELECT COUNT(1) from fn_listextendedproperty('MS_Description',
'SCHEMA', N'{0}',
'TABLE', N'{1}',
NULL, NULL)) > 0)
EXEC sp_updateextendedproperty @name = N'MS_Description', @value = N'{2}'
, @level0type = 'SCHEMA', @level0name = N'{0}'
, @level1type = 'TABLE', @level1name = N'{1}'
ELSE
EXEC sp_addextendedproperty @name = N'MS_Description', @value = N'{2}'
, @level0type = 'SCHEMA', @level0name = N'{0}'
, @level1type = 'TABLE', @level1name = N'{1}'
", schema.Replace("'", "''"), table.Replace("'", "''"), comment?.Replace("'", "''") ?? "");
}
void AddOrUpdateMS_Description(StringBuilder sb, string schema, string table, string column, string comment)
{
if (string.IsNullOrEmpty(comment))
{
sb.AppendFormat(@"
IF ((SELECT COUNT(1) from fn_listextendedproperty('MS_Description',
'SCHEMA', N'{0}',
'TABLE', N'{1}',
'COLUMN', N'{2}')) > 0)
EXEC sp_dropextendedproperty @name = N'MS_Description'
, @level0type = 'SCHEMA', @level0name = N'{0}'
, @level1type = 'TABLE', @level1name = N'{1}'
, @level2type = 'COLUMN', @level2name = N'{2}'
", schema.Replace("'", "''"), table.Replace("'", "''"), column.Replace("'", "''"));
return;
}
sb.AppendFormat(@"
IF ((SELECT COUNT(1) from fn_listextendedproperty('MS_Description',
'SCHEMA', N'{0}',
'TABLE', N'{1}',
'COLUMN', N'{2}')) > 0)
EXEC sp_updateextendedproperty @name = N'MS_Description', @value = N'{3}'
, @level0type = 'SCHEMA', @level0name = N'{0}'
, @level1type = 'TABLE', @level1name = N'{1}'
, @level2type = 'COLUMN', @level2name = N'{2}'
ELSE
EXEC sp_addextendedproperty @name = N'MS_Description', @value = N'{3}'
, @level0type = 'SCHEMA', @level0name = N'{0}'
, @level1type = 'TABLE', @level1name = N'{1}'
, @level2type = 'COLUMN', @level2name = N'{2}'
", schema.Replace("'", "''"), table.Replace("'", "''"), column.Replace("'", "''"), comment?.Replace("'", "''") ?? "");
}
protected override string GetComparisonDDLStatements(params TypeSchemaAndName[] objects)
{
Object<DbConnection> conn = null;
string database = null;
try
{
conn = _orm.Ado.MasterPool.Get(TimeSpan.FromSeconds(5));
database = conn.Value.Database;
var sb = new StringBuilder();
foreach (var obj in objects)
{
if (sb.Length > 0) sb.Append("\r\n");
var tb = obj.tableSchema;
if (tb == null) throw new Exception(CoreErrorStrings.S_Type_IsNot_Migrable(obj.tableSchema.Type.FullName));
if (tb.Columns.Any() == false) throw new Exception(CoreErrorStrings.S_Type_IsNot_Migrable_0Attributes(obj.tableSchema.Type.FullName));
var tbname = _commonUtils.SplitTableName(tb.DbName);
if (tbname?.Length == 1) tbname = new[] { database, "dbo", tbname[0] };
if (tbname?.Length == 2) tbname = new[] { database, tbname[0], tbname[1] };
var tboldname = _commonUtils.SplitTableName(tb.DbOldName); //旧表名
if (tboldname?.Length == 1) tboldname = new[] { database, "dbo", tboldname[0] };
if (tboldname?.Length == 2) tboldname = new[] { database, tboldname[0], tboldname[1] };
if (string.IsNullOrEmpty(obj.tableName) == false)
{
var tbtmpname = _commonUtils.SplitTableName(obj.tableName);
if (tbtmpname?.Length == 1) tbtmpname = new[] { database, "dbo", tbtmpname[0] };
if (tbtmpname?.Length == 2) tbtmpname = new[] { database, tbtmpname[0], tbtmpname[1] };
if (tbname[0] != tbtmpname[0] || tbname[1] != tbtmpname[1] || tbname[2] != tbtmpname[2])
{
tbname = tbtmpname;
tboldname = null;
}
}
//codefirst 不支持表名、模式名、数据库名中带 .
if (string.Compare(tbname[0], database, true) != 0 && LocalExecuteScalar(database, $" select 1 from sys.databases where name='{tbname[0]}'") == null) //创建数据库
LocalExecuteScalar(database, $"if not exists(select 1 from sys.databases where name='{tbname[0]}')\r\n\tcreate database [{tbname[0]}];");
if (string.Compare(tbname[1], "dbo", true) != 0 && LocalExecuteScalar(tbname[0], $" select 1 from sys.schemas where name='{tbname[1]}'") == null) //创建模式
LocalExecuteScalar(tbname[0], $"create schema [{tbname[1]}] authorization [dbo]");
var sbalter = new StringBuilder();
var istmpatler = false; //创建临时表,导入数据,删除旧表,修改
if (LocalExecuteScalar(tbname[0], $" select 1 from dbo.sysobjects where id = object_id(N'[{tbname[1]}].[{tbname[2]}]') and OBJECTPROPERTY(id, N'IsUserTable') = 1") == null)
{ //表不存在
if (tboldname != null)
{
if (string.Compare(tboldname[0], tbname[0], true) != 0 && LocalExecuteScalar(database, $" select 1 from sys.databases where name='{tboldname[0]}'") == null ||
string.Compare(tboldname[1], tbname[1], true) != 0 && LocalExecuteScalar(tboldname[0], $" select 1 from sys.schemas where name='{tboldname[1]}'") == null ||
LocalExecuteScalar(tboldname[0], $" select 1 from dbo.sysobjects where id = object_id(N'[{tboldname[1]}].[{tboldname[2]}]') and OBJECTPROPERTY(id, N'IsUserTable') = 1") == null)
//数据库或模式或表不存在
tboldname = null;
}
if (tboldname == null)
{
//创建表
var createTableName = _commonUtils.QuoteSqlName(tbname[1], tbname[2]);
sb.Append("use [").Append(tbname[0]).Append("];\r\nCREATE TABLE ").Append(createTableName).Append(" ( ");
var pkidx = 0;
foreach (var tbcol in tb.ColumnsByPosition)
{
sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType);
if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)");
if (tbcol.Attribute.IsPrimary == true)
{
if (tb.Primarys.Length > 1)
{
if (pkidx == tb.Primarys.Length - 1)
sb.Append(" primary key (").Append(string.Join(", ", tb.Primarys.Select(a => _commonUtils.QuoteSqlName(a.Attribute.Name)))).Append(")");
}
else
sb.Append(" primary key");
pkidx++;
}
sb.Append(",");
}
sb.Remove(sb.Length - 1, 1).Append("\r\n);\r\n");
//创建表的索引
foreach (var uk in tb.Indexes)
{
sb.Append("CREATE ");
if (uk.IsUnique) sb.Append("UNIQUE ");
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(ReplaceIndexName(uk.Name, tbname[1]))).Append(" ON ").Append(createTableName).Append("(");
foreach (var tbcol in uk.Columns)
{
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
if (tbcol.IsDesc) sb.Append(" DESC");
sb.Append(", ");
}
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
}
//备注
foreach (var tbcol in tb.ColumnsByPosition)
{
if (string.IsNullOrEmpty(tbcol.Comment) == false)
AddOrUpdateMS_Description(sb, tbname[1], tbname[2], tbcol.Attribute.Name, tbcol.Comment);
}
if (string.IsNullOrEmpty(tb.Comment) == false)
AddOrUpdateMS_Description(sb, tbname[1], tbname[2], tb.Comment);
continue;
}
//如果新表,旧表在一个数据库和模式下,直接修改表名
if (string.Compare(tbname[0], tboldname[0], true) == 0 &&
string.Compare(tbname[1], tboldname[1], true) == 0)
sbalter.Append("use [").Append(tbname[0]).Append(_commonUtils.FormatSql("];\r\nEXEC sp_rename {0}, {1};\r\n", _commonUtils.QuoteSqlName(tboldname[0], tboldname[1], tboldname[2]), tbname[2]));
else
{
//如果新表,旧表不在一起,创建新表,导入数据,删除旧表
istmpatler = true;
}
}
else
tboldname = null; //如果新表已经存在,不走改表名逻辑
//对比字段,只可以修改类型、增加字段、有限的修改字段名;保证安全不删除字段
var sql = string.Format(@"
use [{0}];
select
a.name 'column'
,b.name + case
when b.name in ('char', 'varchar', 'nchar', 'nvarchar', 'binary', 'varbinary') then '(' +
case when a.max_length = -1 then 'MAX'
when b.name in ('nchar', 'nvarchar') then cast(a.max_length / 2 as varchar)
else cast(a.max_length as varchar) end + ')'
when b.name in ('numeric', 'decimal') then '(' + cast(a.precision as varchar) + ',' + cast(a.scale as varchar) + ')'
else '' end as 'sqltype'
,case when a.is_nullable = 1 then '1' else '0' end 'isnullable'
,case when a.is_identity = 1 then '1' else '0' end 'isidentity'
,(select value from sys.extended_properties where major_id = a.object_id AND minor_id = a.column_id AND name = 'MS_Description') 'comment'
from sys.columns a
inner join sys.types b on b.user_type_id = a.user_type_id
left join sys.tables d on d.object_id = a.object_id
left join sys.schemas e on e.schema_id = d.schema_id
where a.object_id in (object_id(N'[{1}].[{2}]'));
use [" + database + "];", tboldname ?? tbname);
var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
var tbstruct = ds.ToDictionary(a => string.Concat(a[0]), a => new
{
column = string.Concat(a[0]),
sqlType = string.Concat(a[1]),
is_nullable = string.Concat(a[2]) == "1",
is_identity = string.Concat(a[3]) == "1",
comment = string.Concat(a[4])
}, StringComparer.CurrentCultureIgnoreCase);
if (istmpatler == false)
{
foreach (var tbcol in tb.ColumnsByPosition)
{
if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) ||
string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol))
{
var isCommentChanged = tbstructcol.comment != (tbcol.Comment ?? "");
if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false ||
tbcol.Attribute.IsNullable != tbstructcol.is_nullable ||
tbcol.Attribute.IsIdentity != tbstructcol.is_identity)
{
istmpatler = true;
break;
}
if (string.Compare(tbstructcol.column, tbcol.Attribute.OldName, true) == 0)
//修改列名
sbalter.Append(_commonUtils.FormatSql("EXEC sp_rename {0}, {1}, 'COLUMN';\r\n", $"{tbname[0]}.{tbname[1]}.{tbname[2]}.{tbstructcol.column}", tbcol.Attribute.Name));
if (isCommentChanged)
//修改备备注
AddOrUpdateMS_Description(sbalter, tbname[1], tbname[2], tbcol.Attribute.Name, tbcol.Comment);
continue;
}
//添加列
sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName(tbname[0], tbname[1], tbname[2])).Append(" ADD ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType);
if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sbalter.Append(" identity(1,1)");
if (tbcol.Attribute.IsNullable == false && tbcol.DbDefaultValue != "NULL" && tbcol.Attribute.IsIdentity == false) sbalter.Append(" default(").Append(GetTransferDbDefaultValue(tbcol)).Append(")");
sbalter.Append(";\r\n");
if (string.IsNullOrEmpty(tbcol.Comment) == false) AddOrUpdateMS_Description(sbalter, tbname[1], tbname[2], tbcol.Attribute.Name, tbcol.Comment);
}
}
if (istmpatler == false)
{
var dsuksql = string.Format(@"
use [{0}];
select
c.name
,b.name
,case when a.is_descending_key = 1 then 1 else 0 end
,case when b.is_unique = 1 then 1 else 0 end
from sys.index_columns a
inner join sys.indexes b on b.object_id = a.object_id and b.index_id = a.index_id
left join sys.columns c on c.object_id = a.object_id and c.column_id = a.column_id
where a.object_id in (object_id(N'[{1}].[{2}]')) and b.is_primary_key = 0;
use [" + database + "];", tboldname ?? tbname);
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]), string.Concat(a[2]), string.Concat(a[3]) });
foreach (var uk in tb.Indexes)
{
if (string.IsNullOrEmpty(uk.Name) || uk.Columns.Any() == false) continue;
var ukname = ReplaceIndexName(uk.Name, tbname[1]);
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], ukname, true) == 0).ToArray();
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Columns.Length || dsukfind1.Where(a => (a[3] == "1") == uk.IsUnique && uk.Columns.Where(b => string.Compare(b.Column.Attribute.Name, a[0], true) == 0 && (a[2] == "1") == b.IsDesc).Any()).Count() != uk.Columns.Length)
{
if (dsukfind1.Any()) sbalter.Append("DROP INDEX ").Append(_commonUtils.QuoteSqlName(ukname)).Append(" ON ").Append(_commonUtils.QuoteSqlName(tbname[1], tbname[2])).Append(";\r\n");
sbalter.Append("CREATE ");
if (uk.IsUnique) sbalter.Append("UNIQUE ");
sbalter.Append("INDEX ").Append(_commonUtils.QuoteSqlName(ukname)).Append(" ON ").Append(_commonUtils.QuoteSqlName(tbname[1], tbname[2])).Append("(");
foreach (var tbcol in uk.Columns)
{
sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
if (tbcol.IsDesc) sbalter.Append(" DESC");
sbalter.Append(", ");
}
sbalter.Remove(sbalter.Length - 2, 2).Append(");\r\n");
}
}
}
if (istmpatler == false)
{
var dbcommentsql = $" SELECT value from fn_listextendedproperty('MS_Description', 'schema', N'{tbname[1].Replace("'", "''")}', 'table', N'{tbname[2].Replace("'", "''")}', NULL, NULL)";
if (string.Compare(tbname[0], database, true) != 0) dbcommentsql = $"use [{tbname[0]}];{dbcommentsql};use [{database}];";
var dbcomment = string.Concat(_orm.Ado.ExecuteScalar(CommandType.Text, dbcommentsql));
if (dbcomment != (tb.Comment ?? ""))
AddOrUpdateMS_Description(sbalter, tbname[1], tbname[2], tb.Comment);
if (sbalter.Length > 0)
sb.Append($"use [{tbname[0]}];").Append(sbalter).Append("\r\nuse [").Append(database).Append("];");
continue;
}
//创建临时表,数据导进临时表,然后删除原表,将临时表改名为原表名
bool idents = false;
var newtablename = _commonUtils.QuoteSqlName(tbname[0], tbname[1], tbname[2]);
var tablename = tboldname == null ? newtablename : _commonUtils.QuoteSqlName(tboldname[0], tboldname[1], tboldname[2]);
var tmptablename = _commonUtils.QuoteSqlName(tbname[0], tbname[1], $"FreeSqlTmp_{tbname[2]}");
sb.Append("BEGIN TRANSACTION\r\n")
.Append("SET QUOTED_IDENTIFIER ON\r\n")
.Append("SET ARITHABORT ON\r\n")
.Append("SET NUMERIC_ROUNDABORT OFF\r\n")
.Append("SET CONCAT_NULL_YIELDS_NULL ON\r\n")
.Append("SET ANSI_NULLS ON\r\n")
.Append("SET ANSI_PADDING ON\r\n")
.Append("SET ANSI_WARNINGS ON\r\n")
.Append("COMMIT\r\n");
sb.Append("BEGIN TRANSACTION;\r\n");
//创建临时表
sb.Append("CREATE TABLE ").Append(tmptablename).Append(" ( ");
var pkidx2 = 0;
foreach (var tbcol in tb.ColumnsByPosition)
{
sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType);
if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)");
if (tbcol.Attribute.IsPrimary == true)
{
if (tb.Primarys.Length > 1)
{
if (pkidx2 == tb.Primarys.Length - 1)
sb.Append(" primary key (").Append(string.Join(", ", tb.Primarys.Select(a => _commonUtils.QuoteSqlName(a.Attribute.Name)))).Append(")");
}
else
sb.Append(" primary key");
pkidx2++;
}
sb.Append(",");
idents = idents || tbcol.Attribute.IsIdentity == true;
}
sb.Remove(sb.Length - 1, 1).Append("\r\n);\r\n");
//备注
foreach (var tbcol in tb.ColumnsByPosition)
{
if (string.IsNullOrEmpty(tbcol.Comment) == false)
AddOrUpdateMS_Description(sb, tbname[1], $"FreeSqlTmp_{tbname[2]}", tbcol.Attribute.Name, tbcol.Comment);
}
if (string.IsNullOrEmpty(tb.Comment) == false)
AddOrUpdateMS_Description(sb, tbname[1], $"FreeSqlTmp_{tbname[2]}", tb.Comment);
if ((_commonUtils as CustomSqlServerUtils).ServerVersion > 9) //SqlServer 2008+
sb.Append("ALTER TABLE ").Append(tmptablename).Append(" SET (LOCK_ESCALATION = TABLE);\r\n");
if (idents) sb.Append("SET IDENTITY_INSERT ").Append(tmptablename).Append(" ON;\r\n");
sb.Append("IF EXISTS(SELECT 1 FROM ").Append(tablename).Append(")\r\n");
sb.Append("\tEXEC('INSERT INTO ").Append(tmptablename).Append(" (");
foreach (var tbcol in tb.ColumnsByPosition)
sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
sb.Remove(sb.Length - 2, 2).Append(")\r\n\t\tSELECT ");
foreach (var tbcol in tb.ColumnsByPosition)
{
var insertvalue = "NULL";
if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) ||
string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol))
{
insertvalue = _commonUtils.QuoteSqlName(tbstructcol.column);
if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false)
insertvalue = $"cast({insertvalue} as {tbcol.Attribute.DbType.Split(' ').First()})";
if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable)
insertvalue = $"isnull({insertvalue},{GetTransferDbDefaultValue(tbcol)})";
}
else if (tbcol.Attribute.IsNullable == false)
if (tbcol.DbDefaultValue != "NULL" && tbcol.Attribute.IsIdentity == false)
insertvalue = GetTransferDbDefaultValue(tbcol);
sb.Append(insertvalue.Replace("'", "''")).Append(", ");
}
sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(" WITH (HOLDLOCK TABLOCKX)');\r\n");
if (idents) sb.Append("SET IDENTITY_INSERT ").Append(tmptablename).Append(" OFF;\r\n");
sb.Append("DROP TABLE ").Append(tablename).Append(";\r\n");
sb.Append("EXECUTE sp_rename N'").Append(tmptablename).Append("', N'").Append(tbname[2]).Append("', 'OBJECT';\r\n");
//创建表的索引
foreach (var uk in tb.Indexes)
{
sb.Append("CREATE ");
if (uk.IsUnique) sb.Append("UNIQUE ");
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(ReplaceIndexName(uk.Name, tbname[1]))).Append(" ON ").Append(newtablename).Append("(");
foreach (var tbcol in uk.Columns)
{
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
if (tbcol.IsDesc) sb.Append(" DESC");
sb.Append(", ");
}
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
}
sb.Append("COMMIT;\r\n");
}
return sb.Length == 0 ? null : sb.ToString();
}
finally
{
try
{
if (string.IsNullOrEmpty(database) == false)
conn.Value.ChangeDatabase(database);
_orm.Ado.MasterPool.Return(conn);
}
catch
{
_orm.Ado.MasterPool.Return(conn, true);
}
}
object LocalExecuteScalar(string db, string sql)
{
if (string.Compare(database, db) != 0) conn.Value.ChangeDatabase(db);
try
{
using (var cmd = conn.Value.CreateCommand())
{
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
var before = new Aop.CommandBeforeEventArgs(cmd);
this._orm?.Aop.CommandBeforeHandler?.Invoke(this._orm, before);
Exception afterException = null;
try
{
return cmd.ExecuteScalar();
}
catch (Exception ex)
{
afterException = ex;
throw;
}
finally
{
this._orm?.Aop.CommandAfterHandler?.Invoke(this._orm, new Aop.CommandAfterEventArgs(before, afterException, null));
}
}
}
finally
{
if (string.Compare(database, db) != 0) conn.Value.ChangeDatabase(database);
}
}
}
string GetTransferDbDefaultValue(ColumnInfo col)
{
var ddv = col.DbDefaultValue;
if (string.IsNullOrEmpty(ddv) || ddv == "NULL") return ddv;
if (col.Attribute.MapType.NullableTypeOrThis() == typeof(DateTime) && DateTime.TryParse(ddv, out var trydt))
{
if (col.Attribute.DbType.Contains("SMALLDATETIME") && trydt < new DateTime(1900, 1, 1)) ddv = _commonUtils.FormatSql("{0}", new DateTime(1900, 1, 1));
else if (col.Attribute.DbType.Contains("DATETIME") && trydt < new DateTime(1753, 1, 1)) ddv = _commonUtils.FormatSql("{0}", new DateTime(1753, 1, 1));
else if (col.Attribute.DbType.Contains("DATE") && trydt < new DateTime(0001, 1, 1)) ddv = _commonUtils.FormatSql("{0}", new DateTime(0001, 1, 1));
}
return ddv;
}
}
} | CustomSqlServerCodeFirst |
csharp | dotnet__aspnetcore | src/Servers/Kestrel/Core/src/Internal/Infrastructure/KestrelConnectionOfT.cs | {
"start": 367,
"end": 4037
} | internal sealed class ____<T> : KestrelConnection, IThreadPoolWorkItem where T : BaseConnectionContext
{
private readonly Func<T, Task> _connectionDelegate;
private readonly T _transportConnection;
public KestrelConnection(long id,
ServiceContext serviceContext,
TransportConnectionManager transportConnectionManager,
Func<T, Task> connectionDelegate,
T connectionContext,
KestrelTrace logger,
ConnectionMetricsContext connectionMetricsContext)
: base(id, serviceContext, transportConnectionManager, logger, connectionMetricsContext)
{
_connectionDelegate = connectionDelegate;
_transportConnection = connectionContext;
connectionContext.Features.Set<IConnectionHeartbeatFeature>(this);
connectionContext.Features.Set<IConnectionCompleteFeature>(this);
connectionContext.Features.Set<IConnectionLifetimeNotificationFeature>(this);
connectionContext.Features.Set<IConnectionMetricsContextFeature>(this);
}
private KestrelMetrics Metrics => _serviceContext.Metrics;
public override BaseConnectionContext TransportConnection => _transportConnection;
void IThreadPoolWorkItem.Execute()
{
_ = ExecuteAsync();
}
internal async Task ExecuteAsync()
{
var connectionContext = _transportConnection;
var startTimestamp = 0L;
ConnectionMetricsTagsFeature? metricsTagsFeature = null;
Exception? unhandledException = null;
if (MetricsContext.ConnectionDurationEnabled)
{
metricsTagsFeature = new ConnectionMetricsTagsFeature();
connectionContext.Features.Set<IConnectionMetricsTagsFeature>(metricsTagsFeature);
startTimestamp = Stopwatch.GetTimestamp();
}
try
{
KestrelEventSource.Log.ConnectionQueuedStop(connectionContext);
Metrics.ConnectionQueuedStop(MetricsContext);
Logger.ConnectionStart(connectionContext.ConnectionId);
KestrelEventSource.Log.ConnectionStart(connectionContext);
Metrics.ConnectionStart(MetricsContext);
using (BeginConnectionScope(connectionContext))
{
try
{
await _connectionDelegate(connectionContext);
}
catch (Exception ex)
{
unhandledException = ex;
Logger.LogError(0, ex, "Unhandled exception while processing {ConnectionId}.", connectionContext.ConnectionId);
}
}
}
finally
{
await FireOnCompletedAsync();
var currentTimestamp = 0L;
if (MetricsContext.ConnectionDurationEnabled)
{
currentTimestamp = Stopwatch.GetTimestamp();
}
Logger.ConnectionStop(connectionContext.ConnectionId);
KestrelEventSource.Log.ConnectionStop(connectionContext);
Metrics.ConnectionStop(MetricsContext, unhandledException, metricsTagsFeature?.TagsList, startTimestamp, currentTimestamp);
// Dispose the transport connection, this needs to happen before removing it from the
// connection manager so that we only signal completion of this connection after the transport
// is properly torn down.
await connectionContext.DisposeAsync();
_transportConnectionManager.RemoveConnection(_id);
}
}
| KestrelConnection |
csharp | microsoft__PowerToys | src/settings-ui/Settings.UI/SettingsXAML/Controls/KeyVisual/KeyCharPresenter.xaml.cs | {
"start": 557,
"end": 1027
} | partial class ____ : Control
{
public KeyCharPresenter()
{
DefaultStyleKey = typeof(KeyCharPresenter);
}
public object Content
{
get => (object)GetValue(ContentProperty);
set => SetValue(ContentProperty, value);
}
public static readonly DependencyProperty ContentProperty = DependencyProperty.Register(nameof(Content), typeof(object), typeof(KeyCharPresenter), new PropertyMetadata(default(string)));
}
| KeyCharPresenter |
csharp | dotnet__aspire | src/Aspire.Hosting.Kubernetes/Resources/HelmChartDependency.cs | {
"start": 628,
"end": 2756
} | public sealed class ____
{
/// <summary>
/// Gets or sets the name of the Helm chart dependency.
/// This property specifies the unique name identifying the Helm chart.
/// </summary>
[YamlMember(Alias = "name")]
public string Name { get; set; } = null!;
/// <summary>
/// Gets or sets the version of the Helm chart dependency.
/// This property specifies the version of the Helm chart to be used
/// in the deployment process, ensuring compatibility and correctness.
/// </summary>
[YamlMember(Alias = "version")]
public string Version { get; set; } = null!;
/// <summary>
/// Gets or sets the repository URL or location where the Helm chart dependency is located.
/// </summary>
[YamlMember(Alias = "repository")]
public string Repository { get; set; } = null!;
/// <summary>
/// Gets or sets the condition associated with the Helm chart dependency.
/// The condition is used to control whether this dependency is enabled or disabled
/// based on specific criteria or flags defined in the Helm values.
/// </summary>
[YamlMember(Alias = "condition")]
public string Condition { get; set; } = null!;
/// <summary>
/// Gets or sets a list of tags associated with the Helm chart dependency.
/// Tags are used to manage and conditionally enable dependencies in a Helm chart.
/// </summary>
[YamlMember(Alias = "tags")]
public List<string> Tags { get; set; } = [];
/// <summary>
/// Represents the list of values to be imported into the Helm chart dependency.
/// These values are used to override or supplement configuration settings within the chart.
/// </summary>
[YamlMember(Alias = "import-values")]
public List<string> ImportValues { get; set; } = [];
/// <summary>
/// Gets or sets the alias for the Helm chart dependency.
/// The alias is an optional identifier that can be used to reference or override the default name of the dependency.
/// </summary>
[YamlMember(Alias = "alias")]
public string Alias { get; set; } = null!;
}
| HelmChartDependency |
csharp | dotnet__efcore | test/EFCore.Relational.Specification.Tests/Query/OperatorsProceduralQueryTestBase.cs | {
"start": 34881,
"end": 35133
} | public class ____<TEntity1, TResult>(TEntity1 entity1, TResult result)
where TEntity1 : OperatorEntityBase
{
public TEntity1 Entity1 { get; set; } = entity1;
public TResult Result { get; set; } = result;
}
| OperatorDto1 |
csharp | dotnet__aspnetcore | src/Middleware/Diagnostics/src/StatusCodePage/StatusCodePagesFeature.cs | {
"start": 258,
"end": 638
} | public class ____ : IStatusCodePagesFeature
{
/// <summary>
/// Enables or disables status code pages. The default value is true.
/// Set this to false to prevent the <see cref="StatusCodePagesMiddleware"/>
/// from creating a response body while handling the error status code.
/// </summary>
public bool Enabled { get; set; } = true;
}
| StatusCodePagesFeature |
csharp | jellyfin__jellyfin | tests/Jellyfin.Server.Implementations.Tests/Sorting/AiredEpisodeOrderComparerTests.cs | {
"start": 946,
"end": 1194
} | private sealed class ____ : TheoryData<BaseItem?, BaseItem?>
{
public EpisodeBadData()
{
Add(null, new Episode());
Add(new Episode(), null);
}
}
| EpisodeBadData |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedAssertSessionPinnedOperation.cs | {
"start": 1136,
"end": 2078
} | public class ____
{
private readonly UnifiedEntityMap _entityMap;
public UnifiedAssertSessionPinnedOperationBuilder(UnifiedEntityMap entityMap)
{
_entityMap = entityMap;
}
public UnifiedAssertSessionPinnedOperation Build(BsonDocument arguments)
{
IClientSessionHandle session = null;
foreach (var argument in arguments)
{
switch (argument.Name)
{
case "session":
session = _entityMap.Sessions[argument.Value.AsString];
break;
default:
throw new FormatException($"Invalid AssertSessionPinnedOperation argument name: '{argument.Name}'.");
}
}
return new UnifiedAssertSessionPinnedOperation(session);
}
}
}
| UnifiedAssertSessionPinnedOperationBuilder |
csharp | unoplatform__uno | src/Uno.Foundation/IAsyncOperation.cs | {
"start": 316,
"end": 711
} | public partial interface ____<TResult> : IAsyncInfo
{
/// <summary>
/// Gets or sets the method that handles the operation completed notification.
/// </summary>
AsyncOperationCompletedHandler<TResult> Completed { get; set; }
/// <summary>
/// Returns the results of the operation.
/// </summary>
/// <returns>The results of the operation.</returns>
TResult GetResults();
}
| IAsyncOperation |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.Tests/Attributes/ValidateArgumentsAttributeTests.cs | {
"start": 2418,
"end": 2550
} | public class ____
{
[ValidateArguments(typeof(Dummy))]
public string Hello(string value) => value;
}
| Class2 |
csharp | abpframework__abp | framework/src/Volo.Abp.Emailing/Volo/Abp/Emailing/BackgroundEmailSendingJob.cs | {
"start": 142,
"end": 870
} | public class ____ : AsyncBackgroundJob<BackgroundEmailSendingJobArgs>, ITransientDependency
{
protected IEmailSender EmailSender { get; }
public BackgroundEmailSendingJob(IEmailSender emailSender)
{
EmailSender = emailSender;
}
public async override Task ExecuteAsync(BackgroundEmailSendingJobArgs args)
{
if (args.From.IsNullOrWhiteSpace())
{
await EmailSender.SendAsync(args.To, args.Subject, args.Body, args.IsBodyHtml, args.AdditionalEmailSendingArgs);
}
else
{
await EmailSender.SendAsync(args.From!, args.To, args.Subject, args.Body, args.IsBodyHtml, args.AdditionalEmailSendingArgs);
}
}
}
| BackgroundEmailSendingJob |
csharp | jellyfin__jellyfin | Jellyfin.Api/Constants/InternalClaimTypes.cs | {
"start": 108,
"end": 908
} | public static class ____
{
/// <summary>
/// User Id.
/// </summary>
public const string UserId = "Jellyfin-UserId";
/// <summary>
/// Device Id.
/// </summary>
public const string DeviceId = "Jellyfin-DeviceId";
/// <summary>
/// Device.
/// </summary>
public const string Device = "Jellyfin-Device";
/// <summary>
/// Client.
/// </summary>
public const string Client = "Jellyfin-Client";
/// <summary>
/// Version.
/// </summary>
public const string Version = "Jellyfin-Version";
/// <summary>
/// Token.
/// </summary>
public const string Token = "Jellyfin-Token";
/// <summary>
/// Is Api Key.
/// </summary>
public const string IsApiKey = "Jellyfin-IsApiKey";
}
| InternalClaimTypes |
csharp | jellyfin__jellyfin | MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs | {
"start": 337,
"end": 3034
} | public interface ____
{
/// <summary>
/// Creates a new group.
/// </summary>
/// <param name="session">The session that's creating the group.</param>
/// <param name="request">The request.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The newly created group.</returns>
GroupInfoDto NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken);
/// <summary>
/// Adds the session to a group.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="request">The request.</param>
/// <param name="cancellationToken">The cancellation token.</param>
void JoinGroup(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken);
/// <summary>
/// Removes the session from a group.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="request">The request.</param>
/// <param name="cancellationToken">The cancellation token.</param>
void LeaveGroup(SessionInfo session, LeaveGroupRequest request, CancellationToken cancellationToken);
/// <summary>
/// Gets list of available groups for a session.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="request">The request.</param>
/// <returns>The list of available groups.</returns>
List<GroupInfoDto> ListGroups(SessionInfo session, ListGroupsRequest request);
/// <summary>
/// Gets available groups for a session by id.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="groupId">The group id.</param>
/// <returns>The groups or null.</returns>
GroupInfoDto GetGroup(SessionInfo session, Guid groupId);
/// <summary>
/// Handle a request by a session in a group.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="request">The request.</param>
/// <param name="cancellationToken">The cancellation token.</param>
void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken);
/// <summary>
/// Checks whether a user has an active session using SyncPlay.
/// </summary>
/// <param name="userId">The user identifier to check.</param>
/// <returns><c>true</c> if the user is using SyncPlay; <c>false</c> otherwise.</returns>
bool IsUserActive(Guid userId);
}
}
| ISyncPlayManager |
csharp | dotnet__reactive | Ix.NET/Source/System.Linq.Async/System/Linq/Operators/LastOrDefault.cs | {
"start": 423,
"end": 11380
} | partial class ____
#endif
{
#if INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
// https://learn.microsoft.com/en-us/dotnet/api/system.linq.asyncenumerable.lastordefaultasync?view=net-9.0-pp#system-linq-asyncenumerable-lastordefaultasync-1(system-collections-generic-iasyncenumerable((-0))-system-threading-cancellationtoken)
/// <summary>
/// Returns the last element of an async-enumerable sequence, or a default value if no such element exists.
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <param name="source">Source async-enumerable sequence.</param>
/// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
/// <returns>ValueTask containing the last element in the async-enumerable sequence, or a default value if no such element exists.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
public static ValueTask<TSource?> LastOrDefaultAsync<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default)
{
if (source == null)
throw Error.ArgumentNull(nameof(source));
return Core(source, cancellationToken);
static async ValueTask<TSource?> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
{
var last = await TryGetLast(source, cancellationToken).ConfigureAwait(false);
return last.HasValue ? last.Value : default;
}
}
// https://learn.microsoft.com/en-us/dotnet/api/system.linq.asyncenumerable.lastordefaultasync?view=net-9.0-pp#system-linq-asyncenumerable-lastordefaultasync-1(system-collections-generic-iasyncenumerable((-0))-system-func((-0-system-boolean))-system-threading-cancellationtoken)
/// <summary>
/// Returns the last element of an async-enumerable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <param name="source">Source async-enumerable sequence.</param>
/// <param name="predicate">A predicate function to evaluate for elements in the source sequence.</param>
/// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
/// <returns>ValueTask containing the last element in the async-enumerable sequence that satisfies the condition in the predicate, or a default value if no such element exists.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is null.</exception>
public static ValueTask<TSource?> LastOrDefaultAsync<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken = default)
{
if (source == null)
throw Error.ArgumentNull(nameof(source));
if (predicate == null)
throw Error.ArgumentNull(nameof(predicate));
return Core(source, predicate, cancellationToken);
static async ValueTask<TSource?> Core(IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken)
{
var last = await TryGetLast(source, predicate, cancellationToken).ConfigureAwait(false);
return last.HasValue ? last.Value : default;
}
}
#endif // INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
// https://learn.microsoft.com/en-us/dotnet/api/system.linq.asyncenumerable.lastordefaultasync?view=net-9.0-pp#system-linq-asyncenumerable-lastordefaultasync-1(system-collections-generic-iasyncenumerable((-0))-system-func((-0-system-threading-cancellationtoken-system-threading-tasks-valuetask((system-boolean))))-system-threading-cancellationtoken)
/// <summary>
/// Returns the last element of an async-enumerable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
/// </summary>
/// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
/// <param name="source">Source async-enumerable sequence.</param>
/// <param name="predicate">An asynchronous predicate function to evaluate for elements in the source sequence.</param>
/// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
/// <returns>ValueTask containing the last element in the async-enumerable sequence that satisfies the condition in the predicate, or a default value if no such element exists.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is null.</exception>
[GenerateAsyncOverload]
[Obsolete("Use LastOrDefaultAsync. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the LastOrDefaultAwaitAsync functionality now exists as overloads of LastOrDefaultAsync.")]
private static ValueTask<TSource?> LastOrDefaultAwaitAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
{
if (source == null)
throw Error.ArgumentNull(nameof(source));
if (predicate == null)
throw Error.ArgumentNull(nameof(predicate));
return Core(source, predicate, cancellationToken);
static async ValueTask<TSource?> Core(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken)
{
var last = await TryGetLast(source, predicate, cancellationToken).ConfigureAwait(false);
return last.HasValue ? last.Value : default;
}
}
#if !NO_DEEP_CANCELLATION
[GenerateAsyncOverload]
[Obsolete("Use LastOrDefaultAsync. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the LastOrDefaultAwaitWithCancellationAsync functionality now exists as overloads of LastOrDefaultAsync.")]
private static ValueTask<TSource?> LastOrDefaultAwaitWithCancellationAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
{
if (source == null)
throw Error.ArgumentNull(nameof(source));
if (predicate == null)
throw Error.ArgumentNull(nameof(predicate));
return Core(source, predicate, cancellationToken);
static async ValueTask<TSource?> Core(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken)
{
var last = await TryGetLast(source, predicate, cancellationToken).ConfigureAwait(false);
return last.HasValue ? last.Value : default;
}
}
#endif
private static ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
{
if (source is IList<TSource> list)
{
var count = list.Count;
if (count > 0)
{
return new ValueTask<Maybe<TSource>>(new Maybe<TSource>(list[count - 1]));
}
}
else if (source is IAsyncPartition<TSource> p)
{
return p.TryGetLastAsync(cancellationToken);
}
else
{
return Core(source, cancellationToken);
static async ValueTask<Maybe<TSource>> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
{
var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
var hasLast = false;
await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
{
hasLast = true;
last = item;
}
return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
}
}
return new ValueTask<Maybe<TSource>>(new Maybe<TSource>());
}
private static async ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken)
{
var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
var hasLast = false;
await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
{
if (predicate(item))
{
hasLast = true;
last = item;
}
}
return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
}
private static async ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken)
{
var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
var hasLast = false;
await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
{
if (await predicate(item).ConfigureAwait(false))
{
hasLast = true;
last = item;
}
}
return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
}
#if !NO_DEEP_CANCELLATION
private static async ValueTask<Maybe<TSource>> TryGetLast<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken)
{
var last = default(TSource)!; // NB: Only matters when hasLast is set to true.
var hasLast = false;
await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
{
if (await predicate(item, cancellationToken).ConfigureAwait(false))
{
hasLast = true;
last = item;
}
}
return hasLast ? new Maybe<TSource>(last!) : new Maybe<TSource>();
}
#endif
}
}
| AsyncEnumerable |
csharp | dotnet__efcore | src/EFCore/Metadata/Builders/CollectionNavigationBuilder.cs | {
"start": 940,
"end": 18688
} | public class ____ : IInfrastructure<IConventionForeignKeyBuilder?>
{
/// <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 CollectionNavigationBuilder(
IMutableEntityType declaringEntityType,
IMutableEntityType relatedEntityType,
MemberIdentity navigation,
IMutableForeignKey? foreignKey,
IMutableSkipNavigation? skipNavigation)
{
DeclaringEntityType = declaringEntityType;
RelatedEntityType = relatedEntityType;
CollectionMember = navigation.MemberInfo;
CollectionName = navigation.Name;
Builder = ((ForeignKey?)foreignKey)?.Builder;
SkipNavigation = skipNavigation;
}
/// <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]
protected virtual InternalForeignKeyBuilder? Builder { get; private set; }
private IMutableSkipNavigation? SkipNavigation { get; set; }
/// <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]
protected virtual string? CollectionName { get; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
protected virtual MemberInfo? CollectionMember { get; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
protected virtual IMutableEntityType RelatedEntityType { get; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
protected virtual IMutableEntityType DeclaringEntityType { get; }
/// <summary>
/// <para>
/// Gets the internal builder being used to configure the relationship.
/// </para>
/// <para>
/// This property is intended for use by extension methods that need to make use of services
/// not directly exposed in the public API surface.
/// </para>
/// </summary>
IConventionForeignKeyBuilder? IInfrastructure<IConventionForeignKeyBuilder?>.Instance
=> Builder;
/// <summary>
/// Configures this as a one-to-many relationship.
/// </summary>
/// <remarks>
/// Note that calling this method with no parameters will explicitly configure this side
/// of the relationship to use no navigation property, even if such a property exists on the
/// entity type. If the navigation property is to be used, then it must be specified.
/// </remarks>
/// <param name="navigationName">
/// The name of the reference navigation property on the other end of this relationship.
/// If null or not specified, then there is no navigation property on the other end of the relationship.
/// </param>
/// <returns>An object to further configure the relationship.</returns>
public virtual ReferenceCollectionBuilder WithOne(string? navigationName = null)
=> new(
DeclaringEntityType,
RelatedEntityType,
WithOneBuilder(
Check.NullButNotEmpty(navigationName)).Metadata);
/// <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]
protected virtual InternalForeignKeyBuilder WithOneBuilder(string? navigationName)
=> WithOneBuilder(MemberIdentity.Create(navigationName));
/// <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]
protected virtual InternalForeignKeyBuilder WithOneBuilder(
MemberInfo? navigationMemberInfo)
=> WithOneBuilder(MemberIdentity.Create(navigationMemberInfo));
private InternalForeignKeyBuilder WithOneBuilder(MemberIdentity reference)
{
if (SkipNavigation != null)
{
// Note: we delayed setting the ConfigurationSource of SkipNavigation in HasMany()
// so we can test it here and override if the skip navigation was originally found
// by convention.
if (((IConventionSkipNavigation)SkipNavigation).GetConfigurationSource() == ConfigurationSource.Explicit)
{
throw new InvalidOperationException(
CoreStrings.ConflictingRelationshipNavigation(
SkipNavigation.DeclaringEntityType.DisplayName() + "." + SkipNavigation.Name,
RelatedEntityType.DisplayName()
+ (reference.Name == null
? ""
: "." + reference.Name),
SkipNavigation.DeclaringEntityType.DisplayName() + "." + SkipNavigation.Name,
SkipNavigation.TargetEntityType.DisplayName()
+ (SkipNavigation.Inverse == null
? ""
: "." + SkipNavigation.Inverse.Name)));
}
var navigationName = SkipNavigation.Name;
var declaringEntityType = (EntityType)DeclaringEntityType;
if (SkipNavigation.Inverse != null)
{
((EntityType)SkipNavigation.Inverse.DeclaringEntityType).Builder.HasNoSkipNavigation(
(SkipNavigation)SkipNavigation.Inverse, ConfigurationSource.Explicit);
}
declaringEntityType.Builder.HasNoSkipNavigation((SkipNavigation)SkipNavigation, ConfigurationSource.Explicit);
Builder = declaringEntityType.Builder
.HasRelationship(
(EntityType)RelatedEntityType,
navigationName,
ConfigurationSource.Explicit,
targetIsPrincipal: false);
SkipNavigation = null;
}
var foreignKey = Builder!.Metadata;
var referenceName = reference.Name;
if (referenceName != null
&& foreignKey.DependentToPrincipal != null
&& foreignKey.GetDependentToPrincipalConfigurationSource() == ConfigurationSource.Explicit
&& foreignKey.DependentToPrincipal.Name != referenceName)
{
InternalForeignKeyBuilder.ThrowForConflictingNavigation(foreignKey, referenceName, newToPrincipal: true);
}
return reference.MemberInfo == null || CollectionMember == null
? Builder.HasNavigations(
reference.Name, CollectionName,
(EntityType)DeclaringEntityType, (EntityType)RelatedEntityType,
ConfigurationSource.Explicit)!
: Builder.HasNavigations(
reference.MemberInfo, CollectionMember,
(EntityType)DeclaringEntityType, (EntityType)RelatedEntityType,
ConfigurationSource.Explicit)!;
}
/// <summary>
/// Configures this as a many-to-many relationship.
/// </summary>
/// <param name="navigationName">
/// The name of the collection navigation property on the other end of this relationship.
/// </param>
/// <returns>An object to further configure the relationship.</returns>
public virtual CollectionCollectionBuilder WithMany(string? navigationName = null)
{
var leftName = Builder?.Metadata.PrincipalToDependent?.Name;
var collectionCollectionBuilder =
new CollectionCollectionBuilder(
RelatedEntityType,
DeclaringEntityType,
WithLeftManyNavigation(navigationName),
WithRightManyNavigation(navigationName, leftName!));
return collectionCollectionBuilder;
}
/// <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]
protected virtual IMutableSkipNavigation WithLeftManyNavigation(MemberInfo inverseMemberInfo)
=> WithLeftManyNavigation(inverseMemberInfo.Name);
/// <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]
protected virtual IMutableSkipNavigation WithLeftManyNavigation(string? inverseName)
{
Check.NullButNotEmpty(inverseName);
if (SkipNavigation != null)
{
return SkipNavigation;
}
var foreignKey = Builder!.Metadata;
var navigationMember = foreignKey.PrincipalToDependent.CreateMemberIdentity();
if (foreignKey.GetDependentToPrincipalConfigurationSource() == ConfigurationSource.Explicit)
{
InternalForeignKeyBuilder.ThrowForConflictingNavigation(
foreignKey, DeclaringEntityType, RelatedEntityType, navigationMember.Name, inverseName);
}
using (foreignKey.DeclaringEntityType.Model.DelayConventions())
{
foreignKey.DeclaringEntityType.Builder.HasNoRelationship(foreignKey, ConfigurationSource.Explicit);
Builder = null;
return ((EntityType)DeclaringEntityType).Builder.HasSkipNavigation(
navigationMember,
(EntityType)RelatedEntityType,
foreignKey.PrincipalToDependent?.ClrType,
ConfigurationSource.Explicit,
collection: true,
onDependent: false)!.Metadata;
}
}
/// <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]
protected virtual IMutableSkipNavigation WithRightManyNavigation(string? navigationName, string? inverseName)
=> WithRightManyNavigation(MemberIdentity.Create(navigationName), inverseName);
/// <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]
protected virtual IMutableSkipNavigation WithRightManyNavigation(
MemberInfo navigationMemberInfo,
string? inverseName)
=> WithRightManyNavigation(MemberIdentity.Create(navigationMemberInfo), inverseName);
private IMutableSkipNavigation WithRightManyNavigation(MemberIdentity navigationMember, string? inverseName)
{
Check.DebugAssert(Builder == null, "Expected no associated foreign key at this point");
var navigationName = navigationMember.Name;
using (((EntityType)RelatedEntityType).Model.DelayConventions())
{
if (navigationName != null)
{
var conflictingNavigation = RelatedEntityType.FindNavigation(navigationName) as IConventionNavigation;
var foreignKey = (ForeignKey?)conflictingNavigation?.ForeignKey;
if (conflictingNavigation?.GetConfigurationSource() == ConfigurationSource.Explicit)
{
InternalForeignKeyBuilder.ThrowForConflictingNavigation(
foreignKey!, DeclaringEntityType, RelatedEntityType, inverseName, navigationName);
}
if (conflictingNavigation != null)
{
foreignKey!.DeclaringEntityType.Builder.HasNoRelationship(foreignKey, ConfigurationSource.Explicit);
}
else
{
var skipNavigation = RelatedEntityType.FindSkipNavigation(navigationName);
if (skipNavigation != null)
{
((SkipNavigation)skipNavigation).UpdateConfigurationSource(ConfigurationSource.Explicit);
return skipNavigation;
}
}
}
return ((EntityType)RelatedEntityType).Builder.HasSkipNavigation(
navigationMember,
(EntityType)DeclaringEntityType,
ConfigurationSource.Explicit,
collection: true,
onDependent: false)!.Metadata;
}
}
#region Hidden System.Object members
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>A string that represents the current object.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public override string? ToString()
=> base.ToString();
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// </summary>
/// <param name="obj">The object to compare with the current object.</param>
/// <returns><see langword="true" /> if the specified object is equal to the current object; otherwise, <see langword="false" />.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
// ReSharper disable once BaseObjectEqualsIsObjectEquals
public override bool Equals(object? obj)
=> base.Equals(obj);
/// <summary>
/// Serves as the default hash function.
/// </summary>
/// <returns>A hash code for the current object.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
// ReSharper disable once BaseObjectGetHashCodeCallInGetHashCode
public override int GetHashCode()
=> base.GetHashCode();
#endregion
}
| CollectionNavigationBuilder |
csharp | smartstore__Smartstore | src/Smartstore.Core/Data/SmartDbContext.cs | {
"start": 328,
"end": 465
} | public abstract class ____<TEntity> : AsyncDbSaveHook<SmartDbContext, TEntity>
where TEntity : class
{
}
| AsyncDbSaveHook |
csharp | nunit__nunit | src/NUnitFramework/framework/Internal/MessagePumpStrategy.cs | {
"start": 7936,
"end": 9835
} | private sealed class ____ : MessagePumpStrategy
{
public static readonly SingleThreadedTestMessagePumpStrategy Instance = new();
private SingleThreadedTestMessagePumpStrategy()
{
}
public override void WaitForCompletion(AwaitAdapter awaiter)
{
var context = SynchronizationContext.Current as SingleThreadedTestSynchronizationContext
?? throw new InvalidOperationException("This strategy must only be used from a SingleThreadedTestSynchronizationContext.");
if (awaiter.IsCompleted)
return;
// Wait for a post rather than scheduling the continuation now. If there has been a race condition
// and it completed after the IsCompleted check, it will wait until the message loop runs *before*
// shutting it down. Otherwise context.ShutDown will throw.
context.Post(
_ => ContinueOnSameSynchronizationContext(awaiter, context.ShutDown),
state: awaiter);
context.Run();
}
}
private static void ContinueOnSameSynchronizationContext(AwaitAdapter awaiter, Action continuation)
{
if (awaiter is null)
throw new ArgumentNullException(nameof(awaiter));
if (continuation is null)
throw new ArgumentNullException(nameof(continuation));
var context = SynchronizationContext.Current;
awaiter.OnCompleted(() =>
{
if (context is null || SynchronizationContext.Current == context)
continuation.Invoke();
else
context.Post(_ => continuation.Invoke(), state: continuation);
});
}
}
}
| SingleThreadedTestMessagePumpStrategy |
csharp | mongodb__mongo-csharp-driver | src/MongoDB.Driver/Core/Bindings/CoreTransactionState.cs | {
"start": 728,
"end": 1260
} | public enum ____
{
/// <summary>
/// StartTransaction has been called but no operations have been performed yet.
/// </summary>
Starting = 1,
/// <summary>
/// The transaction is in progress.
/// </summary>
InProgress,
/// <summary>
/// CommitTransaction has been called.
/// </summary>
Committed,
/// <summary>
/// AbortTransaction has been called.
/// </summary>
Aborted
}
}
| CoreTransactionState |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.DataLoader/IDataLoader.cs | {
"start": 128,
"end": 610
} | public interface ____
{
/// <summary>
/// Dispatch any pending operations
/// </summary>
/// <param name="cancellationToken">Optional <seealso cref="CancellationToken"/> to pass to the fetch delegate</param>
Task DispatchAsync(CancellationToken cancellationToken = default);
}
/// <summary>
/// Provides a method of queuing a data loading operation to be dispatched later.
/// </summary>
/// <typeparam name="T">The type of data to be loaded</typeparam>
| IDataLoader |
csharp | ardalis__CleanArchitecture | src/Clean.Architecture.Core/ContributorAggregate/Handlers/ContributorDeletedHandler.cs | {
"start": 169,
"end": 827
} | public class ____(ILogger<ContributorDeletedHandler> logger,
IEmailSender emailSender) : INotificationHandler<ContributorDeletedEvent>
{
public async ValueTask Handle(ContributorDeletedEvent domainEvent, CancellationToken cancellationToken)
{
logger.LogInformation("Handling Contributed Deleted event for {contributorId}", domainEvent.ContributorId);
await emailSender.SendEmailAsync("to@test.com",
"from@test.com",
"Contributor Deleted",
$"Contributor with id {domainEvent.ContributorId} was deleted.");
}
}
| ContributorDeletedHandler |
csharp | App-vNext__Polly | test/Polly.Specs/Retry/RetryAsyncSpecs.cs | {
"start": 127,
"end": 29649
} | public class ____
{
[Fact]
public void Should_throw_when_action_is_null()
{
var flags = BindingFlags.NonPublic | BindingFlags.Instance;
Func<Context, CancellationToken, Task<EmptyStruct>> action = null!;
var policyBuilder = new PolicyBuilder(exception => exception);
Func<Exception, TimeSpan, int, Context, Task> onRetryAsync = (_, _, _, _) => Task.CompletedTask;
int permittedRetryCount = int.MaxValue;
IEnumerable<TimeSpan>? sleepDurationsEnumerable = null;
Func<int, Exception, Context, TimeSpan> sleepDurationProvider = null!;
var instance = Activator.CreateInstance(
typeof(AsyncRetryPolicy),
flags,
null,
[policyBuilder, onRetryAsync, permittedRetryCount, sleepDurationsEnumerable, sleepDurationProvider],
null)!;
var instanceType = instance.GetType();
var methods = instanceType.GetMethods(flags);
var methodInfo = methods.First(method => method is { Name: "ImplementationAsync", ReturnType.Name: "Task`1" });
var generic = methodInfo.MakeGenericMethod(typeof(EmptyStruct));
var func = () => generic.Invoke(instance, [action, new Context(), TestCancellation.Token, false]);
var exceptionAssertions = Should.Throw<TargetInvocationException>(func);
exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation.");
exceptionAssertions.InnerException.ShouldBeOfType<ArgumentNullException>()
.ParamName.ShouldBe("action");
}
[Fact]
public void Should_throw_when_retry_count_is_less_than_zero_without_context()
{
Action<Exception, int> onRetry = (_, _) => { };
Action policy = () => Policy
.Handle<DivideByZeroException>()
.RetryAsync(-1, onRetry);
Should.Throw<ArgumentOutOfRangeException>(policy)
.ParamName.ShouldBe("retryCount");
}
[Fact]
public async Task Should_not_throw_when_specified_exception_thrown_same_number_of_times_as_retry_count()
{
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3);
await Should.NotThrowAsync(() => policy.RaiseExceptionAsync<DivideByZeroException>(3));
}
[Fact]
public async Task Should_not_throw_when_one_of_the_specified_exceptions_thrown_same_number_of_times_as_retry_count()
{
var policy = Policy
.Handle<DivideByZeroException>()
.Or<ArgumentException>()
.RetryAsync(3);
await Should.NotThrowAsync(() => policy.RaiseExceptionAsync<ArgumentException>(3));
}
[Fact]
public async Task Should_not_throw_when_specified_exception_thrown_less_number_of_times_than_retry_count()
{
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3);
await Should.NotThrowAsync(() => policy.RaiseExceptionAsync<DivideByZeroException>());
}
[Fact]
public async Task Should_not_throw_when_one_of_the_specified_exceptions_thrown_less_number_of_times_than_retry_count()
{
var policy = Policy
.Handle<DivideByZeroException>()
.Or<ArgumentException>()
.RetryAsync(3);
await Should.NotThrowAsync(() => policy.RaiseExceptionAsync<ArgumentException>());
}
[Fact]
public async Task Should_throw_when_specified_exception_thrown_more_times_then_retry_count()
{
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3);
await Should.ThrowAsync<DivideByZeroException>(() => policy.RaiseExceptionAsync<DivideByZeroException>(3 + 1));
}
[Fact]
public async Task Should_throw_when_one_of_the_specified_exceptions_are_thrown_more_times_then_retry_count()
{
var policy = Policy
.Handle<DivideByZeroException>()
.Or<ArgumentException>()
.RetryAsync(3);
await Should.ThrowAsync<ArgumentException>(() => policy.RaiseExceptionAsync<ArgumentException>(3 + 1));
}
[Fact]
public async Task Should_throw_when_exception_thrown_is_not_the_specified_exception_type()
{
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync();
await Should.ThrowAsync<NullReferenceException>(() => policy.RaiseExceptionAsync<NullReferenceException>());
}
[Fact]
public async Task Should_throw_when_exception_thrown_is_not_one_of_the_specified_exception_types()
{
var policy = Policy
.Handle<DivideByZeroException>()
.Or<ArgumentException>()
.RetryAsync();
await Should.ThrowAsync<NullReferenceException>(() => policy.RaiseExceptionAsync<NullReferenceException>());
}
[Fact]
public async Task Should_throw_when_specified_exception_predicate_is_not_satisfied()
{
var policy = Policy
.Handle<DivideByZeroException>(_ => false)
.RetryAsync();
await Should.ThrowAsync<DivideByZeroException>(() => policy.RaiseExceptionAsync<DivideByZeroException>());
}
[Fact]
public async Task Should_throw_when_none_of_the_specified_exception_predicates_are_satisfied()
{
var policy = Policy
.Handle<DivideByZeroException>(_ => false)
.Or<ArgumentException>(_ => false)
.RetryAsync();
await Should.ThrowAsync<ArgumentException>(() => policy.RaiseExceptionAsync<ArgumentException>());
}
[Fact]
public async Task Should_not_throw_when_specified_exception_predicate_is_satisfied()
{
var policy = Policy
.Handle<DivideByZeroException>(_ => true)
.RetryAsync();
await Should.NotThrowAsync(() => policy.RaiseExceptionAsync<DivideByZeroException>());
}
[Fact]
public async Task Should_not_throw_when_one_of_the_specified_exception_predicates_are_satisfied()
{
var policy = Policy
.Handle<DivideByZeroException>(_ => true)
.Or<ArgumentException>(_ => true)
.RetryAsync();
await Should.NotThrowAsync(() => policy.RaiseExceptionAsync<ArgumentException>());
}
[Fact]
public void Should_throw_when_onRetry_is_null()
{
Action action = () => Policy
.Handle<DivideByZeroException>()
.RetryAsync(3, (Action<Exception, int>)null!);
Should.Throw<ArgumentNullException>(action).ParamName.ShouldBe("onRetry");
}
[Fact]
public void Should_throw_when_onRetryAsync_is_null()
{
Action action = () => Policy
.Handle<DivideByZeroException>()
.RetryAsync(3, (Func<Exception, int, Task>)null!);
Should.Throw<ArgumentNullException>(action).ParamName.ShouldBe("onRetryAsync");
action = () => Policy
.Handle<DivideByZeroException>()
.RetryAsync(3, (Func<Exception, int, Context, Task>)null!);
Should.Throw<ArgumentNullException>(action).ParamName.ShouldBe("onRetryAsync");
}
[Fact]
public async Task Should_call_onretry_on_each_retry_with_the_current_retry_count()
{
var expectedRetryCounts = new[] { 1, 2, 3 };
var retryCounts = new List<int>();
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3, (_, retryCount) => retryCounts.Add(retryCount));
await policy.RaiseExceptionAsync<DivideByZeroException>(3);
retryCounts.ShouldBe(expectedRetryCounts);
}
[Fact]
public async Task Should_call_onretry_on_each_retry_with_the_current_exception()
{
var expectedExceptions = new[] { "Exception #1", "Exception #2", "Exception #3" };
var retryExceptions = new List<Exception>();
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3, (exception, _) => retryExceptions.Add(exception));
await policy.RaiseExceptionAsync<DivideByZeroException>(3, (e, i) => e.HelpLink = "Exception #" + i);
retryExceptions
.Select(x => x.HelpLink)
.ShouldBe(expectedExceptions);
}
[Fact]
public async Task Should_call_onretry_with_a_handled_innerexception()
{
Exception? passedToOnRetry = null;
var policy = Policy
.HandleInner<DivideByZeroException>()
.RetryAsync(3, (exception, _) => passedToOnRetry = exception);
Exception toRaiseAsInner = new DivideByZeroException();
Exception withInner = new AggregateException(toRaiseAsInner);
await policy.RaiseExceptionAsync(withInner);
passedToOnRetry.ShouldBeSameAs(toRaiseAsInner);
}
[Fact]
public async Task Should_not_call_onretry_when_no_retries_are_performed()
{
var retryCounts = new List<int>();
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync((_, retryCount) => retryCounts.Add(retryCount));
await Should.ThrowAsync<ArgumentException>(() => policy.RaiseExceptionAsync<ArgumentException>());
retryCounts.ShouldBeEmpty();
}
[Fact]
public async Task Should_create_new_state_for_each_call_to_policy()
{
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync();
await Should.NotThrowAsync(() => policy.RaiseExceptionAsync<DivideByZeroException>());
await Should.NotThrowAsync(() => policy.RaiseExceptionAsync<DivideByZeroException>());
}
[Fact]
public void Should_call_onretry_with_the_passed_context()
{
IDictionary<string, object>? contextData = null;
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync((_, _, context) => contextData = context);
policy.RaiseExceptionAsync<DivideByZeroException>(
CreateDictionary("key1", "value1", "key2", "value2"),
cancellationToken: TestCancellation.Token);
contextData.ShouldNotBeNull();
contextData.ShouldContainKeyAndValue("key1", "value1");
contextData.ShouldContainKeyAndValue("key2", "value2");
}
[Fact]
public async Task Should_call_onretry_with_the_passed_context_when_execute_and_capture()
{
IDictionary<string, object>? contextData = null;
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync((_, _, context) => contextData = context);
await Should.NotThrowAsync(
() =>
policy.ExecuteAndCaptureAsync(
_ => { throw new DivideByZeroException(); },
CreateDictionary("key1", "value1", "key2", "value2")));
contextData.ShouldNotBeNull();
contextData.ShouldContainKeyAndValue("key1", "value1");
contextData.ShouldContainKeyAndValue("key2", "value2");
}
[Fact]
public async Task Context_should_be_empty_if_execute_not_called_with_any_data()
{
Context? capturedContext = null;
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync((_, _, context) => capturedContext = context);
await Should.NotThrowAsync(() => policy.RaiseExceptionAsync<DivideByZeroException>());
capturedContext.ShouldNotBeNull();
capturedContext.ShouldBeEmpty();
}
[Fact]
public void Should_create_new_context_for_each_call_to_execute()
{
var cancellationToken = TestCancellation.Token;
string? contextValue = null;
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync((_, _, context) => contextValue = context["key"].ToString());
policy.RaiseExceptionAsync<DivideByZeroException>(
CreateDictionary("key", "original_value"),
cancellationToken: cancellationToken);
contextValue.ShouldBe("original_value");
policy.RaiseExceptionAsync<DivideByZeroException>(
CreateDictionary("key", "new_value"),
cancellationToken: cancellationToken);
contextValue.ShouldBe("new_value");
}
[Fact]
public async Task Should_create_new_context_for_each_call_to_execute_and_capture()
{
string? contextValue = null;
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync((_, _, context) => contextValue = context["key"].ToString());
await Should.NotThrowAsync(
() =>
policy.ExecuteAndCaptureAsync(
_ => throw new DivideByZeroException(),
CreateDictionary("key", "original_value")));
contextValue.ShouldBe("original_value");
await Should.NotThrowAsync(
() =>
policy.ExecuteAndCaptureAsync(
_ => throw new DivideByZeroException(),
CreateDictionary("key", "new_value")));
contextValue.ShouldBe("new_value");
}
[Fact]
public async Task Should_not_call_onretry_when_retry_count_is_zero()
{
bool retryInvoked = false;
Action<Exception, int> onRetry = (_, _) => { retryInvoked = true; };
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(0, onRetry);
await Should.ThrowAsync<DivideByZeroException>(() => policy.RaiseExceptionAsync<DivideByZeroException>());
retryInvoked.ShouldBeFalse();
}
#region Async and cancellation tests
[Fact]
public async Task Should_wait_asynchronously_for_async_onretry_delegate()
{
// This test relates to https://github.com/App-vNext/Polly/issues/107.
// An async (...) => { ... } anonymous delegate with no return type may compile to either an async void or an async Task method; which assign to an Action<...> or Func<..., Task> respectively.
// However, if it compiles to async void (assigning to Action<...>), then the delegate, when run, will return at the first await, and execution continues without waiting for the Action to complete, as described by Stephen Toub: https://devblogs.microsoft.com/pfxteam/potential-pitfalls-to-avoid-when-passing-around-async-lambdas/
// If Polly were to declare only an Action<...> delegate for onRetry - but users declared async () => { } onRetry delegates - the compiler would happily assign them to the Action<...>, but the next 'try' of the retry policy would/could occur before onRetry execution had completed.
// This test ensures the relevant retry policy does have a Func<..., Task> form for onRetry, and that it is awaited before the next try commences.
TimeSpan shimTimeSpan = TimeSpan.FromSeconds(0.2);
int executeDelegateInvocations = 0;
int executeDelegateInvocationsWhenOnRetryExits = 0;
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(async (_, _) =>
{
await Task.Delay(shimTimeSpan);
executeDelegateInvocationsWhenOnRetryExits = executeDelegateInvocations;
});
await Should.ThrowAsync<DivideByZeroException>(() => policy.ExecuteAsync(async () =>
{
executeDelegateInvocations++;
await TaskHelper.EmptyTask;
throw new DivideByZeroException();
}));
while (executeDelegateInvocationsWhenOnRetryExits == 0)
{
// Wait for the onRetry delegate to complete.
}
executeDelegateInvocationsWhenOnRetryExits.ShouldBe(1); // If the async onRetry delegate is genuinely awaited, only one execution of the .Execute delegate should have occurred by the time onRetry completes. If the async onRetry delegate were instead assigned to an Action<...>, then onRetry will return, and the second action execution will commence, before await Task.Delay() completes, leaving executeDelegateInvocationsWhenOnRetryExits == 2.
executeDelegateInvocations.ShouldBe(2);
}
[Fact]
public async Task Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled()
{
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3);
int attemptsInvoked = 0;
Action onExecute = () => attemptsInvoked++;
Scenario scenario = new Scenario
{
NumberOfTimesToRaiseException = 0,
AttemptDuringWhichToCancel = null,
};
using (var cancellationTokenSource = new CancellationTokenSource())
{
CancellationToken cancellationToken = cancellationTokenSource.Token;
await Should.NotThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync<DivideByZeroException>(scenario, cancellationTokenSource, onExecute));
}
attemptsInvoked.ShouldBe(1);
}
[Fact]
public async Task Should_execute_all_tries_when_faulting_and_cancellationToken_not_cancelled()
{
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3);
int attemptsInvoked = 0;
Action onExecute = () => attemptsInvoked++;
Scenario scenario = new Scenario
{
NumberOfTimesToRaiseException = 1 + 3,
AttemptDuringWhichToCancel = null,
};
using (var cancellationTokenSource = new CancellationTokenSource())
{
CancellationToken cancellationToken = cancellationTokenSource.Token;
await Should.ThrowAsync<DivideByZeroException>(() => policy.RaiseExceptionAndOrCancellationAsync<DivideByZeroException>(scenario, cancellationTokenSource, onExecute));
}
attemptsInvoked.ShouldBe(1 + 3);
}
[Fact]
public async Task Should_not_execute_action_when_cancellationToken_cancelled_before_execute()
{
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3);
int attemptsInvoked = 0;
Action onExecute = () => attemptsInvoked++;
Scenario scenario = new Scenario
{
NumberOfTimesToRaiseException = 1 + 3,
AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution.
};
using (var cancellationTokenSource = new CancellationTokenSource())
{
CancellationToken cancellationToken = cancellationTokenSource.Token;
cancellationTokenSource.Cancel();
var ex = await Should.ThrowAsync<OperationCanceledException>(() => policy.RaiseExceptionAndOrCancellationAsync<DivideByZeroException>(scenario, cancellationTokenSource, onExecute));
ex.CancellationToken.ShouldBe(cancellationToken);
}
attemptsInvoked.ShouldBe(0);
}
[Fact]
public async Task Should_report_cancellation_during_otherwise_non_faulting_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken()
{
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3);
int attemptsInvoked = 0;
Action onExecute = () => attemptsInvoked++;
Scenario scenario = new Scenario
{
NumberOfTimesToRaiseException = 0,
AttemptDuringWhichToCancel = 1,
ActionObservesCancellation = true
};
using (var cancellationTokenSource = new CancellationTokenSource())
{
CancellationToken cancellationToken = cancellationTokenSource.Token;
var ex = await Should.ThrowAsync<OperationCanceledException>(() => policy.RaiseExceptionAndOrCancellationAsync<DivideByZeroException>(scenario, cancellationTokenSource, onExecute));
ex.CancellationToken.ShouldBe(cancellationToken);
}
attemptsInvoked.ShouldBe(1);
}
[Fact]
public async Task Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken()
{
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3);
int attemptsInvoked = 0;
Action onExecute = () => attemptsInvoked++;
Scenario scenario = new Scenario
{
NumberOfTimesToRaiseException = 1 + 3,
AttemptDuringWhichToCancel = 1,
ActionObservesCancellation = true
};
using (var cancellationTokenSource = new CancellationTokenSource())
{
CancellationToken cancellationToken = cancellationTokenSource.Token;
var ex = await Should.ThrowAsync<OperationCanceledException>(() => policy.RaiseExceptionAndOrCancellationAsync<DivideByZeroException>(scenario, cancellationTokenSource, onExecute));
ex.CancellationToken.ShouldBe(cancellationToken);
}
attemptsInvoked.ShouldBe(1);
}
[Fact]
public async Task Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken()
{
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3);
int attemptsInvoked = 0;
Action onExecute = () => attemptsInvoked++;
Scenario scenario = new Scenario
{
NumberOfTimesToRaiseException = 1 + 3,
AttemptDuringWhichToCancel = 1,
ActionObservesCancellation = false
};
using (var cancellationTokenSource = new CancellationTokenSource())
{
CancellationToken cancellationToken = cancellationTokenSource.Token;
var ex = await Should.ThrowAsync<OperationCanceledException>(() => policy.RaiseExceptionAndOrCancellationAsync<DivideByZeroException>(scenario, cancellationTokenSource, onExecute));
ex.CancellationToken.ShouldBe(cancellationToken);
}
attemptsInvoked.ShouldBe(1);
}
[Fact]
public async Task Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken()
{
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3);
int attemptsInvoked = 0;
Action onExecute = () => attemptsInvoked++;
Scenario scenario = new Scenario
{
NumberOfTimesToRaiseException = 1 + 3,
AttemptDuringWhichToCancel = 2,
ActionObservesCancellation = true
};
using (var cancellationTokenSource = new CancellationTokenSource())
{
CancellationToken cancellationToken = cancellationTokenSource.Token;
var ex = await Should.ThrowAsync<OperationCanceledException>(() => policy.RaiseExceptionAndOrCancellationAsync<DivideByZeroException>(scenario, cancellationTokenSource, onExecute));
ex.CancellationToken.ShouldBe(cancellationToken);
}
attemptsInvoked.ShouldBe(2);
}
[Fact]
public async Task Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken()
{
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3);
int attemptsInvoked = 0;
Action onExecute = () => attemptsInvoked++;
Scenario scenario = new Scenario
{
NumberOfTimesToRaiseException = 1 + 3,
AttemptDuringWhichToCancel = 2,
ActionObservesCancellation = false
};
using (var cancellationTokenSource = new CancellationTokenSource())
{
CancellationToken cancellationToken = cancellationTokenSource.Token;
var ex = await Should.ThrowAsync<OperationCanceledException>(() => policy.RaiseExceptionAndOrCancellationAsync<DivideByZeroException>(scenario, cancellationTokenSource, onExecute));
ex.CancellationToken.ShouldBe(cancellationToken);
}
attemptsInvoked.ShouldBe(2);
}
[Fact]
public async Task Should_report_cancellation_during_faulting_last_retry_execution_when_user_delegate_does_observe_cancellationToken()
{
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3);
int attemptsInvoked = 0;
Action onExecute = () => attemptsInvoked++;
Scenario scenario = new Scenario
{
NumberOfTimesToRaiseException = 1 + 3,
AttemptDuringWhichToCancel = 1 + 3,
ActionObservesCancellation = true
};
using (var cancellationTokenSource = new CancellationTokenSource())
{
CancellationToken cancellationToken = cancellationTokenSource.Token;
var ex = await Should.ThrowAsync<OperationCanceledException>(() => policy.RaiseExceptionAndOrCancellationAsync<DivideByZeroException>(scenario, cancellationTokenSource, onExecute));
ex.CancellationToken.ShouldBe(cancellationToken);
}
attemptsInvoked.ShouldBe(1 + 3);
}
[Fact]
public async Task Should_report_faulting_from_faulting_last_retry_execution_when_user_delegate_does_not_observe_cancellation_raised_during_last_retry()
{
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3);
int attemptsInvoked = 0;
Action onExecute = () => attemptsInvoked++;
Scenario scenario = new Scenario
{
NumberOfTimesToRaiseException = 1 + 3,
AttemptDuringWhichToCancel = 1 + 3,
ActionObservesCancellation = false
};
using (var cancellationTokenSource = new CancellationTokenSource())
{
CancellationToken cancellationToken = cancellationTokenSource.Token;
await Should.ThrowAsync<DivideByZeroException>(() => policy.RaiseExceptionAndOrCancellationAsync<DivideByZeroException>(scenario, cancellationTokenSource, onExecute));
}
attemptsInvoked.ShouldBe(1 + 3);
}
[Fact]
public async Task Should_report_cancellation_after_faulting_action_execution_and_cancel_further_retries_if_onRetry_invokes_cancellation()
{
int attemptsInvoked = 0;
Action onExecute = () => attemptsInvoked++;
Scenario scenario = new Scenario
{
NumberOfTimesToRaiseException = 1 + 3,
AttemptDuringWhichToCancel = null, // Cancellation during onRetry instead - see below.
ActionObservesCancellation = false
};
using (var cancellationTokenSource = new CancellationTokenSource())
{
CancellationToken cancellationToken = cancellationTokenSource.Token;
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3, (_, _) =>
{
cancellationTokenSource.Cancel();
});
var ex = await Should.ThrowAsync<OperationCanceledException>(() => policy.RaiseExceptionAndOrCancellationAsync<DivideByZeroException>(scenario, cancellationTokenSource, onExecute));
ex.CancellationToken.ShouldBe(cancellationToken);
}
attemptsInvoked.ShouldBe(1);
}
[Fact]
public async Task Should_execute_func_returning_value_when_cancellationToken_not_cancelled()
{
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3);
int attemptsInvoked = 0;
Action onExecute = () => attemptsInvoked++;
bool? result = null;
Scenario scenario = new Scenario
{
NumberOfTimesToRaiseException = 0,
AttemptDuringWhichToCancel = null,
};
using (var cancellationTokenSource = new CancellationTokenSource())
{
CancellationToken cancellationToken = cancellationTokenSource.Token;
Func<Task> action = async () => result = await policy.RaiseExceptionAndOrCancellationAsync<DivideByZeroException, bool>(scenario, cancellationTokenSource, onExecute, true);
await Should.NotThrowAsync(action);
}
result.ShouldNotBeNull();
result.Value.ShouldBeTrue();
attemptsInvoked.ShouldBe(1);
}
[Fact]
public async Task Should_honour_and_report_cancellation_during_func_execution()
{
var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync(3);
int attemptsInvoked = 0;
Action onExecute = () => attemptsInvoked++;
bool? result = null;
Scenario scenario = new Scenario
{
NumberOfTimesToRaiseException = 0,
AttemptDuringWhichToCancel = 1,
ActionObservesCancellation = true
};
using (var cancellationTokenSource = new CancellationTokenSource())
{
CancellationToken cancellationToken = cancellationTokenSource.Token;
Func<Task> action = async () => result = await policy.RaiseExceptionAndOrCancellationAsync<DivideByZeroException, bool>(scenario, cancellationTokenSource, onExecute, true);
var ex = await Should.ThrowAsync<OperationCanceledException>(action);
ex.CancellationToken.ShouldBe(cancellationToken);
}
result.ShouldBeNull();
attemptsInvoked.ShouldBe(1);
}
#endregion
}
| RetryAsyncSpecs |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/Middleware/Latest_Specs.cs | {
"start": 161,
"end": 1137
} | public class ____
{
[Test]
public async Task Should_keep_track_of_only_the_last_value()
{
ILatestFilter<IInputContext<A>> latestFilter = null;
IPipe<IInputContext<A>> pipe = Pipe.New<IInputContext<A>>(x =>
{
x.UseLatest(l => l.Created = filter => latestFilter = filter);
x.UseExecute(payload =>
{
});
});
Assert.That(latestFilter, Is.Not.Null);
var inputContext = new InputContext(new object());
var limit = 100;
for (var i = 0; i <= limit; i++)
{
var context = new InputContext<A>(inputContext, new A { Index = i });
await pipe.Send(context);
}
IInputContext<A> latest = await latestFilter.Latest;
Assert.That(latest.Value.Index, Is.EqualTo(limit));
}
| Using_the_latest_filter_on_the_pipe |
csharp | FluentValidation__FluentValidation | src/FluentValidation.Tests/EnumValidatorTests.cs | {
"start": 9579,
"end": 9650
} | private enum ____ : int {
A = 0,
B = 1,
C = 2
}
[Flags]
| Int32Enum |
csharp | RicoSuter__NJsonSchema | src/NJsonSchema.CodeGeneration.CSharp/Models/ClassTemplateModel.cs | {
"start": 8477,
"end": 8612
} | class ____.</summary>
public ClassTemplateModel? BaseClass { get; }
/// <summary>Gets a value indicating whether the | model |
csharp | dotnet__efcore | test/EFCore.Tests/ChangeTracking/PropertyEntryTest.cs | {
"start": 258194,
"end": 259725
} | private abstract class ____ : HasChanged, INotifyPropertyChanging
{
public event PropertyChangingEventHandler? PropertyChanging;
protected void OnPropertyChanging([CallerMemberName] string propertyName = "")
=> PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(propertyName));
}
public static IModel BuildModel(
ChangeTrackingStrategy fullNotificationStrategy = ChangeTrackingStrategy.ChangingAndChangedNotifications,
ModelBuilder builder = null!,
bool finalize = true)
{
builder ??= InMemoryTestHelpers.Instance.CreateConventionBuilder();
builder.HasChangeTrackingStrategy(fullNotificationStrategy);
builder.Entity<Wotty>(b =>
{
b.Property(e => e.RequiredPrimate).IsRequired();
b.HasChangeTrackingStrategy(ChangeTrackingStrategy.Snapshot);
});
builder.Entity<ObjectWotty>(b =>
{
b.Property(e => e.RequiredPrimate).IsRequired();
b.HasChangeTrackingStrategy(ChangeTrackingStrategy.Snapshot);
});
builder.Entity<NotifyingWotty>(b => b.HasChangeTrackingStrategy(ChangeTrackingStrategy.ChangedNotifications));
builder.Entity<FullyNotifyingWotty>(b =>
{
b.HasChangeTrackingStrategy(fullNotificationStrategy);
b.Property(e => e.ConcurrentPrimate).IsConcurrencyToken();
});
return finalize ? builder.Model.FinalizeModel() : (IModel)builder.Model;
}
| HasChangedAndChanging |
csharp | fluentassertions__fluentassertions | Tests/FluentAssertions.Specs/Numeric/NullableNumericAssertionSpecs.BeInRange.cs | {
"start": 145,
"end": 2122
} | public class ____
{
[Theory]
[InlineData(float.NaN, 5F)]
[InlineData(5F, float.NaN)]
public void A_float_can_never_be_in_a_range_containing_NaN(float minimumValue, float maximumValue)
{
// Arrange
float? value = 4.5F;
// Act
Action act = () => value.Should().BeInRange(minimumValue, maximumValue);
// Assert
act
.Should().Throw<ArgumentException>()
.WithMessage(
"*NaN*");
}
[Fact]
public void NaN_is_never_in_range_of_two_floats()
{
// Arrange
float? value = float.NaN;
// Act
Action act = () => value.Should().BeInRange(4, 5);
// Assert
act
.Should().Throw<XunitException>()
.WithMessage(
"Expected value to be between*4* and*5*, but found*NaN*");
}
[Theory]
[InlineData(double.NaN, 5)]
[InlineData(5, double.NaN)]
public void A_double_can_never_be_in_a_range_containing_NaN(double minimumValue, double maximumValue)
{
// Arrange
double? value = 4.5;
// Act
Action act = () => value.Should().BeInRange(minimumValue, maximumValue);
// Assert
act
.Should().Throw<ArgumentException>()
.WithMessage(
"*NaN*");
}
[Fact]
public void NaN_is_never_in_range_of_two_doubles()
{
// Arrange
double? value = double.NaN;
// Act
Action act = () => value.Should().BeInRange(4, 5);
// Assert
act
.Should().Throw<XunitException>()
.WithMessage(
"Expected value to be between*4* and*5*, but found*NaN*");
}
}
| BeInRange |
csharp | aspnetboilerplate__aspnetboilerplate | src/Abp.Web.Common/Web/Models/AbpUserConfiguration/AbpUserTimingConfigDto.cs | {
"start": 52,
"end": 168
} | public class ____
{
public AbpUserTimeZoneConfigDto TimeZoneInfo { get; set; }
}
} | AbpUserTimingConfigDto |
csharp | dotnet__efcore | src/EFCore.Relational/Migrations/MigrationsAnnotationProviderDependencies.cs | {
"start": 262,
"end": 598
} | class ____ <see cref="MigrationsAnnotationProvider" />
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
/// <remarks>
/// <para>
/// Do not construct instances of this | for |
csharp | dotnet__aspnetcore | src/Components/Analyzers/test/Helpers/DiagnosticVerifier.Helper.cs | {
"start": 584,
"end": 7712
} | partial class ____
{
private static readonly MetadataReference CorlibReference = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
private static readonly MetadataReference SystemCoreReference = MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location);
private static readonly MetadataReference CSharpSymbolsReference = MetadataReference.CreateFromFile(typeof(CSharpCompilation).Assembly.Location);
private static readonly MetadataReference CodeAnalysisReference = MetadataReference.CreateFromFile(typeof(Compilation).Assembly.Location);
internal static string DefaultFilePathPrefix = "Test";
internal static string CSharpDefaultFileExt = "cs";
internal static string VisualBasicDefaultExt = "vb";
internal static string TestProjectName = "TestProject";
#region Get Diagnostics
/// <summary>
/// Given classes in the form of strings, their language, and an IDiagnosticAnalyzer to apply to it, return the diagnostics found in the string after converting it to a document.
/// </summary>
/// <param name="sources">Classes in the form of strings</param>
/// <param name="language">The language the source classes are in</param>
/// <param name="analyzer">The analyzer to be run on the sources</param>
/// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns>
private static Diagnostic[] GetSortedDiagnostics(string[] sources, string language, DiagnosticAnalyzer analyzer)
{
return GetSortedDiagnosticsFromDocuments(analyzer, GetDocuments(sources, language));
}
/// <summary>
/// Given an analyzer and a document to apply it to, run the analyzer and gather an array of diagnostics found in it.
/// The returned diagnostics are then ordered by location in the source document.
/// </summary>
/// <param name="analyzer">The analyzer to run on the documents</param>
/// <param name="documents">The Documents that the analyzer will be run on</param>
/// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns>
protected static Diagnostic[] GetSortedDiagnosticsFromDocuments(DiagnosticAnalyzer analyzer, Document[] documents)
{
var projects = new HashSet<Project>();
foreach (var document in documents)
{
projects.Add(document.Project);
}
var diagnostics = new List<Diagnostic>();
foreach (var project in projects)
{
var compilationWithAnalyzers = project.GetCompilationAsync().Result.WithAnalyzers(ImmutableArray.Create(analyzer));
var diags = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result;
foreach (var diag in diags)
{
if (diag.Location == Location.None || diag.Location.IsInMetadata)
{
diagnostics.Add(diag);
}
else
{
for (int i = 0; i < documents.Length; i++)
{
var document = documents[i];
var tree = document.GetSyntaxTreeAsync().Result;
if (tree == diag.Location.SourceTree)
{
diagnostics.Add(diag);
}
}
}
}
}
var results = SortDiagnostics(diagnostics);
diagnostics.Clear();
return results;
}
/// <summary>
/// Sort diagnostics by location in source document
/// </summary>
/// <param name="diagnostics">The list of Diagnostics to be sorted</param>
/// <returns>An IEnumerable containing the Diagnostics in order of Location</returns>
private static Diagnostic[] SortDiagnostics(IEnumerable<Diagnostic> diagnostics)
{
return diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
}
#endregion
#region Set up compilation and documents
/// <summary>
/// Given an array of strings as sources and a language, turn them into a project and return the documents and spans of it.
/// </summary>
/// <param name="sources">Classes in the form of strings</param>
/// <param name="language">The language the source code is in</param>
/// <returns>A Tuple containing the Documents produced from the sources and their TextSpans if relevant</returns>
private static Document[] GetDocuments(string[] sources, string language)
{
if (language != LanguageNames.CSharp && language != LanguageNames.VisualBasic)
{
throw new ArgumentException("Unsupported Language");
}
var project = CreateProject(sources, language);
var documents = project.Documents.ToArray();
if (sources.Length != documents.Length)
{
throw new InvalidOperationException("Amount of sources did not match amount of Documents created");
}
return documents;
}
/// <summary>
/// Create a Document from a string through creating a project that contains it.
/// </summary>
/// <param name="source">Classes in the form of a string</param>
/// <param name="language">The language the source code is in</param>
/// <returns>A Document created from the source string</returns>
protected static Document CreateDocument(string source, string language = LanguageNames.CSharp)
{
return CreateProject(new[] { source }, language).Documents.First();
}
/// <summary>
/// Create a project using the inputted strings as sources.
/// </summary>
/// <param name="sources">Classes in the form of strings</param>
/// <param name="language">The language the source code is in</param>
/// <returns>A Project created out of the Documents created from the source strings</returns>
private static Project CreateProject(string[] sources, string language = LanguageNames.CSharp)
{
string fileNamePrefix = DefaultFilePathPrefix;
string fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;
var projectId = ProjectId.CreateNewId(debugName: TestProjectName);
var solution = new AdhocWorkspace()
.CurrentSolution
.AddProject(projectId, TestProjectName, TestProjectName, language)
.AddMetadataReference(projectId, CorlibReference)
.AddMetadataReference(projectId, SystemCoreReference)
.AddMetadataReference(projectId, CSharpSymbolsReference)
.AddMetadataReference(projectId, CodeAnalysisReference);
int count = 0;
foreach (var source in sources)
{
var newFileName = fileNamePrefix + count + "." + fileExt;
var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName);
solution = solution.AddDocument(documentId, newFileName, SourceText.From(source));
count++;
}
return solution.GetProject(projectId);
}
#endregion
}
| DiagnosticVerifier |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs | {
"start": 5256,
"end": 8523
} | public class ____
{
public string PropertyName { get; set; }
}
[Test]
public void SerializeReadOnlyProperty()
{
Child c = new Child
{
PropertyName = "value?"
};
IList<string> l = new List<string>
{
"value!"
};
Parent p = new Parent
{
Child1 = c,
Child2 = c,
List1 = l,
List2 = l
};
string json = JsonConvert.SerializeObject(p, new JsonSerializerSettings
{
Formatting = Formatting.Indented,
PreserveReferencesHandling = PreserveReferencesHandling.All
});
StringAssert.AreEqual(@"{
""$id"": ""1"",
""ReadOnlyChild"": {
""PropertyName"": ""value?""
},
""Child1"": {
""$id"": ""2"",
""PropertyName"": ""value?""
},
""Child2"": {
""$ref"": ""2""
},
""ReadOnlyList"": [
""value!""
],
""List1"": {
""$id"": ""3"",
""$values"": [
""value!""
]
},
""List2"": {
""$ref"": ""3""
}
}", json);
Parent newP = JsonConvert.DeserializeObject<Parent>(json, new JsonSerializerSettings
{
Formatting = Formatting.Indented,
PreserveReferencesHandling = PreserveReferencesHandling.All
});
Assert.AreEqual("value?", newP.Child1.PropertyName);
Assert.AreEqual(newP.Child1, newP.Child2);
Assert.AreEqual(newP.Child1, newP.ReadOnlyChild);
Assert.AreEqual("value!", newP.List1[0]);
Assert.AreEqual(newP.List1, newP.List2);
Assert.AreEqual(newP.List1, newP.ReadOnlyList);
}
[Test]
public void SerializeDictionarysWithPreserveObjectReferences()
{
CircularDictionary circularDictionary = new CircularDictionary();
circularDictionary.Add("other", new CircularDictionary { { "blah", null } });
circularDictionary.Add("self", circularDictionary);
string json = JsonConvert.SerializeObject(circularDictionary, Formatting.Indented,
new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All });
StringAssert.AreEqual(@"{
""$id"": ""1"",
""other"": {
""$id"": ""2"",
""blah"": null
},
""self"": {
""$ref"": ""1""
}
}", json);
}
[Test]
public void DeserializeDictionarysWithPreserveObjectReferences()
{
string json = @"{
""$id"": ""1"",
""other"": {
""$id"": ""2"",
""blah"": null
},
""self"": {
""$ref"": ""1""
}
}";
CircularDictionary circularDictionary = JsonConvert.DeserializeObject<CircularDictionary>(json,
new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All
});
Assert.AreEqual(2, circularDictionary.Count);
Assert.AreEqual(1, circularDictionary["other"].Count);
Assert.IsTrue(ReferenceEquals(circularDictionary, circularDictionary["self"]));
}
| Child |
csharp | abpframework__abp | framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreMvcModule.cs | {
"start": 1998,
"end": 10840
} | public class ____ : AbpModule
{
public override void PreConfigureServices(ServiceConfigurationContext context)
{
DynamicProxyIgnoreTypes.Add<ControllerBase>();
DynamicProxyIgnoreTypes.Add<PageModel>();
DynamicProxyIgnoreTypes.Add<ViewComponent>();
context.Services.AddConventionalRegistrar(new AbpAspNetCoreMvcConventionalRegistrar());
}
public override void ConfigureServices(ServiceConfigurationContext context)
{
Configure<AbpApiDescriptionModelOptions>(options =>
{
options.IgnoredInterfaces.AddIfNotContains(typeof(IAsyncActionFilter));
options.IgnoredInterfaces.AddIfNotContains(typeof(IFilterMetadata));
options.IgnoredInterfaces.AddIfNotContains(typeof(IActionFilter));
});
Configure<AbpRemoteServiceApiDescriptionProviderOptions>(options =>
{
var statusCodes = new List<int>
{
(int) HttpStatusCode.Forbidden,
(int) HttpStatusCode.Unauthorized,
(int) HttpStatusCode.BadRequest,
(int) HttpStatusCode.NotFound,
(int) HttpStatusCode.NotImplemented,
(int) HttpStatusCode.InternalServerError
};
options.SupportedResponseTypes.AddIfNotContains(statusCodes.Select(statusCode => new ApiResponseType
{
Type = typeof(RemoteServiceErrorResponse),
StatusCode = statusCode
}));
});
context.Services.PostConfigure<AbpAspNetCoreMvcOptions>(options =>
{
if (options.MinifyGeneratedScript == null)
{
options.MinifyGeneratedScript = context.Services.GetHostingEnvironment().IsProduction();
}
});
var mvcCoreBuilder = context.Services.AddMvcCore(options =>
{
options.Filters.Add(new AbpAutoValidateAntiforgeryTokenAttribute());
});
context.Services.ExecutePreConfiguredActions(mvcCoreBuilder);
var abpMvcDataAnnotationsLocalizationOptions = context.Services
.ExecutePreConfiguredActions(
new AbpMvcDataAnnotationsLocalizationOptions()
);
context.Services
.AddSingleton<IOptions<AbpMvcDataAnnotationsLocalizationOptions>>(
new OptionsWrapper<AbpMvcDataAnnotationsLocalizationOptions>(
abpMvcDataAnnotationsLocalizationOptions
)
);
var mvcBuilder = context.Services.AddMvc()
.AddDataAnnotationsLocalization(options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
{
var resourceType = abpMvcDataAnnotationsLocalizationOptions
.AssemblyResources
.GetOrDefault(type.Assembly);
if (resourceType != null)
{
return factory.Create(resourceType);
}
return factory.CreateDefaultOrNull() ??
factory.Create(type);
};
})
.AddViewLocalization(); //TODO: How to configure from the application? Also, consider to move to a UI module since APIs does not care about it.
mvcCoreBuilder.AddAbpJson();
context.Services.ExecutePreConfiguredActions(mvcBuilder);
//TODO: AddViewLocalization by default..?
//Use DI to create controllers
mvcBuilder.AddControllersAsServices();
//Use DI to create view components
mvcBuilder.AddViewComponentsAsServices();
//Use DI to create razor page
context.Services.Replace(ServiceDescriptor.Singleton<IPageModelActivatorProvider, ServiceBasedPageModelActivatorProvider>());
//Add feature providers
var partManager = context.Services.GetSingletonInstance<ApplicationPartManager>();
var application = context.Services.GetSingletonInstance<IAbpApplication>();
partManager.FeatureProviders.Add(new AbpConventionalControllerFeatureProvider(application));
partManager.ApplicationParts.AddIfNotContains(typeof(AbpAspNetCoreMvcModule).Assembly);
context.Services.Replace(ServiceDescriptor.Singleton<IValidationAttributeAdapterProvider, AbpValidationAttributeAdapterProvider>());
context.Services.AddSingleton<ValidationAttributeAdapterProvider>();
context.Services.TryAddEnumerable(ServiceDescriptor.Transient<IActionDescriptorProvider, AbpMvcActionDescriptorProvider>());
context.Services.AddOptions<MvcOptions>()
.Configure<IServiceProvider>((mvcOptions, serviceProvider) =>
{
mvcOptions.AddAbp(context.Services);
// serviceProvider is root service provider.
var stringLocalizer = serviceProvider.GetRequiredService<IStringLocalizer<AbpValidationResource>>();
mvcOptions.ModelBindingMessageProvider.SetValueIsInvalidAccessor(_ => stringLocalizer["The value '{0}' is invalid."]);
mvcOptions.ModelBindingMessageProvider.SetNonPropertyValueMustBeANumberAccessor(() => stringLocalizer["The field must be a number."]);
mvcOptions.ModelBindingMessageProvider.SetValueMustBeANumberAccessor(value => stringLocalizer["The field {0} must be a number.", value]);
});
Configure<AbpEndpointRouterOptions>(options =>
{
options.EndpointConfigureActions.Add(endpointContext =>
{
endpointContext.Endpoints.MapControllerRoute("defaultWithArea", "{area}/{controller=Home}/{action=Index}/{id?}");
endpointContext.Endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}").WithStaticAssets();
endpointContext.Endpoints.MapRazorPages().WithStaticAssets();
});
});
Configure<DynamicJavaScriptProxyOptions>(options =>
{
options.DisableModule("abp");
});
context.Services.Replace(ServiceDescriptor.Singleton<IHttpResponseStreamWriterFactory, AbpMemoryPoolHttpResponseStreamWriterFactory>());
}
public override void PostConfigureServices(ServiceConfigurationContext context)
{
ApplicationPartSorter.Sort(
context.Services.GetSingletonInstance<ApplicationPartManager>(),
context.Services.GetSingletonInstance<IModuleContainer>()
);
var preConfigureActions = context.Services.GetPreConfigureActions<AbpAspNetCoreMvcOptions>();
DynamicProxyIgnoreTypes.Add(preConfigureActions.Configure()
.ConventionalControllers
.ConventionalControllerSettings.SelectMany(x => x.ControllerTypes).ToArray());
Configure<AbpAspNetCoreMvcOptions>(options =>
{
preConfigureActions.Configure(options);
});
}
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
AddApplicationParts(context);
CheckLibs(context);
}
private static void AddApplicationParts(ApplicationInitializationContext context)
{
var partManager = context.ServiceProvider.GetService<ApplicationPartManager>();
if (partManager == null)
{
return;
}
var moduleContainer = context.ServiceProvider.GetRequiredService<IModuleContainer>();
var plugInModuleAssemblies = moduleContainer
.Modules
.Where(m => m.IsLoadedAsPlugIn)
.SelectMany(m => m.AllAssemblies)
.Distinct();
AddToApplicationParts(partManager, plugInModuleAssemblies);
var controllerAssemblies = context
.ServiceProvider
.GetRequiredService<IOptions<AbpAspNetCoreMvcOptions>>()
.Value
.ConventionalControllers
.ConventionalControllerSettings
.Select(s => s.Assembly)
.Distinct();
AddToApplicationParts(partManager, controllerAssemblies);
var additionalAssemblies = moduleContainer
.Modules
.SelectMany(m => m.GetAdditionalAssemblies())
.Distinct();
AddToApplicationParts(partManager, additionalAssemblies);
}
private static void AddToApplicationParts(ApplicationPartManager partManager, IEnumerable<Assembly> moduleAssemblies)
{
foreach (var moduleAssembly in moduleAssemblies)
{
partManager.ApplicationParts.AddIfNotContains(moduleAssembly);
}
}
private static void CheckLibs(ApplicationInitializationContext context)
{
context.ServiceProvider.GetRequiredService<IAbpMvcLibsService>().CheckLibs(context);
}
}
| AbpAspNetCoreMvcModule |
csharp | microsoft__semantic-kernel | dotnet/test/VectorData/SqlServer.ConformanceTests/TypeTests/SqlServerEmbeddingTypeTests.cs | {
"start": 917,
"end": 1057
} | class ____ : EmbeddingTypeTests<Guid>.Fixture
{
public override TestStore TestStore => SqlServerTestStore.Instance;
}
}
| Fixture |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Sitemaps/Handlers/SitemapPartHandler.cs | {
"start": 160,
"end": 714
} | public class ____ : ContentPartHandler<SitemapPart>
{
public override Task GetContentItemAspectAsync(ContentItemAspectContext context, SitemapPart part)
{
return context.ForAsync<SitemapMetadataAspect>(aspect =>
{
if (part.OverrideSitemapConfig)
{
aspect.ChangeFrequency = part.ChangeFrequency.ToString();
aspect.Priority = part.Priority;
aspect.Exclude = part.Exclude;
}
return Task.CompletedTask;
});
}
}
| SitemapPartHandler |
csharp | bitwarden__server | test/Core.Test/AutoFixture/UserFixtures.cs | {
"start": 1403,
"end": 1546
} | internal class ____ : BitCustomizeAttribute
{
public override ICustomization GetCustomization() => new UserFixture();
}
| UserCustomizeAttribute |
csharp | cake-build__cake | src/Cake.Common.Tests/Fixtures/Tools/SignToolResolverFixture.cs | {
"start": 345,
"end": 5660
} | internal sealed class ____
{
private readonly bool _is64Bit;
public IFileSystem FileSystem { get; set; }
public ICakeEnvironment Environment { get; set; }
public IRegistry Registry { get; set; }
public SignToolResolverFixture(bool is64Bit = true)
{
_is64Bit = is64Bit;
FileSystem = Substitute.For<IFileSystem>();
Environment = Substitute.For<ICakeEnvironment>();
Registry = Substitute.For<IRegistry>();
Environment.Platform.Is64Bit.Returns(_is64Bit);
Environment.GetSpecialPath(SpecialPath.ProgramFiles).Returns("/ProgramFiles");
Environment.GetSpecialPath(SpecialPath.ProgramFilesX86).Returns("/ProgramFilesX86");
}
public void GivenThatToolExistInKnownPath()
{
if (_is64Bit)
{
FileSystem.Exist(Arg.Is<FilePath>(p => p.FullPath == "/ProgramFilesX86/Windows Kits/8.1/bin/x64/signtool.exe")).Returns(true);
}
else
{
FileSystem.Exist(Arg.Is<FilePath>(p => p.FullPath == "/ProgramFiles/Windows Kits/8.1/bin/x86/signtool.exe")).Returns(true);
}
}
public void GivenThatToolExistInKnownPathWindows10()
{
if (_is64Bit)
{
FileSystem.Exist(Arg.Is<FilePath>(p => p.FullPath == "/ProgramFilesX86/Windows Kits/10/bin/x64/signtool.exe")).Returns(true);
}
else
{
FileSystem.Exist(Arg.Is<FilePath>(p => p.FullPath == "/ProgramFiles/Windows Kits/10/bin/x86/signtool.exe")).Returns(true);
}
}
public void GivenThatToolExistInKnownPathAppCertificationKit()
{
if (_is64Bit)
{
FileSystem.Exist(Arg.Is<FilePath>(p => p.FullPath == "/ProgramFilesX86/Windows Kits/10/App Certification Kit/signtool.exe")).Returns(true);
}
else
{
FileSystem.Exist(Arg.Is<FilePath>(p => p.FullPath == "/ProgramFiles/Windows Kits/10/App Certification Kit/signtool.exe")).Returns(true);
}
}
public void GivenThatToolHasRegistryKeyMicrosoftSdks()
{
var signToolKey = Substitute.For<IRegistryKey>();
signToolKey.GetValue("InstallationFolder").Returns("/SignTool");
var windowsKey = Substitute.For<IRegistryKey>();
windowsKey.GetSubKeyNames().Returns(new[] { "v8.1A" });
windowsKey.OpenKey("v8.1A").Returns(signToolKey);
var localMachine = Substitute.For<IRegistryKey>();
localMachine.OpenKey("Software\\Microsoft\\Microsoft SDKs\\Windows").Returns(windowsKey);
FileSystem.Exist(Arg.Is<FilePath>(p => p.FullPath == "/SignTool/bin/signtool.exe")).Returns(true);
Registry.LocalMachine.Returns(localMachine);
}
public void GivenThatToolHasRegistryKeyWindowsKits()
{
var signToolKey = Substitute.For<IRegistryKey>();
signToolKey.GetValue("KitsRoot").Returns("/SignTool");
var localMachine = Substitute.For<IRegistryKey>();
localMachine.OpenKey("Software\\Microsoft\\Windows Kits\\Installed Roots").Returns(signToolKey);
if (_is64Bit)
{
FileSystem.Exist(Arg.Is<FilePath>(p => p.FullPath == "/SignTool/bin/x64/signtool.exe")).Returns(true);
}
else
{
FileSystem.Exist(Arg.Is<FilePath>(p => p.FullPath == "/SignTool/bin/x86/signtool.exe")).Returns(true);
}
Registry.LocalMachine.Returns(localMachine);
}
public void GivenThatToolHasRegistryKeyWindows10Kits()
{
var versions = new[] { "10.0.15063.0", "10.0.16299.0" };
var signToolKey = Substitute.For<IRegistryKey>();
signToolKey.GetValue("KitsRoot10").Returns("/SignTool");
signToolKey.GetSubKeyNames().Returns(versions);
var localMachine = Substitute.For<IRegistryKey>();
localMachine.OpenKey("Software\\Microsoft\\Windows Kits\\Installed Roots").Returns(signToolKey);
foreach (string version in versions)
{
if (_is64Bit)
{
FileSystem.Exist(Arg.Is<FilePath>(p => p.FullPath == $"/SignTool/bin/{version}/x64/signtool.exe"))
.Returns(true);
}
else
{
FileSystem.Exist(Arg.Is<FilePath>(p => p.FullPath == $"/SignTool/bin/{version}/x86/signtool.exe"))
.Returns(true);
}
}
Registry.LocalMachine.Returns(localMachine);
}
public void GivenThatNoSdkRegistryKeyExist()
{
var localMachine = Substitute.For<IRegistryKey>();
localMachine.OpenKey("Software\\Microsoft\\Microsoft SDKs\\Windows").Returns((IRegistryKey)null);
Registry.LocalMachine.Returns(localMachine);
}
public FilePath Resolve()
{
var resolver = new SignToolResolver(FileSystem, Environment, Registry);
return resolver.GetPath();
}
}
} | SignToolResolverFixture |
csharp | dotnet__aspire | src/Components/Aspire.Oracle.EntityFrameworkCore/api/Aspire.Oracle.EntityFrameworkCore.cs | {
"start": 420,
"end": 1064
} | partial class ____
{
public int? CommandTimeout { get { throw null; } set { } }
public string? ConnectionString { get { throw null; } set { } }
public bool DisableHealthChecks { get { throw null; } set { } }
public bool DisableRetry { get { throw null; } set { } }
public bool DisableTracing { get { throw null; } set { } }
public System.Action<global::Oracle.ManagedDataAccess.OpenTelemetry.OracleDataProviderInstrumentationOptions>? InstrumentationOptions { get { throw null; } set { } }
}
}
namespace Microsoft.Extensions.Hosting
{
public static | OracleEntityFrameworkCoreSettings |
csharp | dotnet__reactive | Rx.NET/Source/src/System.Reactive/Linq/Observable/Delay.cs | {
"start": 23728,
"end": 25457
} | private sealed class ____ : SafeObserver<TDelay>
{
private readonly _ _parent;
private readonly TSource _value;
private bool _once;
public DelayObserver(_ parent, TSource value)
{
_parent = parent;
_value = value;
}
public override void OnNext(TDelay value)
{
if (!_once)
{
_once = true;
lock (_parent._gate)
{
_parent.ForwardOnNext(_value);
_parent._delays.Remove(this);
_parent.CheckDone();
}
}
}
public override void OnError(Exception error)
{
lock (_parent._gate)
{
_parent.ForwardOnError(error);
}
}
public override void OnCompleted()
{
if (!_once)
{
lock (_parent._gate)
{
_parent.ForwardOnNext(_value);
_parent._delays.Remove(this);
_parent.CheckDone();
}
}
}
}
}
}
| DelayObserver |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/NorthwindAuto/Migrations/Migration1001.cs | {
"start": 815,
"end": 2115
} | public class ____ : AuditBase
{
[AutoIncrement]
public int Id { get; set; } // 'Id' is PrimaryKey by convention
[Required]
public string FirstName { get; set; } // Creates NOT NULL Column
[Alias("Surname")] // Maps to [Surname] RDBMS column
public string LastName { get; set; }
[Index(Unique = true)] // Creates Unique Index
public string Email { get; set; }
public List<Phone> PhoneNumbers { get; set; } // Complex Types blobbed by default
[Reference]
public List<PlayerGameItem> GameItems { get; set; } // 1:M Reference Type saved separately
[Reference]
public Profile Profile { get; set; } // 1:1 Reference Type saved separately
public int ProfileId { get; set; } // 1:1 Self Ref Id on Parent Table
[ForeignKey(typeof(Level), OnDelete="CASCADE")] // Creates ON DELETE CASCADE Constraint
public Guid SavedLevelId { get; set; } // Creates Foreign Key Reference
public ulong RowVersion { get; set; } // Optimistic Concurrency Updates
public string CAPITAL { get; set; } // All capital column name
}
| Player |
csharp | unoplatform__uno | src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Controls/TextControlPasteEventArgs.cs | {
"start": 261,
"end": 556
} | public partial class ____
{
// Skipping already declared property Handled
// Forced skipping of method Microsoft.UI.Xaml.Controls.TextControlPasteEventArgs.Handled.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.TextControlPasteEventArgs.Handled.set
}
}
| TextControlPasteEventArgs |
csharp | dotnet__aspnetcore | src/Shared/CertificateGeneration/CertificateManager.cs | {
"start": 38461,
"end": 64327
} | public sealed class ____ : EventSource
{
[Event(1, Level = EventLevel.Verbose, Message = "Listing certificates from {0}\\{1}")]
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Parameters passed to WriteEvent are all primative values.")]
public void ListCertificatesStart(StoreLocation location, StoreName storeName) => WriteEvent(1, location, storeName);
[Event(2, Level = EventLevel.Verbose, Message = "Found certificates: {0}")]
public void DescribeFoundCertificates(string matchingCertificates) => WriteEvent(2, matchingCertificates);
[Event(3, Level = EventLevel.Verbose, Message = "Checking certificates validity")]
public void CheckCertificatesValidity() => WriteEvent(3);
[Event(4, Level = EventLevel.Verbose, Message = "Valid certificates: {0}")]
public void DescribeValidCertificates(string validCertificates) => WriteEvent(4, validCertificates);
[Event(5, Level = EventLevel.Verbose, Message = "Invalid certificates: {0}")]
public void DescribeInvalidCertificates(string invalidCertificates) => WriteEvent(5, invalidCertificates);
[Event(6, Level = EventLevel.Verbose, Message = "Finished listing certificates.")]
public void ListCertificatesEnd() => WriteEvent(6);
[Event(7, Level = EventLevel.Error, Message = "An error occurred while listing the certificates: {0}")]
public void ListCertificatesError(string e) => WriteEvent(7, e);
[Event(8, Level = EventLevel.Verbose, Message = "Filtered certificates: {0}")]
public void FilteredCertificates(string filteredCertificates) => WriteEvent(8, filteredCertificates);
[Event(9, Level = EventLevel.Verbose, Message = "Excluded certificates: {0}")]
public void ExcludedCertificates(string excludedCertificates) => WriteEvent(9, excludedCertificates);
[Event(14, Level = EventLevel.Verbose, Message = "Valid certificates: {0}")]
public void ValidCertificatesFound(string certificates) => WriteEvent(14, certificates);
[Event(15, Level = EventLevel.Verbose, Message = "Selected certificate: {0}")]
public void SelectedCertificate(string certificate) => WriteEvent(15, certificate);
[Event(16, Level = EventLevel.Verbose, Message = "No valid certificates found.")]
public void NoValidCertificatesFound() => WriteEvent(16);
[Event(17, Level = EventLevel.Verbose, Message = "Generating HTTPS development certificate.")]
public void CreateDevelopmentCertificateStart() => WriteEvent(17);
[Event(18, Level = EventLevel.Verbose, Message = "Finished generating HTTPS development certificate.")]
public void CreateDevelopmentCertificateEnd() => WriteEvent(18);
[Event(19, Level = EventLevel.Error, Message = "An error has occurred generating the certificate: {0}.")]
public void CreateDevelopmentCertificateError(string e) => WriteEvent(19, e);
[Event(20, Level = EventLevel.Verbose, Message = "Saving certificate '{0}' to store {2}\\{1}.")]
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Parameters passed to WriteEvent are all primitive values.")]
public void SaveCertificateInStoreStart(string certificate, StoreName name, StoreLocation location) => WriteEvent(20, certificate, name, location);
[Event(21, Level = EventLevel.Verbose, Message = "Finished saving certificate to the store.")]
public void SaveCertificateInStoreEnd() => WriteEvent(21);
[Event(22, Level = EventLevel.Error, Message = "An error has occurred saving the certificate: {0}.")]
public void SaveCertificateInStoreError(string e) => WriteEvent(22, e);
[Event(23, Level = EventLevel.Verbose, Message = "Saving certificate '{0}' to {1} {2} private key.")]
public void ExportCertificateStart(string certificate, string path, bool includePrivateKey) => WriteEvent(23, certificate, path, includePrivateKey ? "with" : "without");
[Event(24, Level = EventLevel.Verbose, Message = "Exporting certificate with private key but no password.")]
public void NoPasswordForCertificate() => WriteEvent(24);
[Event(25, Level = EventLevel.Verbose, Message = "Creating directory {0}.")]
public void CreateExportCertificateDirectory(string path) => WriteEvent(25, path);
[Event(26, Level = EventLevel.Error, Message = "An error has occurred while exporting the certificate: {0}.")]
public void ExportCertificateError(string error) => WriteEvent(26, error);
[Event(27, Level = EventLevel.Verbose, Message = "Writing the certificate to: {0}.")]
public void WriteCertificateToDisk(string path) => WriteEvent(27, path);
[Event(28, Level = EventLevel.Error, Message = "An error has occurred while writing the certificate to disk: {0}.")]
public void WriteCertificateToDiskError(string error) => WriteEvent(28, error);
[Event(29, Level = EventLevel.Verbose, Message = "Trusting the certificate to: {0}.")]
public void TrustCertificateStart(string certificate) => WriteEvent(29, certificate);
[Event(30, Level = EventLevel.Verbose, Message = "Finished trusting the certificate.")]
public void TrustCertificateEnd() => WriteEvent(30);
[Event(31, Level = EventLevel.Error, Message = "An error has occurred while trusting the certificate: {0}.")]
public void TrustCertificateError(string error) => WriteEvent(31, error);
[Event(32, Level = EventLevel.Verbose, Message = "Running the trust command {0}.")]
public void MacOSTrustCommandStart(string command) => WriteEvent(32, command);
[Event(33, Level = EventLevel.Verbose, Message = "Finished running the trust command.")]
public void MacOSTrustCommandEnd() => WriteEvent(33);
[Event(34, Level = EventLevel.Warning, Message = "An error has occurred while running the trust command: {0}.")]
public void MacOSTrustCommandError(int exitCode) => WriteEvent(34, exitCode);
[Event(35, Level = EventLevel.Verbose, Message = "Running the remove trust command for {0}.")]
public void MacOSRemoveCertificateTrustRuleStart(string certificate) => WriteEvent(35, certificate);
[Event(36, Level = EventLevel.Verbose, Message = "Finished running the remove trust command.")]
public void MacOSRemoveCertificateTrustRuleEnd() => WriteEvent(36);
[Event(37, Level = EventLevel.Warning, Message = "An error has occurred while running the remove trust command: {0}.")]
public void MacOSRemoveCertificateTrustRuleError(int exitCode) => WriteEvent(37, exitCode);
[Event(38, Level = EventLevel.Verbose, Message = "The certificate is not trusted: {0}.")]
public void MacOSCertificateUntrusted(string certificate) => WriteEvent(38, certificate);
[Event(39, Level = EventLevel.Verbose, Message = "Removing the certificate from the keychain {0} {1}.")]
public void MacOSRemoveCertificateFromKeyChainStart(string keyChain, string certificate) => WriteEvent(39, keyChain, certificate);
[Event(40, Level = EventLevel.Verbose, Message = "Finished removing the certificate from the keychain.")]
public void MacOSRemoveCertificateFromKeyChainEnd() => WriteEvent(40);
[Event(41, Level = EventLevel.Warning, Message = "An error has occurred while running the remove trust command: {0}.")]
public void MacOSRemoveCertificateFromKeyChainError(int exitCode) => WriteEvent(41, exitCode);
[Event(42, Level = EventLevel.Verbose, Message = "Removing the certificate from the user store {0}.")]
public void RemoveCertificateFromUserStoreStart(string certificate) => WriteEvent(42, certificate);
[Event(43, Level = EventLevel.Verbose, Message = "Finished removing the certificate from the user store.")]
public void RemoveCertificateFromUserStoreEnd() => WriteEvent(43);
[Event(44, Level = EventLevel.Error, Message = "An error has occurred while removing the certificate from the user store: {0}.")]
public void RemoveCertificateFromUserStoreError(string error) => WriteEvent(44, error);
[Event(45, Level = EventLevel.Verbose, Message = "Adding certificate to the trusted root certification authority store.")]
public void WindowsAddCertificateToRootStore() => WriteEvent(45);
[Event(46, Level = EventLevel.Verbose, Message = "The certificate is already trusted.")]
public void WindowsCertificateAlreadyTrusted() => WriteEvent(46);
[Event(47, Level = EventLevel.Verbose, Message = "Trusting the certificate was cancelled by the user.")]
public void WindowsCertificateTrustCanceled() => WriteEvent(47);
[Event(48, Level = EventLevel.Verbose, Message = "Removing the certificate from the trusted root certification authority store.")]
public void WindowsRemoveCertificateFromRootStoreStart() => WriteEvent(48);
[Event(49, Level = EventLevel.Verbose, Message = "Finished removing the certificate from the trusted root certification authority store.")]
public void WindowsRemoveCertificateFromRootStoreEnd() => WriteEvent(49);
[Event(50, Level = EventLevel.Verbose, Message = "The certificate was not trusted.")]
public void WindowsRemoveCertificateFromRootStoreNotFound() => WriteEvent(50);
[Event(51, Level = EventLevel.Verbose, Message = "Correcting the the certificate state for '{0}'.")]
public void CorrectCertificateStateStart(string certificate) => WriteEvent(51, certificate);
[Event(52, Level = EventLevel.Verbose, Message = "Finished correcting the certificate state.")]
public void CorrectCertificateStateEnd() => WriteEvent(52);
[Event(53, Level = EventLevel.Error, Message = "An error has occurred while correcting the certificate state: {0}.")]
public void CorrectCertificateStateError(string error) => WriteEvent(53, error);
[Event(54, Level = EventLevel.Verbose, Message = "Importing the certificate {1} to the keychain '{0}'.")]
internal void MacOSAddCertificateToKeyChainStart(string keychain, string certificate) => WriteEvent(54, keychain, certificate);
[Event(55, Level = EventLevel.Verbose, Message = "Finished importing the certificate to the keychain.")]
internal void MacOSAddCertificateToKeyChainEnd() => WriteEvent(55);
[Event(56, Level = EventLevel.Error, Message = "An error has occurred while importing the certificate to the keychain: {0}, {1}")]
internal void MacOSAddCertificateToKeyChainError(int exitCode, string output) => WriteEvent(56, exitCode, output);
[Event(57, Level = EventLevel.Verbose, Message = "Writing the certificate to: {0}.")]
public void WritePemKeyToDisk(string path) => WriteEvent(57, path);
[Event(58, Level = EventLevel.Error, Message = "An error has occurred while writing the certificate to disk: {0}.")]
public void WritePemKeyToDiskError(string error) => WriteEvent(58, error);
[Event(59, Level = EventLevel.Error, Message = "The file '{0}' does not exist.")]
internal void ImportCertificateMissingFile(string certificatePath) => WriteEvent(59, certificatePath);
[Event(60, Level = EventLevel.Error, Message = "One or more HTTPS certificates exist '{0}'.")]
internal void ImportCertificateExistingCertificates(string certificateDescription) => WriteEvent(60, certificateDescription);
[Event(61, Level = EventLevel.Verbose, Message = "Loading certificate from path '{0}'.")]
internal void LoadCertificateStart(string certificatePath) => WriteEvent(61, certificatePath);
[Event(62, Level = EventLevel.Verbose, Message = "The certificate '{0}' has been loaded successfully.")]
internal void LoadCertificateEnd(string description) => WriteEvent(62, description);
[Event(63, Level = EventLevel.Error, Message = "An error has occurred while loading the certificate from disk: {0}.")]
internal void LoadCertificateError(string error) => WriteEvent(63, error);
[Event(64, Level = EventLevel.Error, Message = "The provided certificate '{0}' is not a valid ASP.NET Core HTTPS development certificate.")]
internal void NoHttpsDevelopmentCertificate(string description) => WriteEvent(64, description);
[Event(65, Level = EventLevel.Verbose, Message = "The certificate is already trusted.")]
public void MacOSCertificateAlreadyTrusted() => WriteEvent(65);
[Event(66, Level = EventLevel.Verbose, Message = "Saving the certificate {1} to the user profile folder '{0}'.")]
internal void MacOSAddCertificateToUserProfileDirStart(string directory, string certificate) => WriteEvent(66, directory, certificate);
[Event(67, Level = EventLevel.Verbose, Message = "Finished saving the certificate to the user profile folder.")]
internal void MacOSAddCertificateToUserProfileDirEnd() => WriteEvent(67);
[Event(68, Level = EventLevel.Error, Message = "An error has occurred while saving certificate '{0}' in the user profile folder: {1}.")]
internal void MacOSAddCertificateToUserProfileDirError(string certificateThumbprint, string errorMessage) => WriteEvent(68, certificateThumbprint, errorMessage);
[Event(69, Level = EventLevel.Error, Message = "An error has occurred while removing certificate '{0}' from the user profile folder: {1}.")]
internal void MacOSRemoveCertificateFromUserProfileDirError(string certificateThumbprint, string errorMessage) => WriteEvent(69, certificateThumbprint, errorMessage);
[Event(70, Level = EventLevel.Error, Message = "The file '{0}' is not a valid certificate.")]
internal void MacOSFileIsNotAValidCertificate(string path) => WriteEvent(70, path);
[Event(71, Level = EventLevel.Warning, Message = "The on-disk store directory was not found.")]
internal void MacOSDiskStoreDoesNotExist() => WriteEvent(71);
[Event(72, Level = EventLevel.Verbose, Message = "Reading OpenSSL trusted certificates location from {0}.")]
internal void UnixOpenSslCertificateDirectoryOverridePresent(string nssDbOverrideVariableName) => WriteEvent(72, nssDbOverrideVariableName);
[Event(73, Level = EventLevel.Verbose, Message = "Reading NSS database locations from {0}.")]
internal void UnixNssDbOverridePresent(string environmentVariable) => WriteEvent(73, environmentVariable);
// Recoverable - just don't use it.
[Event(74, Level = EventLevel.Warning, Message = "The NSS database '{0}' provided via {1} does not exist.")]
internal void UnixNssDbDoesNotExist(string nssDb, string environmentVariable) => WriteEvent(74, nssDb, environmentVariable);
[Event(75, Level = EventLevel.Warning, Message = "The certificate is not trusted by .NET. This will likely affect System.Net.Http.HttpClient.")]
internal void UnixNotTrustedByDotnet() => WriteEvent(75);
[Event(76, Level = EventLevel.Warning, Message = "The certificate is not trusted by OpenSSL. Ensure that the {0} environment variable is set correctly.")]
internal void UnixNotTrustedByOpenSsl(string envVarName) => WriteEvent(76, envVarName);
[Event(77, Level = EventLevel.Warning, Message = "The certificate is not trusted in the NSS database in '{0}'. This will likely affect the {1} family of browsers.")]
internal void UnixNotTrustedByNss(string path, string browser) => WriteEvent(77, path, browser);
// If there's no home directory, there are no NSS DBs to check (barring an override), but this isn't strictly a problem.
[Event(78, Level = EventLevel.Verbose, Message = "Home directory '{0}' does not exist. Unable to discover NSS databases for user '{1}'. This will likely affect browsers.")]
internal void UnixHomeDirectoryDoesNotExist(string homeDirectory, string username) => WriteEvent(78, homeDirectory, username);
// Checking the system-wide OpenSSL directory is only used to make output more helpful - don't warn if it fails.
[Event(79, Level = EventLevel.Verbose, Message = "OpenSSL reported its directory in an unexpected format.")]
internal void UnixOpenSslVersionParsingFailed() => WriteEvent(79);
// Checking the system-wide OpenSSL directory is only used to make output more helpful - don't warn if it fails.
[Event(80, Level = EventLevel.Verbose, Message = "Unable to determine the OpenSSL directory.")]
internal void UnixOpenSslVersionFailed() => WriteEvent(80);
// Checking the system-wide OpenSSL directory is only used to make output more helpful - don't warn if it fails.
[Event(81, Level = EventLevel.Verbose, Message = "Unable to determine the OpenSSL directory: {0}.")]
internal void UnixOpenSslVersionException(string exceptionMessage) => WriteEvent(81, exceptionMessage);
// We'll continue on to NSS DB, but leaving the OpenSSL hash files in a bad state is a real problem.
[Event(82, Level = EventLevel.Error, Message = "Unable to compute the hash of certificate {0}. OpenSSL trust is likely in an inconsistent state.")]
internal void UnixOpenSslHashFailed(string certificatePath) => WriteEvent(82, certificatePath);
// We'll continue on to NSS DB, but leaving the OpenSSL hash files in a bad state is a real problem.
[Event(83, Level = EventLevel.Error, Message = "Unable to compute the certificate hash: {0}. OpenSSL trust is likely in an inconsistent state.")]
internal void UnixOpenSslHashException(string certificatePath, string exceptionMessage) => WriteEvent(83, certificatePath, exceptionMessage);
// We'll continue on to NSS DB, but leaving the OpenSSL hash files in a bad state is a real problem.
[Event(84, Level = EventLevel.Error, Message = "Unable to update certificate '{0}' in the OpenSSL trusted certificate hash collection - {2} certificates have the hash {1}.")]
internal void UnixOpenSslRehashTooManyHashes(string fullName, string hash, int maxHashCollisions) => WriteEvent(84, fullName, hash, maxHashCollisions);
// We'll continue on to NSS DB, but leaving the OpenSSL hash files in a bad state is a real problem.
[Event(85, Level = EventLevel.Error, Message = "Unable to update the OpenSSL trusted certificate hash collection: {0}. " +
"Manually rehashing may help. See https://aka.ms/dev-certs-trust for more information.")] // This should recommend manually running c_rehash.
internal void UnixOpenSslRehashException(string exceptionMessage) => WriteEvent(85, exceptionMessage);
[Event(86, Level = EventLevel.Warning, Message = "Failed to trust the certificate in .NET: {0}.")]
internal void UnixDotnetTrustException(string exceptionMessage) => WriteEvent(86, exceptionMessage);
[Event(87, Level = EventLevel.Verbose, Message = "Trusted the certificate in .NET.")]
internal void UnixDotnetTrustSucceeded() => WriteEvent(87);
[Event(88, Level = EventLevel.Warning, Message = "Clients that validate certificate trust using OpenSSL will not trust the certificate.")]
internal void UnixOpenSslTrustFailed() => WriteEvent(88);
[Event(89, Level = EventLevel.Verbose, Message = "Trusted the certificate in OpenSSL.")]
internal void UnixOpenSslTrustSucceeded() => WriteEvent(89);
[Event(90, Level = EventLevel.Warning, Message = "Failed to trust the certificate in the NSS database in '{0}'. This will likely affect the {1} family of browsers.")]
internal void UnixNssDbTrustFailed(string path, string browser) => WriteEvent(90, path, browser);
[Event(91, Level = EventLevel.Verbose, Message = "Trusted the certificate in the NSS database in '{0}'.")]
internal void UnixNssDbTrustSucceeded(string path) => WriteEvent(91, path);
[Event(92, Level = EventLevel.Warning, Message = "Failed to untrust the certificate in .NET: {0}.")]
internal void UnixDotnetUntrustException(string exceptionMessage) => WriteEvent(92, exceptionMessage);
[Event(93, Level = EventLevel.Warning, Message = "Failed to untrust the certificate in OpenSSL.")]
internal void UnixOpenSslUntrustFailed() => WriteEvent(93);
[Event(94, Level = EventLevel.Verbose, Message = "Untrusted the certificate in OpenSSL.")]
internal void UnixOpenSslUntrustSucceeded() => WriteEvent(94);
[Event(95, Level = EventLevel.Warning, Message = "Failed to remove the certificate from the NSS database in '{0}'.")]
internal void UnixNssDbUntrustFailed(string path) => WriteEvent(95, path);
[Event(96, Level = EventLevel.Verbose, Message = "Removed the certificate from the NSS database in '{0}'.")]
internal void UnixNssDbUntrustSucceeded(string path) => WriteEvent(96, path);
[Event(97, Level = EventLevel.Warning, Message = "The certificate is only partially trusted - some clients will not accept it.")]
internal void UnixTrustPartiallySucceeded() => WriteEvent(97);
[Event(98, Level = EventLevel.Warning, Message = "Failed to look up the certificate in the NSS database in '{0}': {1}.")]
internal void UnixNssDbCheckException(string path, string exceptionMessage) => WriteEvent(98, path, exceptionMessage);
[Event(99, Level = EventLevel.Warning, Message = "Failed to add the certificate to the NSS database in '{0}': {1}.")]
internal void UnixNssDbAdditionException(string path, string exceptionMessage) => WriteEvent(99, path, exceptionMessage);
[Event(100, Level = EventLevel.Warning, Message = "Failed to remove the certificate from the NSS database in '{0}': {1}.")]
internal void UnixNssDbRemovalException(string path, string exceptionMessage) => WriteEvent(100, path, exceptionMessage);
[Event(101, Level = EventLevel.Warning, Message = "Failed to find the Firefox profiles in directory '{0}': {1}.")]
internal void UnixFirefoxProfileEnumerationException(string firefoxDirectory, string message) => WriteEvent(101, firefoxDirectory, message);
[Event(102, Level = EventLevel.Verbose, Message = "No Firefox profiles found in directory '{0}'.")]
internal void UnixNoFirefoxProfilesFound(string firefoxDirectory) => WriteEvent(102, firefoxDirectory);
[Event(103, Level = EventLevel.Warning, Message = "Failed to trust the certificate in the NSS database in '{0}'. This will likely affect the {1} family of browsers. " +
"This likely indicates that the database already contains an entry for the certificate under a different name. Please remove it and try again.")]
internal void UnixNssDbTrustFailedWithProbableConflict(string path, string browser) => WriteEvent(103, path, browser);
// This may be annoying, since anyone setting the variable for un/trust will likely leave it set for --check.
// However, it seems important to warn users who set it specifically for --check.
[Event(104, Level = EventLevel.Warning, Message = "The {0} environment variable is set but will not be consumed while checking trust.")]
internal void UnixOpenSslCertificateDirectoryOverrideIgnored(string openSslCertDirectoryOverrideVariableName) => WriteEvent(104, openSslCertDirectoryOverrideVariableName);
[Event(105, Level = EventLevel.Warning, Message = "The {0} command is unavailable. It is required for updating certificate trust in OpenSSL.")]
internal void UnixMissingOpenSslCommand(string openSslCommand) => WriteEvent(105, openSslCommand);
[Event(106, Level = EventLevel.Warning, Message = "The {0} command is unavailable. It is required for querying and updating NSS databases, which are chiefly used to trust certificates in browsers.")]
internal void UnixMissingCertUtilCommand(string certUtilCommand) => WriteEvent(106, certUtilCommand);
[Event(107, Level = EventLevel.Verbose, Message = "Untrusting the certificate in OpenSSL was skipped since '{0}' does not exist.")]
internal void UnixOpenSslUntrustSkipped(string certPath) => WriteEvent(107, certPath);
[Event(108, Level = EventLevel.Warning, Message = "Failed to delete certificate file '{0}': {1}.")]
internal void UnixCertificateFileDeletionException(string certPath, string exceptionMessage) => WriteEvent(108, certPath, exceptionMessage);
[Event(109, Level = EventLevel.Error, Message = "Unable to export the certificate since '{0}' already exists. Please remove it.")]
internal void UnixNotOverwritingCertificate(string certPath) => WriteEvent(109, certPath);
[Event(110, Level = EventLevel.LogAlways, Message = "For OpenSSL trust to take effect, '{0}' must be listed in the {2} environment variable. " +
"For example, `export SSL_CERT_DIR={0}:{1}`. " +
"See https://aka.ms/dev-certs-trust for more information.")]
internal void UnixSuggestSettingEnvironmentVariable(string certDir, string openSslDir, string envVarName) => WriteEvent(110, certDir, openSslDir, envVarName);
[Event(111, Level = EventLevel.LogAlways, Message = "For OpenSSL trust to take effect, '{0}' must be listed in the {2} environment variable. " +
"See https://aka.ms/dev-certs-trust for more information.")]
internal void UnixSuggestSettingEnvironmentVariableWithoutExample(string certDir, string envVarName) => WriteEvent(111, certDir, envVarName);
[Event(112, Level = EventLevel.Warning, Message = "Directory '{0}' may be readable by other users.")]
internal void DirectoryPermissionsNotSecure(string directoryPath) => WriteEvent(112, directoryPath);
}
| CertificateManagerEventSource |
csharp | files-community__Files | src/Files.App/UserControls/FilePreviews/CodePreview.xaml.cs | {
"start": 250,
"end": 1059
} | partial class ____ : UserControl
{
private RichTextBlockFormatter formatter;
private CodePreviewViewModel ViewModel { get; set; }
public CodePreview(CodePreviewViewModel model)
{
ViewModel = model;
InitializeComponent();
}
private void RenderDocument()
{
if (codeView is not null)
{
codeView.Blocks?.Clear();
formatter = new RichTextBlockFormatter(ActualTheme);
formatter.FormatRichTextBlock(ViewModel.TextValue, ViewModel.CodeLanguage, codeView);
}
}
private void UserControl_Loaded(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
{
RenderDocument();
}
private void UserControl_ActualThemeChanged(Microsoft.UI.Xaml.FrameworkElement sender, object args)
{
try
{
RenderDocument();
}
catch (Exception)
{
}
}
}
} | CodePreview |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Fusion-vnext/test/Fusion.AspNetCore.Tests/AnyScalarTests.cs | {
"start": 6215,
"end": 9246
} | public class ____
{
[GraphQLType<AnyType>]
public Dictionary<string, object?> GetObject()
=> new() { { "abc", "def" } };
[GraphQLType<AnyType>]
public Dictionary<string, object?> GetSimpleValues()
=> new()
{
{ "string", "hello" },
{ "int", 42 },
{ "double", 3.14 },
{ "bool", true },
{ "null", null }
};
[GraphQLType<AnyType>]
public List<object?> GetList()
=> ["string", 123, true, 45.67, null];
[GraphQLType<AnyType>]
public Dictionary<string, object?> GetNestedObject()
=> new()
{
{ "name", "test" },
{
"address", new Dictionary<string, object?>
{
{ "street", "Main St" },
{ "number", 123 },
{ "city", "Springfield" }
}
}
};
[GraphQLType<AnyType>]
public List<object?> GetListOfObjects()
=>
[
new Dictionary<string, object?> { { "id", 1 }, { "name", "Alice" } },
new Dictionary<string, object?> { { "id", 2 }, { "name", "Bob" } },
new Dictionary<string, object?> { { "id", 3 }, { "name", "Charlie" } }
];
[GraphQLType<AnyType>]
public Dictionary<string, object?> GetObjectWithLists()
=> new()
{
{ "name", "Product" },
{ "tags", new List<object?> { "electronics", "gadget", "popular" } },
{ "prices", new List<object?> { 99.99, 89.99, 79.99 } }
};
[GraphQLType<AnyType>]
public Dictionary<string, object?> GetComplexNested()
=> new()
{
{ "id", 1 },
{ "name", "Root" },
{
"children", new List<object?>
{
new Dictionary<string, object?>
{
{ "id", 2 },
{ "name", "Child1" },
{ "values", new List<object?> { 1, 2, 3 } }
},
new Dictionary<string, object?>
{
{ "id", 3 },
{ "name", "Child2" },
{
"metadata", new Dictionary<string, object?>
{
{ "created", "2024-01-01" },
{ "tags", new List<object?> { "tag1", "tag2" } }
}
}
}
}
}
};
[GraphQLType<AnyType>]
public object? GetNullValue() => null;
}
}
| Query |
csharp | Cysharp__UniTask | src/UniTask/Assets/Plugins/UniTask/Runtime/Internal/WeakDictionary.cs | {
"start": 8789,
"end": 9620
} | class ____
{
public WeakReference<TKey> Key;
public TValue Value;
public int Hash;
public Entry Prev;
public Entry Next;
// debug only
public override string ToString()
{
if (Key.TryGetTarget(out var target))
{
return target + "(" + Count() + ")";
}
else
{
return "(Dead)";
}
}
int Count()
{
var count = 1;
var n = this;
while (n.Next != null)
{
count++;
n = n.Next;
}
return count;
}
}
}
}
| Entry |
csharp | NSubstitute__NSubstitute | tests/NSubstitute.Acceptance.Specs/PartialSubExamples.cs | {
"start": 1462,
"end": 2070
} | public class ____
{
public virtual int Read()
{
var s = ReadFile();
return s.Split(',').Select(int.Parse).Sum();
}
public virtual string ReadFile() { return "the result of reading the file here"; }
}
[Test]
public void ShouldSumAllNumbersInFile()
{
var reader = Substitute.ForPartsOf<SummingReader>();
reader.ReadFile().Returns("1,2,3,4,5");
var result = reader.Read();
Assert.That(result, Is.EqualTo(15));
}
}
| SummingReader |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Phone.Media.Devices/AudioRoutingManager.cs | {
"start": 302,
"end": 4445
} | public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal AudioRoutingManager()
{
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Phone.Media.Devices.AvailableAudioRoutingEndpoints AvailableAudioEndpoints
{
get
{
throw new global::System.NotImplementedException("The member AvailableAudioRoutingEndpoints AudioRoutingManager.AvailableAudioEndpoints is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=AvailableAudioRoutingEndpoints%20AudioRoutingManager.AvailableAudioEndpoints");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Phone.Media.Devices.AudioRoutingEndpoint GetAudioEndpoint()
{
throw new global::System.NotImplementedException("The member AudioRoutingEndpoint AudioRoutingManager.GetAudioEndpoint() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=AudioRoutingEndpoint%20AudioRoutingManager.GetAudioEndpoint%28%29");
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public void SetAudioEndpoint(global::Windows.Phone.Media.Devices.AudioRoutingEndpoint endpoint)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Phone.Media.Devices.AudioRoutingManager", "void AudioRoutingManager.SetAudioEndpoint(AudioRoutingEndpoint endpoint)");
}
#endif
// Forced skipping of method Windows.Phone.Media.Devices.AudioRoutingManager.AudioEndpointChanged.add
// Forced skipping of method Windows.Phone.Media.Devices.AudioRoutingManager.AudioEndpointChanged.remove
// Forced skipping of method Windows.Phone.Media.Devices.AudioRoutingManager.AvailableAudioEndpoints.get
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public static global::Windows.Phone.Media.Devices.AudioRoutingManager GetDefault()
{
throw new global::System.NotImplementedException("The member AudioRoutingManager AudioRoutingManager.GetDefault() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=AudioRoutingManager%20AudioRoutingManager.GetDefault%28%29");
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.Phone.Media.Devices.AudioRoutingManager, object> AudioEndpointChanged
{
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Phone.Media.Devices.AudioRoutingManager", "event TypedEventHandler<AudioRoutingManager, object> AudioRoutingManager.AudioEndpointChanged");
}
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Phone.Media.Devices.AudioRoutingManager", "event TypedEventHandler<AudioRoutingManager, object> AudioRoutingManager.AudioEndpointChanged");
}
}
#endif
}
}
| AudioRoutingManager |
csharp | MassTransit__MassTransit | src/MassTransit/SagaStateMachine/ThenExtensions.cs | {
"start": 110,
"end": 12504
} | public static class ____
{
/// <summary>
/// Adds a synchronous delegate activity to the event's behavior
/// </summary>
/// <typeparam name="TSaga">The state machine instance type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="action">The synchronous delegate</param>
public static EventActivityBinder<TSaga> Then<TSaga>(this EventActivityBinder<TSaga> binder, Action<BehaviorContext<TSaga>> action)
where TSaga : class, SagaStateMachineInstance
{
return binder.Add(new ActionActivity<TSaga>(action));
}
/// <summary>
/// Adds a synchronous delegate activity to the event's behavior
/// </summary>
/// <typeparam name="TSaga">The state machine instance type</typeparam>
/// <typeparam name="TException">The exception type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="action">The synchronous delegate</param>
public static ExceptionActivityBinder<TSaga, TException> Then<TSaga, TException>(this ExceptionActivityBinder<TSaga, TException> binder,
Action<BehaviorExceptionContext<TSaga, TException>> action)
where TSaga : class, SagaStateMachineInstance
where TException : Exception
{
return binder.Add(new FaultedActionActivity<TSaga, TException>(action));
}
/// <summary>
/// Adds a asynchronous delegate activity to the event's behavior
/// </summary>
/// <typeparam name="TSaga">The state machine instance type</typeparam>
/// <typeparam name="TException">The exception type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="asyncAction">The asynchronous delegate</param>
public static ExceptionActivityBinder<TSaga, TException> ThenAsync<TSaga, TException>(this ExceptionActivityBinder<TSaga, TException> binder,
Func<BehaviorExceptionContext<TSaga, TException>, Task> asyncAction)
where TSaga : class, SagaStateMachineInstance
where TException : Exception
{
return binder.Add(new AsyncFaultedActionActivity<TSaga, TException>(asyncAction));
}
/// <summary>
/// Adds an asynchronous delegate activity to the event's behavior
/// </summary>
/// <typeparam name="TSaga">The state machine instance type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="action">The asynchronous delegate</param>
public static EventActivityBinder<TSaga> ThenAsync<TSaga>(this EventActivityBinder<TSaga> binder, Func<BehaviorContext<TSaga>, Task> action)
where TSaga : class, SagaStateMachineInstance
{
return binder.Add(new AsyncActivity<TSaga>(action));
}
/// <summary>
/// Adds a synchronous delegate activity to the event's behavior
/// </summary>
/// <typeparam name="TSaga">The state machine instance type</typeparam>
/// <typeparam name="TData">The event data type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="action">The synchronous delegate</param>
public static EventActivityBinder<TSaga, TData> Then<TSaga, TData>(this EventActivityBinder<TSaga, TData> binder,
Action<BehaviorContext<TSaga, TData>> action)
where TSaga : class, SagaStateMachineInstance
where TData : class
{
return binder.Add(new ActionActivity<TSaga, TData>(action));
}
/// <summary>
/// Adds a synchronous delegate activity to the event's behavior
/// </summary>
/// <typeparam name="TSaga">The state machine instance type</typeparam>
/// <typeparam name="TException">The exception type</typeparam>
/// <typeparam name="TData">The event data type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="action">The synchronous delegate</param>
public static ExceptionActivityBinder<TSaga, TData, TException> Then<TSaga, TData, TException>(
this ExceptionActivityBinder<TSaga, TData, TException> binder,
Action<BehaviorExceptionContext<TSaga, TData, TException>> action)
where TSaga : class, SagaStateMachineInstance
where TException : Exception
where TData : class
{
return binder.Add(new FaultedActionActivity<TSaga, TData, TException>(action));
}
/// <summary>
/// Adds a asynchronous delegate activity to the event's behavior
/// </summary>
/// <typeparam name="TSaga">The state machine instance type</typeparam>
/// <typeparam name="TException">The exception type</typeparam>
/// <typeparam name="TData">The event data type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="asyncAction">The asynchronous delegate</param>
public static ExceptionActivityBinder<TSaga, TData, TException> ThenAsync<TSaga, TData, TException>(
this ExceptionActivityBinder<TSaga, TData, TException> binder,
Func<BehaviorExceptionContext<TSaga, TData, TException>, Task> asyncAction)
where TSaga : class, SagaStateMachineInstance
where TException : Exception
where TData : class
{
return binder.Add(new AsyncFaultedActionActivity<TSaga, TData, TException>(asyncAction));
}
/// <summary>
/// Adds an asynchronous delegate activity to the event's behavior
/// </summary>
/// <typeparam name="TSaga">The state machine instance type</typeparam>
/// <typeparam name="TData">The event data type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="action">The asynchronous delegate</param>
public static EventActivityBinder<TSaga, TData> ThenAsync<TSaga, TData>(this EventActivityBinder<TSaga, TData> binder,
Func<BehaviorContext<TSaga, TData>, Task> action)
where TSaga : class, SagaStateMachineInstance
where TData : class
{
return binder.Add(new AsyncActivity<TSaga, TData>(action));
}
/// <summary>
/// Add an activity execution to the event's behavior
/// </summary>
/// <typeparam name="TSaga">The state machine instance type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="activityFactory">The factory method which returns the activity to execute</param>
public static EventActivityBinder<TSaga> Execute<TSaga>(this EventActivityBinder<TSaga> binder,
Func<BehaviorContext<TSaga>, IStateMachineActivity<TSaga>> activityFactory)
where TSaga : class, SagaStateMachineInstance
{
var activity = new FactoryActivity<TSaga>(activityFactory);
return binder.Add(activity);
}
/// <summary>
/// Add an activity execution to the event's behavior
/// </summary>
/// <typeparam name="TSaga">The state machine instance type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="activity">An existing activity</param>
public static EventActivityBinder<TSaga> Execute<TSaga>(this EventActivityBinder<TSaga> binder, IStateMachineActivity<TSaga> activity)
where TSaga : class, SagaStateMachineInstance
{
return binder.Add(activity);
}
/// <summary>
/// Add an activity execution to the event's behavior
/// </summary>
/// <typeparam name="TSaga">The state machine instance type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="activityFactory">The factory method which returns the activity to execute</param>
public static EventActivityBinder<TSaga> ExecuteAsync<TSaga>(this EventActivityBinder<TSaga> binder,
Func<BehaviorContext<TSaga>, Task<IStateMachineActivity<TSaga>>> activityFactory)
where TSaga : class, SagaStateMachineInstance
{
var activity = new AsyncFactoryActivity<TSaga>(activityFactory);
return binder.Add(activity);
}
/// <summary>
/// Add an activity execution to the event's behavior
/// </summary>
/// <typeparam name="TSaga">The state machine instance type</typeparam>
/// <typeparam name="TData">The event data type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="activityFactory">The factory method which returns the activity to execute</param>
public static EventActivityBinder<TSaga, TData> Execute<TSaga, TData>(this EventActivityBinder<TSaga, TData> binder,
Func<BehaviorContext<TSaga, TData>, IStateMachineActivity<TSaga, TData>> activityFactory)
where TSaga : class, SagaStateMachineInstance
where TData : class
{
var activity = new FactoryActivity<TSaga, TData>(activityFactory);
return binder.Add(activity);
}
/// <summary>
/// Add an activity execution to the event's behavior
/// </summary>
/// <typeparam name="TSaga">The state machine instance type</typeparam>
/// <typeparam name="TData">The event data type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="activityFactory">The factory method which returns the activity to execute</param>
public static EventActivityBinder<TSaga, TData> ExecuteAsync<TSaga, TData>(this EventActivityBinder<TSaga, TData> binder,
Func<BehaviorContext<TSaga, TData>, Task<IStateMachineActivity<TSaga, TData>>> activityFactory)
where TSaga : class, SagaStateMachineInstance
where TData : class
{
var activity = new AsyncFactoryActivity<TSaga, TData>(activityFactory);
return binder.Add(activity);
}
/// <summary>
/// Add an activity execution to the event's behavior
/// </summary>
/// <typeparam name="TSaga">The state machine instance type</typeparam>
/// <typeparam name="TData">The event data type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="activityFactory">The factory method which returns the activity to execute</param>
public static EventActivityBinder<TSaga, TData> Execute<TSaga, TData>(this EventActivityBinder<TSaga, TData> binder,
Func<BehaviorContext<TSaga, TData>, IStateMachineActivity<TSaga>> activityFactory)
where TSaga : class, SagaStateMachineInstance
where TData : class
{
var activity = new FactoryActivity<TSaga, TData>(context =>
{
IStateMachineActivity<TSaga> newActivity = activityFactory(context);
return new SlimActivity<TSaga, TData>(newActivity);
});
return binder.Add(activity);
}
/// <summary>
/// Add an activity execution to the event's behavior
/// </summary>
/// <typeparam name="TSaga">The state machine instance type</typeparam>
/// <typeparam name="TData">The event data type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="activityFactory">The factory method which returns the activity to execute</param>
public static EventActivityBinder<TSaga, TData> ExecuteAsync<TSaga, TData>(this EventActivityBinder<TSaga, TData> binder,
Func<BehaviorContext<TSaga, TData>, Task<IStateMachineActivity<TSaga>>> activityFactory)
where TSaga : class, SagaStateMachineInstance
where TData : class
{
var activity = new AsyncFactoryActivity<TSaga, TData>(async context =>
{
IStateMachineActivity<TSaga> newActivity = await activityFactory(context).ConfigureAwait(false);
return new SlimActivity<TSaga, TData>(newActivity);
});
return binder.Add(activity);
}
}
}
| ThenExtensions |
csharp | MassTransit__MassTransit | src/Persistence/MassTransit.EntityFrameworkCoreIntegration/EntityFrameworkCoreIntegration/ISagaDbContextFactory.cs | {
"start": 225,
"end": 1020
} | public interface ____<out TSaga>
where TSaga : class, ISaga
{
/// <summary>
/// Create a standalone DbContext
/// </summary>
/// <returns></returns>
DbContext Create();
/// <summary>
/// Create a scoped DbContext within the lifetime scope of the saga repository
/// </summary>
/// <param name="context"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
DbContext CreateScoped<T>(ConsumeContext<T> context)
where T : class;
/// <summary>
/// Release the DbContext once it is no longer needed
/// </summary>
/// <param name="dbContext"></param>
ValueTask ReleaseAsync(DbContext dbContext);
}
}
| ISagaDbContextFactory |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Fusion-vnext/test/Fusion.Composition.Tests/PostMergeValidationRules/InterfaceFieldNoImplementationRuleTests.cs | {
"start": 57,
"end": 258
} | public sealed class ____ : RuleTestBase
{
protected override object Rule { get; } = new InterfaceFieldNoImplementationRule();
// In this example, the "User" | InterfaceFieldNoImplementationRuleTests |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/HttpResultContentTypeTests.cs | {
"start": 1289,
"end": 1654
} | public class ____
{
/// <summary>
/// Controls if the service calls response.ContentType or just new HttpResult
/// </summary>
public bool SetContentType { get; set; }
/// <summary>
/// Text to respond with
/// </summary>
public string Text { get; set; }
}
[Route("/plain-dto")]
| PlainText |
csharp | dotnet__tye | test/E2ETest/TyeBuildTests.Dockerfile.cs | {
"start": 466,
"end": 12153
} | public partial class ____
{
[ConditionalFact]
[SkipIfDockerNotRunning]
public async Task TyeBuild_SinglePhase_GeneratedDockerfile()
{
var projectName = "single-phase-dockerfile";
var environment = "production";
var imageName = "test/single-phase-dockerfile";
await DockerAssert.DeleteDockerImagesAsync(output, imageName);
using var projectDirectory = CopyTestProjectDirectory(projectName);
File.Delete(Path.Combine(projectDirectory.DirectoryPath, "Dockerfile"));
Assert.False(File.Exists(Path.Combine(projectDirectory.DirectoryPath, "Dockerfile")), "Dockerfile should be gone.");
var projectFile = new FileInfo(Path.Combine(projectDirectory.DirectoryPath, "tye.yaml"));
var outputContext = new OutputContext(sink, Verbosity.Debug);
var application = await ApplicationFactory.CreateAsync(outputContext, projectFile);
application.Registry = new ContainerRegistry("test", null);
try
{
await BuildHost.ExecuteBuildAsync(outputContext, application, environment, interactive: false);
var publishOutput = Assert.Single(application.Services.Single().Outputs.OfType<ProjectPublishOutput>());
Assert.False(Directory.Exists(publishOutput.Directory.FullName), $"Directory {publishOutput.Directory.FullName} should be deleted.");
await DockerAssert.AssertImageExistsAsync(output, imageName);
}
finally
{
await DockerAssert.DeleteDockerImagesAsync(output, imageName);
}
}
[ConditionalFact]
[SkipIfDockerNotRunning]
public async Task TyeBuild_SinglePhase_ExistingDockerfile()
{
var projectName = "single-phase-dockerfile";
var environment = "production";
var imageName = "test/single-phase-dockerfile";
await DockerAssert.DeleteDockerImagesAsync(output, imageName);
using var projectDirectory = CopyTestProjectDirectory(projectName);
Assert.True(File.Exists(Path.Combine(projectDirectory.DirectoryPath, "Dockerfile")), "Dockerfile should exist.");
var projectFile = new FileInfo(Path.Combine(projectDirectory.DirectoryPath, "tye.yaml"));
var outputContext = new OutputContext(sink, Verbosity.Debug);
var application = await ApplicationFactory.CreateAsync(outputContext, projectFile);
application.Registry = new ContainerRegistry("test", null);
try
{
await BuildHost.ExecuteBuildAsync(outputContext, application, environment, interactive: false);
var publishOutput = Assert.Single(application.Services.Single().Outputs.OfType<ProjectPublishOutput>());
Assert.False(Directory.Exists(publishOutput.Directory.FullName), $"Directory {publishOutput.Directory.FullName} should be deleted.");
await DockerAssert.AssertImageExistsAsync(output, imageName);
}
finally
{
await DockerAssert.DeleteDockerImagesAsync(output, imageName);
}
}
[ConditionalFact]
[SkipIfDockerNotRunning]
public async Task TyeBuild_SinglePhase_ExistingDockerfileWithBuildArgs()
{
var projectName = "single-phase-dockerfile-args";
var environment = "production";
var imageName = "test/web";
await DockerAssert.DeleteDockerImagesAsync(output, imageName);
using var projectDirectory = CopyTestProjectDirectory(projectName);
Assert.True(File.Exists(Path.Combine(projectDirectory.DirectoryPath, "Dockerfile")), "Dockerfile should exist.");
var projectFile = new FileInfo(Path.Combine(projectDirectory.DirectoryPath, "tye.yaml"));
var outputContext = new OutputContext(sink, Verbosity.Debug);
var application = await ApplicationFactory.CreateAsync(outputContext, projectFile);
application.Registry = new ContainerRegistry("test", null);
try
{
await BuildHost.ExecuteBuildAsync(outputContext, application, environment, interactive: false);
Assert.Single(application.Services.Single().Outputs.OfType<DockerImageOutput>());
var builder = (DockerFileServiceBuilder)application.Services.First();
var valuePair = builder.BuildArgs.First();
Assert.Equal("pat", valuePair.Key);
Assert.Equal("thisisapat", valuePair.Value);
await DockerAssert.AssertImageExistsAsync(output, imageName);
}
finally
{
await DockerAssert.DeleteDockerImagesAsync(output, imageName);
}
}
[ConditionalFact]
[SkipIfDockerNotRunning]
public async Task TyeBuild_SinglePhase_ExistingDockerfileWithBuildArgsDuplicateArgs()
{
var projectName = "single-phase-dockerfile-args";
var environment = "production";
var imageName = "test/web";
await DockerAssert.DeleteDockerImagesAsync(output, imageName);
using var projectDirectory = CopyTestProjectDirectory(projectName);
Assert.True(File.Exists(Path.Combine(projectDirectory.DirectoryPath, "Dockerfile")), "Dockerfile should exist.");
var projectFile = new FileInfo(Path.Combine(projectDirectory.DirectoryPath, "tye.yaml"));
var outputContext = new OutputContext(sink, Verbosity.Debug);
var application = await ApplicationFactory.CreateAsync(outputContext, projectFile);
application.Registry = new ContainerRegistry("test", null);
try
{
await BuildHost.ExecuteBuildAsync(outputContext, application, environment, interactive: false);
Assert.Single(application.Services.Single().Outputs.OfType<DockerImageOutput>());
var builder = (DockerFileServiceBuilder)application.Services.First();
var valuePair = builder.BuildArgs.First();
Assert.Equal("pat", valuePair.Key);
Assert.Equal("thisisapat", valuePair.Value);
await DockerAssert.AssertImageExistsAsync(output, imageName);
}
finally
{
await DockerAssert.DeleteDockerImagesAsync(output, imageName);
}
}
[ConditionalFact]
[SkipIfDockerNotRunning]
public async Task TyeBuild_SinglePhase_ExistingDockerfileWithBuildArgsMultiArgs()
{
var projectName = "single-phase-dockerfile-multi-args";
var environment = "production";
var imageName = "test/web";
await DockerAssert.DeleteDockerImagesAsync(output, imageName);
using var projectDirectory = CopyTestProjectDirectory(projectName);
Assert.True(File.Exists(Path.Combine(projectDirectory.DirectoryPath, "Dockerfile")), "Dockerfile should exist.");
var projectFile = new FileInfo(Path.Combine(projectDirectory.DirectoryPath, "tye.yaml"));
var outputContext = new OutputContext(sink, Verbosity.Debug);
var application = await ApplicationFactory.CreateAsync(outputContext, projectFile);
application.Registry = new ContainerRegistry("test", null);
try
{
await BuildHost.ExecuteBuildAsync(outputContext, application, environment, interactive: false);
Assert.Single(application.Services.Single().Outputs.OfType<DockerImageOutput>());
var builder = (DockerFileServiceBuilder)application.Services.First();
var valuePair = builder.BuildArgs.ElementAt(0);
Assert.Equal(3, builder.BuildArgs.Count);
Assert.Equal("pat", valuePair.Key);
Assert.Equal("thisisapat", valuePair.Value);
valuePair = builder.BuildArgs.ElementAt(1);
Assert.Equal("number_of_replicas", valuePair.Key);
Assert.Equal("2", valuePair.Value);
valuePair = builder.BuildArgs.ElementAt(2);
Assert.Equal("number_of_shards", valuePair.Key);
Assert.Equal("5", valuePair.Value);
await DockerAssert.AssertImageExistsAsync(output, imageName);
}
finally
{
await DockerAssert.DeleteDockerImagesAsync(output, imageName);
}
}
[ConditionalFact]
[SkipIfDockerNotRunning]
public async Task TyeBuild_MultipleTargetFrameworks_CliArgs()
{
var projectName = "multi-targetframeworks";
var environment = "production";
var imageName = "test/multi-targetframeworks";
await DockerAssert.DeleteDockerImagesAsync(output, imageName);
using var projectDirectory = CopyTestProjectDirectory(projectName);
var projectFile = new FileInfo(Path.Combine(projectDirectory.DirectoryPath, "tye-no-buildproperties.yaml"));
var outputContext = new OutputContext(sink, Verbosity.Debug);
var application = await ApplicationFactory.CreateAsync(outputContext, projectFile, "netcoreapp3.1");
application.Registry = new ContainerRegistry("test", null);
try
{
await BuildHost.ExecuteBuildAsync(outputContext, application, environment, interactive: false);
var publishOutput = Assert.Single(application.Services.Single().Outputs.OfType<ProjectPublishOutput>());
Assert.False(Directory.Exists(publishOutput.Directory.FullName), $"Directory {publishOutput.Directory.FullName} should be deleted.");
await DockerAssert.AssertImageExistsAsync(output, imageName);
}
finally
{
await DockerAssert.DeleteDockerImagesAsync(output, imageName);
}
}
[ConditionalFact]
[SkipIfDockerNotRunning]
public async Task TyeBuild_MultipleTargetFrameworks_YamlBuildProperties()
{
var projectName = "multi-targetframeworks";
var environment = "production";
var imageName = "test/multi-targetframeworks";
await DockerAssert.DeleteDockerImagesAsync(output, imageName);
using var projectDirectory = CopyTestProjectDirectory(projectName);
var projectFile = new FileInfo(Path.Combine(projectDirectory.DirectoryPath, "tye-with-netcoreapp31.yaml"));
var outputContext = new OutputContext(sink, Verbosity.Debug);
var application = await ApplicationFactory.CreateAsync(outputContext, projectFile, "netcoreapp3.1");
application.Registry = new ContainerRegistry("test", null);
try
{
await BuildHost.ExecuteBuildAsync(outputContext, application, environment, interactive: false);
var publishOutput = Assert.Single(application.Services.Single().Outputs.OfType<ProjectPublishOutput>());
Assert.False(Directory.Exists(publishOutput.Directory.FullName), $"Directory {publishOutput.Directory.FullName} should be deleted.");
await DockerAssert.AssertImageExistsAsync(output, imageName);
}
finally
{
await DockerAssert.DeleteDockerImagesAsync(output, imageName);
}
}
}
}
| TyeBuildTests |
csharp | dotnet__aspire | src/Aspire.Hosting.Kubernetes/Resources/DeploymentV1.cs | {
"start": 390,
"end": 741
} | sealed class ____ from the BaseKubernetesResource. It defines the
/// desired state and behavior of a deployment within a Kubernetes cluster, including specifications
/// such as the number of replicas, update strategy, and pod templates.
/// It uses the "apps/v1" API version and the resource kind "Deployment".
/// </remarks>
[YamlSerializable]
| derived |
csharp | SixLabors__ImageSharp | src/ImageSharp/PixelFormats/PixelImplementations/PixelOperations/NormalizedShort2.PixelOperations.cs | {
"start": 347,
"end": 417
} | internal class ____ : PixelOperations<NormalizedShort2>;
}
| PixelOperations |
csharp | CommunityToolkit__WindowsCommunityToolkit | Microsoft.Toolkit.Uwp.UI.Controls.Markdown/Parsers/Markdown/Inlines/BoldTextInline.cs | {
"start": 532,
"end": 3866
} | public class ____ : MarkdownInline, IInlineContainer
{
/// <summary>
/// Initializes a new instance of the <see cref="BoldTextInline"/> class.
/// </summary>
public BoldTextInline()
: base(MarkdownInlineType.Bold)
{
}
/// <summary>
/// Gets or sets the contents of the inline.
/// </summary>
public IList<MarkdownInline> Inlines { get; set; }
/// <summary>
/// Returns the chars that if found means we might have a match.
/// </summary>
internal static void AddTripChars(List<InlineTripCharHelper> tripCharHelpers)
{
tripCharHelpers.Add(new InlineTripCharHelper() { FirstChar = '*', Method = InlineParseMethod.Bold });
tripCharHelpers.Add(new InlineTripCharHelper() { FirstChar = '_', Method = InlineParseMethod.Bold });
}
/// <summary>
/// Attempts to parse a bold text span.
/// </summary>
/// <param name="markdown"> The markdown text. </param>
/// <param name="start"> The location to start parsing. </param>
/// <param name="maxEnd"> The location to stop parsing. </param>
/// <returns> A parsed bold text span, or <c>null</c> if this is not a bold text span. </returns>
internal static InlineParseResult Parse(string markdown, int start, int maxEnd)
{
if (start >= maxEnd - 1)
{
return null;
}
// Check the start sequence.
string startSequence = markdown.Substring(start, 2);
if (startSequence != "**" && startSequence != "__")
{
return null;
}
// Find the end of the span. The end sequence (either '**' or '__') must be the same
// as the start sequence.
var innerStart = start + 2;
int innerEnd = Common.IndexOf(markdown, startSequence, innerStart, maxEnd);
if (innerEnd == -1)
{
return null;
}
// The span must contain at least one character.
if (innerStart == innerEnd)
{
return null;
}
// The first character inside the span must NOT be a space.
if (ParseHelpers.IsMarkdownWhiteSpace(markdown[innerStart]))
{
return null;
}
// The last character inside the span must NOT be a space.
if (ParseHelpers.IsMarkdownWhiteSpace(markdown[innerEnd - 1]))
{
return null;
}
// We found something!
var result = new BoldTextInline();
result.Inlines = Common.ParseInlineChildren(markdown, innerStart, innerEnd);
return new InlineParseResult(result, start, innerEnd + 2);
}
/// <summary>
/// Converts the object into it's textual representation.
/// </summary>
/// <returns> The textual representation of this object. </returns>
public override string ToString()
{
if (Inlines == null)
{
return base.ToString();
}
return "**" + string.Join(string.Empty, Inlines) + "**";
}
}
} | BoldTextInline |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/CheckWebCore/ContactServices.cs | {
"start": 4008,
"end": 4290
} | public enum ____
{
Action,
Adventure,
Comedy,
Drama,
}
}
}
namespace ServiceInterface
{
using ServiceModel;
using ServiceModel.Types;
| FilmGenres |
csharp | jellyfin__jellyfin | MediaBrowser.Controller/QuickConnect/IQuickConnect.cs | {
"start": 297,
"end": 1856
} | public interface ____
{
/// <summary>
/// Gets a value indicating whether quick connect is enabled or not.
/// </summary>
bool IsEnabled { get; }
/// <summary>
/// Initiates a new quick connect request.
/// </summary>
/// <param name="authorizationInfo">The initiator authorization info.</param>
/// <returns>A quick connect result with tokens to proceed or throws an exception if not active.</returns>
QuickConnectResult TryConnect(AuthorizationInfo authorizationInfo);
/// <summary>
/// Checks the status of an individual request.
/// </summary>
/// <param name="secret">Unique secret identifier of the request.</param>
/// <returns>Quick connect result.</returns>
QuickConnectResult CheckRequestStatus(string secret);
/// <summary>
/// Authorizes a quick connect request to connect as the calling user.
/// </summary>
/// <param name="userId">User id.</param>
/// <param name="code">Identifying code for the request.</param>
/// <returns>A boolean indicating if the authorization completed successfully.</returns>
Task<bool> AuthorizeRequest(Guid userId, string code);
/// <summary>
/// Gets the authorized request for the secret.
/// </summary>
/// <param name="secret">The secret.</param>
/// <returns>The authentication result.</returns>
AuthenticationResult GetAuthorizedRequest(string secret);
}
}
| IQuickConnect |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.