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
|
microsoft__PowerToys
|
src/modules/launcher/Plugins/Community.PowerToys.Run.Plugin.ValueGenerator/Helper/QueryHelper.cs
|
{
"start": 468,
"end": 7938
}
|
internal static class ____
{
/// <summary>
/// a list of all value generator descriptions
/// </summary>
private static readonly string GeneratorDescriptionUuid = Resources.generator_description_uuid;
private static readonly string GeneratorDescriptionUuidv1 = Resources.generator_description_uuidv1;
private static readonly string GeneratorDescriptionUuidv3 = Resources.generator_description_uuidv3;
private static readonly string GeneratorDescriptionUuidv4 = Resources.generator_description_uuidv4;
private static readonly string GeneratorDescriptionUuidv5 = Resources.generator_description_uuidv5;
private static readonly string GeneratorDescriptionUuidv7 = Resources.generator_description_uuidv7;
private static readonly string GeneratorDescriptionHash = Resources.generator_description_hash;
private static readonly string GeneratorDescriptionBase64 = Resources.generator_description_base64;
private static readonly string GeneratorDescriptionBase64d = Resources.generator_description_base64d;
private static readonly string GeneratorDescriptionUrl = Resources.generator_description_url;
private static readonly string GeneratorDescriptionUrld = Resources.generator_description_urld;
private static readonly string GeneratorDescriptionEscData = Resources.generator_description_esc_data;
private static readonly string GeneratorDescriptionUescData = Resources.generator_description_uesc_data;
private static readonly string GeneratorDescriptionEscHex = Resources.generator_description_esc_hex;
private static readonly string GeneratorDescriptionUescHex = Resources.generator_description_uesc_hex;
private static readonly string GeneratorDescriptionYourInput = Resources.generator_description_your_input;
private static readonly string GeneratorExample = Resources.generator_example;
private static readonly string Or = Resources.or;
private static string GetStringFormat(string value, string arg)
{
return string.Format(CultureInfo.CurrentCulture, value, arg);
}
private static string GetStringFormat(string value)
{
return string.Format(CultureInfo.CurrentCulture, value);
}
internal static string GetResultTitle(GeneratorData generatorData)
{
return $"{generatorData.Keyword} - {generatorData.Description}";
}
internal static string GetResultSubtitle(GeneratorData generatorData)
{
return GetStringFormat(GeneratorExample, generatorData.Example);
}
/// <summary>
/// A list that contain all of the value generators and its descriptions
/// </summary>
internal static readonly List<GeneratorData> GeneratorDataList =
[
new()
{
Keyword = "uuid",
Description = GetStringFormat(GeneratorDescriptionUuid),
Example = $"uuid {GetStringFormat(Or)} guid",
},
new()
{
Keyword = "uuidv1",
Description = GetStringFormat(GeneratorDescriptionUuidv1),
Example = $"uuidv1 {GetStringFormat(Or)} uuid1",
},
new()
{
Keyword = "uuidv3",
Description = GetStringFormat(GeneratorDescriptionUuidv3),
Example = $"uuidv3 ns:<DNS, URL, OID, {GetStringFormat(Or)} X500> <{GetStringFormat(GeneratorDescriptionYourInput)}>",
},
new()
{
Keyword = "uuidv4",
Description = GetStringFormat(GeneratorDescriptionUuidv4),
Example = $"uuidv4 {GetStringFormat(Or)} uuid4",
},
new()
{
Keyword = "uuidv5",
Description = GetStringFormat(GeneratorDescriptionUuidv5),
Example = $"uuidv5 ns:<DNS, URL, OID, {GetStringFormat(Or)} X500> <{GetStringFormat(GeneratorDescriptionYourInput)}>",
},
new()
{
Keyword = "uuidv7",
Description = GetStringFormat(GeneratorDescriptionUuidv7),
Example = $"uuidv7 {GetStringFormat(Or)} uuid7",
},
new()
{
Keyword = "md5",
Description = GetStringFormat(GeneratorDescriptionHash, "MD5"),
Example = $"md5 <{GetStringFormat(GeneratorDescriptionYourInput)}>",
},
new()
{
Keyword = "sha1",
Description = GetStringFormat(GeneratorDescriptionHash, "SHA1"),
Example = $"sha1 <{GetStringFormat(GeneratorDescriptionYourInput)}>",
},
new()
{
Keyword = "sha256",
Description = GetStringFormat(GeneratorDescriptionHash, "SHA256"),
Example = $"sha256 <{GetStringFormat(GeneratorDescriptionYourInput)}>",
},
new()
{
Keyword = "sha384",
Description = GetStringFormat(GeneratorDescriptionHash, "SHA384"),
Example = $"sha384 <{GetStringFormat(GeneratorDescriptionYourInput)}>",
},
new()
{
Keyword = "sha512",
Description = GetStringFormat(GeneratorDescriptionHash, "SHA512"),
Example = $"sha512 <{GetStringFormat(GeneratorDescriptionYourInput)}>",
},
new()
{
Keyword = "base64",
Description = GetStringFormat(GeneratorDescriptionBase64),
Example = $"base64 <{GetStringFormat(GeneratorDescriptionYourInput)}>",
},
new()
{
Keyword = "base64d",
Description = GetStringFormat(GeneratorDescriptionBase64d),
Example = $"base64d <{GetStringFormat(GeneratorDescriptionYourInput)}>",
},
new()
{
Keyword = "url",
Description = GetStringFormat(GeneratorDescriptionUrl),
Example = "url https://bing.com/?q=My Test query",
},
new()
{
Keyword = "urld",
Description = GetStringFormat(GeneratorDescriptionUrld),
Example = "urld https://bing.com/?q=My+Test+query",
},
new()
{
Keyword = "esc:data",
Description = GetStringFormat(GeneratorDescriptionEscData),
Example = "esc:data C:\\Program Files\\PowerToys\\PowerToys.exe",
},
new()
{
Keyword = "uesc:data",
Description = GetStringFormat(GeneratorDescriptionUescData),
Example = "uesc:data C%3A%5CProgram%20Files%5CPowerToys%5CPowerToys.exe",
},
new()
{
Keyword = "esc:hex",
Description = GetStringFormat(GeneratorDescriptionEscHex),
Example = "esc:hex z",
},
new()
{
Keyword = "uesc:hex",
Description = GetStringFormat(GeneratorDescriptionUescHex),
Example = "uesc:hex %7A",
},
];
}
}
|
QueryHelper
|
csharp
|
abpframework__abp
|
framework/src/Volo.Abp.UI.Navigation/Volo/Abp/Ui/Navigation/ApplicationMenuGroupList.cs
|
{
"start": 90,
"end": 639
}
|
public class ____: List<ApplicationMenuGroup>
{
public ApplicationMenuGroupList()
{
}
public ApplicationMenuGroupList(int capacity)
: base(capacity)
{
}
public ApplicationMenuGroupList(IEnumerable<ApplicationMenuGroup> collection)
: base(collection)
{
}
public void Normalize()
{
Order();
}
private void Order()
{
var orderedItems = this.OrderBy(item => item.Order).ToArray();
Clear();
AddRange(orderedItems);
}
}
|
ApplicationMenuGroupList
|
csharp
|
HangfireIO__Hangfire
|
src/Hangfire.Core/Dashboard/Pages/AwaitingJobsPage.cshtml.cs
|
{
"start": 1955,
"end": 26054
}
|
internal partial class ____ : RazorPage
{
#line hidden
public override void Execute()
{
WriteLiteral("\r\n");
#line 13 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Layout = new LayoutPage(Strings.AwaitingJobsPage_Title);
int from, perPage;
int.TryParse(Query("from"), out from);
int.TryParse(Query("count"), out perPage);
List<string> jobIds = null;
Pager pager = null;
JobList <AwaitingJobDto> jobs = null;
int jobCount = 0;
if (Storage.HasFeature(JobStorageFeatures.Monitoring.AwaitingJobs))
{
var monitor = Storage.GetMonitoringApi() as JobStorageMonitor;
if (monitor == null)
{
throw new NotSupportedException("MonitoringApi should inherit the `JobStorageMonitor` class");
}
pager = new Pager(from, perPage, DashboardOptions.DefaultRecordsPerPage, monitor.AwaitingCount());
jobs = monitor.AwaitingJobs(pager.FromRecord, pager.RecordsPerPage);
jobCount = jobs.Count;
}
else
{
using (var connection = Storage.GetReadOnlyConnection())
{
var storageConnection = connection as JobStorageConnection;
if (storageConnection != null)
{
pager = new Pager(from, perPage, DashboardOptions.DefaultRecordsPerPage, storageConnection.GetSetCount("awaiting"));
jobIds = storageConnection.GetRangeFromSet("awaiting", pager.FromRecord, pager.FromRecord + pager.RecordsPerPage - 1);
jobCount = jobIds.Count;
}
}
}
#line default
#line hidden
WriteLiteral("\r\n<div class=\"row\">\r\n <div class=\"col-md-3\">\r\n ");
#line 56 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Html.JobsSidebar());
#line default
#line hidden
WriteLiteral("\r\n </div>\r\n <div class=\"col-md-9\">\r\n <h1 id=\"page-title\" class=\"page" +
"-header\">");
#line 59 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.AwaitingJobsPage_Title);
#line default
#line hidden
WriteLiteral("</h1>\r\n\r\n");
#line 61 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
if (jobIds == null && jobs == null)
{
#line default
#line hidden
WriteLiteral(" <div class=\"alert alert-warning\">\r\n <h4>");
#line 64 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.AwaitingJobsPage_ContinuationsWarning_Title);
#line default
#line hidden
WriteLiteral("</h4>\r\n <p>");
#line 65 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.AwaitingJobsPage_ContinuationsWarning_Text);
#line default
#line hidden
WriteLiteral("</p>\r\n </div>\r\n");
#line 67 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
else if (jobCount > 0)
{
#line default
#line hidden
WriteLiteral(" <div class=\"js-jobs-list\">\r\n <div class=\"btn-toolbar b" +
"tn-toolbar-top\">\r\n");
#line 72 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
if (!IsReadOnly)
{
#line default
#line hidden
WriteLiteral(" <button class=\"js-jobs-list-command btn btn-sm btn-primar" +
"y\"\r\n data-url=\"");
#line 75 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Url.To("/jobs/awaiting/enqueue"));
#line default
#line hidden
WriteLiteral("\"\r\n data-loading-text=\"");
#line 76 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.Common_Enqueueing);
#line default
#line hidden
WriteLiteral("\">\r\n <span class=\"glyphicon glyphicon-repeat\"></span>\r" +
"\n ");
#line 78 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.Common_EnqueueButton_Text);
#line default
#line hidden
WriteLiteral("\r\n </button>\r\n");
#line 80 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
#line default
#line hidden
#line 81 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
if (!IsReadOnly)
{
#line default
#line hidden
WriteLiteral(" <button class=\"js-jobs-list-command btn btn-sm btn-defaul" +
"t\"\r\n data-url=\"");
#line 84 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Url.To("/jobs/awaiting/delete"));
#line default
#line hidden
WriteLiteral("\"\r\n data-loading-text=\"");
#line 85 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.Common_Deleting);
#line default
#line hidden
WriteLiteral("\"\r\n data-confirm=\"");
#line 86 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.Common_DeleteConfirm);
#line default
#line hidden
WriteLiteral("\">\r\n <span class=\"glyphicon glyphicon-remove\"></span>\r" +
"\n ");
#line 88 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.Common_DeleteSelected);
#line default
#line hidden
WriteLiteral("\r\n </button>\r\n");
#line 90 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
#line default
#line hidden
WriteLiteral(" ");
#line 91 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Html.PerPageSelector(pager));
#line default
#line hidden
WriteLiteral("\r\n </div>\r\n\r\n <div class=\"table-responsive\">\r\n " +
" <table class=\"table table-hover\" aria-describedby=\"page-title\">\r\n" +
" <thead>\r\n <tr>\r\n");
#line 98 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
if (!IsReadOnly)
{
#line default
#line hidden
WriteLiteral(" <th class=\"min-width\">\r\n " +
" <input type=\"checkbox\" class=\"js-jobs-list-select-all\"/>\r\n " +
" </th>\r\n");
#line 103 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
#line default
#line hidden
WriteLiteral(" <th class=\"min-width\">");
#line 104 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.Common_Id);
#line default
#line hidden
WriteLiteral("</th>\r\n <th>");
#line 105 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.Common_Job);
#line default
#line hidden
WriteLiteral("</th>\r\n <th class=\"min-width\">");
#line 106 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.AwaitingJobsPage_Table_Options);
#line default
#line hidden
WriteLiteral("</th>\r\n <th class=\"min-width\">");
#line 107 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.AwaitingJobsPage_Table_Parent);
#line default
#line hidden
WriteLiteral("</th>\r\n <th class=\"align-right\">");
#line 108 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.AwaitingJobsPage_Table_Since);
#line default
#line hidden
WriteLiteral("</th>\r\n </tr>\r\n </thead>\r\n " +
" <tbody>\r\n");
#line 112 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
for (var i = 0; i < jobCount; i++)
{
var jobId = jobIds != null ? jobIds[i] : jobs[i].Key;
Job job = null;
bool inAwaitingState = true;
IDictionary<string, string> stateData = null;
string parentStateName = null;
DateTime? awaitingSince = null;
if (jobs != null)
{
if (jobs[i].Value != null)
{
job = jobs[i].Value.Job;
inAwaitingState = jobs[i].Value.InAwaitingState;
stateData = jobs[i].Value.StateData;
parentStateName = jobs[i].Value.ParentStateName;
awaitingSince = jobs[i].Value.AwaitingAt;
}
}
else
{
using (var connection = Storage.GetReadOnlyConnection())
{
var jobData = connection.GetJobData(jobId);
var state = connection.GetStateData(jobId);
inAwaitingState = AwaitingState.StateName.Equals(state?.Name);
if (state != null && inAwaitingState)
{
var parentState = connection.GetStateData(state.Data["ParentId"]);
parentStateName = parentState.Name;
}
job = jobData.Job;
stateData = state?.Data;
awaitingSince = jobData.CreatedAt;
}
}
#line default
#line hidden
WriteLiteral(" <tr class=\"js-jobs-list-row ");
#line 153 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(job == null || !inAwaitingState ? "obsolete-data" : null);
#line default
#line hidden
WriteLiteral(" ");
#line 153 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(job != null && inAwaitingState ? "hover" : null);
#line default
#line hidden
WriteLiteral("\">\r\n");
#line 154 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
if (!IsReadOnly)
{
#line default
#line hidden
WriteLiteral(" <td>\r\n");
#line 157 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
if (job != null && inAwaitingState)
{
#line default
#line hidden
WriteLiteral(" <input type=\"checkbox\" class=\"js-" +
"jobs-list-checkbox\" name=\"jobs[]\" value=\"");
#line 159 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(jobId);
#line default
#line hidden
WriteLiteral("\" />\r\n");
#line 160 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
#line default
#line hidden
WriteLiteral(" </td>\r\n");
#line 162 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
#line default
#line hidden
WriteLiteral(" <td class=\"min-width\">\r\n " +
" ");
#line 164 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Html.JobIdLink(jobId));
#line default
#line hidden
WriteLiteral("\r\n");
#line 165 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
if (job != null && !inAwaitingState)
{
#line default
#line hidden
WriteLiteral(" <span title=\"");
#line 167 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.Common_JobStateChanged_Text);
#line default
#line hidden
WriteLiteral("\" class=\"glyphicon glyphicon-question-sign\"></span>\r\n");
#line 168 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
#line default
#line hidden
WriteLiteral(" </td>\r\n");
#line 170 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
if (job == null)
{
#line default
#line hidden
WriteLiteral(" <td colspan=\"4\"><em>");
#line 172 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.Common_JobExpired);
#line default
#line hidden
WriteLiteral("</em></td>\r\n");
#line 173 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
else
{
#line default
#line hidden
WriteLiteral(" <td class=\"word-break\">\r\n " +
" ");
#line 177 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Html.JobNameLink(jobId, job));
#line default
#line hidden
WriteLiteral("\r\n </td>\r\n");
WriteLiteral(" <td class=\"min-width\">\r\n");
#line 180 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
if (stateData != null && stateData.ContainsKey("Options") && !String.IsNullOrWhiteSpace(stateData["Options"]))
{
var optionsDescription = stateData["Options"];
if (Enum.TryParse(optionsDescription, out JobContinuationOptions options))
{
optionsDescription = options.ToString("G");
}
#line default
#line hidden
WriteLiteral(" <code>");
#line 187 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(optionsDescription);
#line default
#line hidden
WriteLiteral("</code>\r\n");
#line 188 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
else
{
#line default
#line hidden
WriteLiteral(" <em>");
#line 191 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.Common_NotAvailable);
#line default
#line hidden
WriteLiteral("</em>\r\n");
#line 192 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
#line default
#line hidden
WriteLiteral(" </td>\r\n");
WriteLiteral(" <td class=\"min-width\">\r\n");
#line 195 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
if (parentStateName != null)
{
#line default
#line hidden
WriteLiteral(" <a href=\"");
#line 197 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Url.JobDetails(stateData["ParentId"]));
#line default
#line hidden
WriteLiteral("\" class=\"text-decoration-none\">\r\n " +
" ");
#line 198 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Html.StateLabel(parentStateName, parentStateName, hover: true));
#line default
#line hidden
WriteLiteral("\r\n </a>\r\n");
#line 200 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
else
{
#line default
#line hidden
WriteLiteral(" <em>");
#line 203 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.Common_NotAvailable);
#line default
#line hidden
WriteLiteral("</em>\r\n");
#line 204 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
#line default
#line hidden
WriteLiteral(" </td>\r\n");
WriteLiteral(" <td class=\"min-width align-right\">\r\n");
#line 207 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
if (awaitingSince.HasValue)
{
#line default
#line hidden
#line 209 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Html.RelativeTime(awaitingSince.Value));
#line default
#line hidden
#line 209 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
else
{
#line default
#line hidden
WriteLiteral(" <em>");
#line 213 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.Common_NotAvailable);
#line default
#line hidden
WriteLiteral("</em>\r\n");
#line 214 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
#line default
#line hidden
WriteLiteral(" </td>\r\n");
#line 216 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
#line default
#line hidden
WriteLiteral(" </tr>\r\n");
#line 218 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
#line default
#line hidden
WriteLiteral(" </tbody>\r\n </table>\r\n <" +
"/div>\r\n ");
#line 222 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Html.Paginator(pager));
#line default
#line hidden
WriteLiteral("\r\n </div>\r\n");
#line 224 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
else
{
#line default
#line hidden
WriteLiteral(" <div class=\"alert alert-info\">\r\n ");
#line 228 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(Strings.AwaitingJobsPage_NoJobs);
#line default
#line hidden
WriteLiteral("\r\n </div>\r\n");
#line 230 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
}
#line default
#line hidden
WriteLiteral(" </div>\r\n</div>\r\n");
}
}
}
#pragma warning restore 1591
|
AwaitingJobsPage
|
csharp
|
louthy__language-ext
|
LanguageExt.Core/Effects/IO/DSL/IOBindMap.cs
|
{
"start": 729,
"end": 1370
}
|
record ____<A, B, C>(A Value, Func<A, K<IO, B>> Ff, Func<B, K<IO, C>> Fg) : InvokeSyncIO<C>
{
public override IO<D> Map<D>(Func<C, D> f) =>
new IOBindBindMap<A, B, C, D>(Value, Ff, Fg, f);
public override IO<D> Bind<D>(Func<C, K<IO, D>> f) =>
new IOBindBind<A, B, D>(Value, Ff, x => Fg(x).Bind(f));
public override IO<D> BindAsync<D>(Func<C, ValueTask<K<IO, D>>> f) =>
new IOBindBind<A, B, D>(Value, Ff, x => Fg(x).As().BindAsync(f));
public override IO<C> Invoke(EnvIO envIO) =>
Ff(Value).As().Bind(Fg);
public override string ToString() =>
"IO bind bind";
}
|
IOBindBind
|
csharp
|
OrchardCMS__OrchardCore
|
src/OrchardCore/OrchardCore.DisplayManagement/ShapeFactoryExtensions.cs
|
{
"start": 194,
"end": 3721
}
|
public static class ____
{
private static readonly ConcurrentDictionary<Type, Type> _proxyTypesCache = [];
private static readonly ProxyGenerator _proxyGenerator = new();
private static readonly Func<ValueTask<IShape>> _newShape = () => ValueTask.FromResult<IShape>(new Shape());
/// <summary>
/// Creates a new generic shape by copying the properties of an object.
/// </summary>
/// <param name="factory">The <see cref="IShapeFactory"/>.</param>
/// <param name="shapeType">The type of shape to create.</param>
/// <param name="model">The model to copy.</param>
/// <returns></returns>
public static ValueTask<IShape> CreateAsync<TModel>(this IShapeFactory factory, string shapeType, TModel model)
=> factory.CreateAsync(shapeType, Arguments.From(model));
/// <summary>
/// Creates a new generic shape instance.
/// </summary>
public static ValueTask<IShape> CreateAsync(this IShapeFactory factory, string shapeType)
=> factory.CreateAsync(shapeType, _newShape);
/// <summary>
/// Creates a new generic shape instance and initializes it.
/// </summary>
public static ValueTask<IShape> CreateAsync(this IShapeFactory factory, string shapeType, Func<ValueTask<IShape>> shapeFactory)
=> factory.CreateAsync(shapeType, shapeFactory, null, null);
/// <summary>
/// Creates a dynamic proxy instance for the type and initializes it.
/// </summary>
/// <typeparam name="TModel">The type to instantiate.</typeparam>
/// <param name="factory">The <see cref="IShapeFactory"/>.</param>
/// <param name="initialize">The initialization method.</param>
/// <returns></returns>
public static ValueTask<IShape> CreateAsync<TModel>(this IShapeFactory factory, Action<TModel> initialize = null)
where TModel : class
=> factory.CreateAsync(typeof(TModel).Name, initialize);
/// <summary>
/// Creates a dynamic proxy instance for the type and initializes it.
/// </summary>
/// <typeparam name="TModel">The type to instantiate.</typeparam>
/// <param name="factory">The <see cref="IShapeFactory"/>.</param>
/// <param name="shapeType">The shape type to create.</param>
/// <param name="initialize">The initialization method.</param>
/// <returns></returns>
public static ValueTask<IShape> CreateAsync<TModel>(this IShapeFactory factory, string shapeType, Action<TModel> initialize = null)
where TModel : class
{
return factory.CreateAsync<TModel>(shapeType, initializeAsync: (model) =>
{
initialize?.Invoke(model);
return ValueTask.CompletedTask;
});
}
/// <summary>
/// Creates a generic shape and initializes it with some properties.
/// </summary>
public static ValueTask<IShape> CreateAsync(this IShapeFactory factory, string shapeType, INamedEnumerable<object> parameters)
{
ArgumentException.ThrowIfNullOrEmpty(shapeType);
if (parameters == null || parameters == Arguments.Empty)
{
return factory.CreateAsync(shapeType);
}
return factory.CreateAsync(shapeType, _newShape, null, createdContext =>
{
var shape = (Shape)createdContext.Shape;
// If only one non-Type, use it as the source object to copy.
var initializer = parameters.Positional.SingleOrDefault();
if (initializer != null)
{
// Use the Arguments
|
ShapeFactoryExtensions
|
csharp
|
getsentry__sentry-dotnet
|
test/Sentry.Tests/Internals/MainExceptionProcessorTests.cs
|
{
"start": 90,
"end": 11599
}
|
private class ____
{
public ISentryStackTraceFactory SentryStackTraceFactory { get; set; } = Substitute.For<ISentryStackTraceFactory>();
public SentryOptions SentryOptions { get; set; } = new();
public MainExceptionProcessor GetSut() => new(SentryOptions, () => SentryStackTraceFactory);
}
private readonly Fixture _fixture = new();
[Fact]
public void Process_ExceptionsWithoutData_MechanismDataIsMinimal()
{
var sut = _fixture.GetSut();
var evt = new SentryEvent();
var ex = GetHandledException();
sut.Process(ex, evt);
var sentryException = evt.SentryExceptions!.Single();
// All managed exceptions has an HResult, at a bare minimum (which we store in the Mechanism.Data)
sentryException.Mechanism!.Data.Should().BeEquivalentTo(new Dictionary<string, string>()
{
["HResult"] = "0x80131500" // The default value of HRESULT for managed exceptions (COR_E_EXCEPTION)
});
}
[Fact]
public void Process_ExceptionsWithData_MechanismDataIsPopulated()
{
var sut = _fixture.GetSut();
var evt = new SentryEvent();
var ex = GetHandledException();
ex.Data["foo"] = 123;
ex.Data["bar"] = 456;
sut.Process(ex, evt);
var sentryException = evt.SentryExceptions!.Single();
var data = sentryException.Mechanism!.Data;
Assert.Contains(data, pair => pair.Key == "foo" && pair.Value.Equals(123));
Assert.Contains(data, pair => pair.Key == "bar" && pair.Value.Equals(456));
}
[Fact]
public void Process_ExceptionWithout_Handled()
{
var sut = _fixture.GetSut();
var evt = new SentryEvent();
var exp = new Exception();
sut.Process(exp, evt);
Assert.NotNull(evt.SentryExceptions);
Assert.Single(evt.SentryExceptions, p => p.Mechanism?.Handled == null);
}
[Fact]
public void Process_ExceptionWith_HandledFalse()
{
var sut = _fixture.GetSut();
var evt = new SentryEvent();
var exp = new Exception();
exp.Data.Add(Mechanism.HandledKey, false);
sut.Process(exp, evt);
Assert.NotNull(evt.SentryExceptions);
Assert.Single(evt.SentryExceptions, p => p.Mechanism?.Handled == false);
}
[Fact]
public void Process_ExceptionWith_HandledTrue()
{
var sut = _fixture.GetSut();
var evt = new SentryEvent();
var exp = new Exception();
exp.Data.Add(Mechanism.HandledKey, true);
sut.Process(exp, evt);
Assert.NotNull(evt.SentryExceptions);
Assert.Single(evt.SentryExceptions, p => p.Mechanism?.Handled == true);
}
[Fact]
public void Process_ExceptionWith_HandledTrue_WhenCaught()
{
var sut = _fixture.GetSut();
var evt = new SentryEvent();
var exp = GetHandledException();
sut.Process(exp, evt);
Assert.NotNull(evt.SentryExceptions);
Assert.Single(evt.SentryExceptions, p => p.Mechanism?.Handled == true);
}
[Fact]
public void Process_ExceptionWith_TerminalTrue_StoresInMechanismData()
{
var sut = _fixture.GetSut();
var evt = new SentryEvent();
var exp = new Exception();
exp.SetSentryMechanism("TestException", terminal: true);
sut.Process(exp, evt);
Assert.NotNull(evt.SentryExceptions);
var sentryException = evt.SentryExceptions.Single();
Assert.NotNull(sentryException.Mechanism?.Terminal);
Assert.True(sentryException.Mechanism?.Terminal);
}
[Fact]
public void Process_ExceptionWith_TerminalFalse_StoresInMechanismData()
{
var sut = _fixture.GetSut();
var evt = new SentryEvent();
var exp = new Exception();
exp.SetSentryMechanism("TestException", terminal: false);
sut.Process(exp, evt);
Assert.NotNull(evt.SentryExceptions);
var sentryException = evt.SentryExceptions.Single();
Assert.False(sentryException.Mechanism?.Terminal);
}
[Fact]
public void CreateSentryException_DataHasObjectAsKey_ItemIgnored()
{
var sut = _fixture.GetSut();
var ex = new Exception
{
Data = { [new object()] = new object() }
};
var actual = sut.CreateSentryExceptions(ex).Single();
// The custom data won't be added, but the mechanism data will still contain an HResult.
// We add the HResult for all exceptions
actual.Mechanism!.Data.Should().BeEquivalentTo(new Dictionary<string, string>()
{
["HResult"] = "0x80131500" // The default value of HRESULT for managed exceptions (COR_E_EXCEPTION)
});
}
[Fact]
public void Process_AggregateException()
{
var sut = _fixture.GetSut();
_fixture.SentryStackTraceFactory = _fixture.SentryOptions.SentryStackTraceFactory;
var evt = new SentryEvent();
sut.Process(BuildAggregateException(), evt);
var last = evt.SentryExceptions!.Last();
// TODO: Create integration test to test this behaviour when publishing AOT apps
// See https://github.com/getsentry/sentry-dotnet/issues/2772
Assert.NotNull(last.Stacktrace);
var mechanism = last.Mechanism;
Assert.NotNull(mechanism);
Assert.False(mechanism.Handled);
Assert.NotNull(mechanism.Type);
Assert.NotEmpty(mechanism.Data);
}
private static AggregateException BuildAggregateException()
{
try
{
// Throwing will put a stack trace on the exception
throw new AggregateException("One or more errors occurred.",
new Exception("Inner message1"),
new Exception("Inner message2"));
}
catch (AggregateException exception)
{
// Add extra data to test fully
exception.Data[Mechanism.HandledKey] = false;
exception.Data[Mechanism.MechanismKey] = "AppDomain.UnhandledException";
exception.Data["foo"] = "bar";
return exception;
}
}
[Fact]
public void Process_HasTagsOnExceptionData_TagsSet()
{
//Assert
var sut = _fixture.GetSut();
var expectedTag1 = new KeyValuePair<string, string>("Tag1", "1234");
var expectedTag2 = new KeyValuePair<string, string>("Tag2", "4321");
var ex = new Exception();
var evt = new SentryEvent();
//Act
ex.AddSentryTag(expectedTag1.Key, expectedTag1.Value);
ex.AddSentryTag(expectedTag2.Key, expectedTag2.Value);
sut.Process(ex, evt);
//Assert
Assert.Single(evt.Tags, expectedTag1);
Assert.Single(evt.Tags, expectedTag2);
}
[Fact]
public void Process_HasInvalidExceptionTagsValue_TagsSetWithInvalidValue()
{
//Assert
var sut = _fixture.GetSut();
var invalidTag1 = new KeyValuePair<string, int>("Tag1", 1234);
var invalidTag2 = new KeyValuePair<string, int?>("Tag2", null);
var invalidTag3 = new KeyValuePair<string, string>("", "abcd");
var expectedTag1 = new KeyValuePair<string, object>("Exception[0][sentry:tag:Tag1]", 1234);
var expectedTag2 = new KeyValuePair<string, object>("Exception[0][sentry:tag:Tag2]", null);
var expectedTag3 = new KeyValuePair<string, object>("Exception[0][sentry:tag:]", "abcd");
var ex = new Exception();
var evt = new SentryEvent();
//Act
ex.Data.Add($"{MainExceptionProcessor.ExceptionDataTagKey}{invalidTag1.Key}", invalidTag1.Value);
ex.Data.Add($"{MainExceptionProcessor.ExceptionDataTagKey}{invalidTag2.Key}", invalidTag2.Value);
ex.AddSentryTag(invalidTag3.Key, invalidTag3.Value);
sut.Process(ex, evt);
//Assert
Assert.Single(evt.Extra, expectedTag1);
Assert.Single(evt.Extra, expectedTag2);
Assert.Single(evt.Extra, expectedTag3);
}
[Fact]
public void Process_HasContextOnExceptionData_ContextSet()
{
//Assert
var sut = _fixture.GetSut();
var ex = new Exception();
var evt = new SentryEvent();
var expectedContext1 = new KeyValuePair<string, Dictionary<string, object>>("Context 1",
new Dictionary<string, object>
{
{ "Data1", new { a = 1, b = 2, c = "12345"} },
{ "Data2", "Something broke." }
});
var expectedContext2 = new KeyValuePair<string, Dictionary<string, object>>("Context 2",
new Dictionary<string, object>
{
{ "Data1", new { c = 1, d = 2, e = "12345"} },
{ "Data2", "Something broke again." }
});
//Act
ex.AddSentryContext(expectedContext1.Key, expectedContext1.Value);
ex.AddSentryContext(expectedContext2.Key, expectedContext2.Value);
sut.Process(ex, evt);
//Assert
Assert.Equal(evt.Contexts[expectedContext1.Key], expectedContext1.Value);
Assert.Equal(evt.Contexts[expectedContext2.Key], expectedContext2.Value);
}
[Fact]
public void Process_HasContextOnExceptionDataWithNullValue_ContextSetWithInvalidValue()
{
//Assert
var sut = _fixture.GetSut();
var ex = new Exception();
var evt = new SentryEvent();
var invalidContext = new KeyValuePair<string, Dictionary<string, object>>("Context 1", null);
var expectedContext = new KeyValuePair<string, object>("Exception[0][sentry:context:Context 1]", null);
var invalidContext2 = new KeyValuePair<string, Dictionary<string, object>>("",
new Dictionary<string, object>
{
{ "Data3", new { c = 1, d = 2, e = "12345"} },
{ "Data4", "Something broke again." }
});
var expectedContext2 = new KeyValuePair<string, object>("Exception[0][sentry:context:]", invalidContext2.Value);
//Act
ex.AddSentryContext(invalidContext.Key, invalidContext.Value);
ex.AddSentryContext(invalidContext2.Key, invalidContext2.Value);
sut.Process(ex, evt);
//Assert
Assert.Single(evt.Extra, expectedContext);
Assert.Single(evt.Extra, expectedContext2);
}
[Fact]
public void Process_HasUnsupportedExceptionValue_ValueSetAsExtra()
{
//Assert
var sut = _fixture.GetSut();
var invalidData1 = new KeyValuePair<string, string>("sentry:attachment:filename", "./path");
var invalidData2 = new KeyValuePair<string, int?>("sentry:unsupported:value", null);
var expectedData = new KeyValuePair<string, object>($"Exception[0][{invalidData1.Key}]", invalidData1.Value);
var expectedData2 = new KeyValuePair<string, object>($"Exception[0][{invalidData2.Key}]", invalidData2.Value);
var ex = new Exception();
var evt = new SentryEvent();
//Act
ex.Data.Add(invalidData1.Key, invalidData1.Value);
ex.Data.Add(invalidData2.Key, invalidData2.Value);
sut.Process(ex, evt);
//Assert
Assert.Single(evt.Extra, expectedData);
Assert.Single(evt.Extra, expectedData2);
}
private Exception GetHandledException()
{
try
{
throw new Exception();
}
catch (Exception exception)
{
return exception;
}
}
}
|
Fixture
|
csharp
|
kgrzybek__modular-monolith-with-ddd
|
src/API/CompanyName.MyMeetings.API/Configuration/Authorization/HasPermissionAuthorizationHandler.cs
|
{
"start": 337,
"end": 1894
}
|
internal class ____ : AttributeAuthorizationHandler<
HasPermissionAuthorizationRequirement, HasPermissionAttribute>
{
private readonly IExecutionContextAccessor _executionContextAccessor;
private readonly IUserAccessModule _userAccessModule;
public HasPermissionAuthorizationHandler(
IExecutionContextAccessor executionContextAccessor,
IUserAccessModule userAccessModule)
{
_executionContextAccessor = executionContextAccessor;
_userAccessModule = userAccessModule;
}
protected override async Task HandleRequirementAsync(
AuthorizationHandlerContext context,
HasPermissionAuthorizationRequirement requirement,
HasPermissionAttribute attribute)
{
var permissions = await _userAccessModule.ExecuteQueryAsync(new GetUserPermissionsQuery(_executionContextAccessor.UserId));
if (!await AuthorizeAsync(attribute.Name, permissions))
{
context.Fail();
return;
}
context.Succeed(requirement);
}
private Task<bool> AuthorizeAsync(string permission, List<UserPermissionDto> permissions)
{
#if !DEBUG
return Task.FromResult(true);
#endif
#pragma warning disable CS0162 // Unreachable code detected
return Task.FromResult(permissions.Any(x => x.Code == permission));
#pragma warning restore CS0162 // Unreachable code detected
}
}
}
|
HasPermissionAuthorizationHandler
|
csharp
|
dotnet__efcore
|
test/EFCore.Relational.Specification.Tests/TestUtilities/PrecompiledQueryTestHelpers.cs
|
{
"start": 1291,
"end": 12510
}
|
public static class ____
{
public static async Task Test(DbContextOptions dbContextOptions)
{
{{sourceCode}}
}
}
""";
return FullSourceTest(
source, dbContextOptions, dbContextType, interceptorCodeAsserter, errorAsserter, testOutputHelper, alwaysPrintGeneratedSources,
callerName);
}
public async Task FullSourceTest(
string sourceCode,
DbContextOptions dbContextOptions,
Type dbContextType,
Action<string>? interceptorCodeAsserter,
Action<List<PrecompiledQueryCodeGenerator.QueryPrecompilationError>>? errorAsserter,
ITestOutputHelper testOutputHelper,
bool alwaysPrintGeneratedSources,
string callerName)
{
// The overall end-to-end testing for precompiled queries is as follows:
// 1. Compile the user code, produce an assembly from it and load it. We need to do this since precompiled query generation requires
// an actual DbContext instance, from which we get the model, services, ec.
// 2. Do precompiled query generation. This outputs additional source files (syntax trees) containing interceptors for the located
// EF LINQ queries.
// 3. Integrate the additional syntax trees into the compilation, and again, produce an assembly from it and load it.
// 4. Use reflection to find the EntryPoint (Main method) on this assembly, and invoke it.
var source = $"""
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
using Xunit;
using static Microsoft.EntityFrameworkCore.Query.PrecompiledQueryRelationalTestBase;
{sourceCode}
""";
// This turns on the interceptors feature for the designated namespace(s).
var parseOptions = new CSharpParseOptions().WithFeatures(
[
new KeyValuePair<string, string>("InterceptorsNamespaces", "Microsoft.EntityFrameworkCore.GeneratedInterceptors")
]);
var syntaxTree = CSharpSyntaxTree.ParseText(source, parseOptions, path: "Test.cs");
var compilation = CSharpCompilation.Create(
"TestCompilation",
syntaxTrees: [syntaxTree],
_metadataReferences,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable));
IReadOnlyList<ScaffoldedFile>? generatedFiles = null;
try
{
// The test code compiled - emit and assembly and load it.
var (assemblyLoadContext, assembly) = EmitAndLoadAssembly(compilation, callerName + "_Original");
try
{
var workspace = new AdhocWorkspace();
var syntaxGenerator = SyntaxGenerator.GetGenerator(workspace, LanguageNames.CSharp);
// TODO: Look up as regular dependencies
var precompiledQueryCodeGenerator = new PrecompiledQueryCodeGenerator();
await using var dbContext = (DbContext)Activator.CreateInstance(dbContextType, args: [dbContextOptions])!;
// Perform precompilation
var precompilationErrors = new List<PrecompiledQueryCodeGenerator.QueryPrecompilationError>();
generatedFiles = precompiledQueryCodeGenerator.GeneratePrecompiledQueries(
compilation, syntaxGenerator, dbContext, memberAccessReplacements: new Dictionary<MemberInfo, QualifiedName>(),
precompilationErrors, new HashSet<string>(), additionalAssembly: assembly);
if (errorAsserter is null)
{
if (precompilationErrors.Count > 0)
{
Assert.Fail("Precompilation error: " + precompilationErrors[0].Exception);
}
}
else
{
errorAsserter(precompilationErrors);
return;
}
interceptorCodeAsserter?.Invoke(generatedFiles.Single().Code);
}
finally
{
assemblyLoadContext.Unload();
}
// We now have the code-generated interceptors; add them to the compilation and re-emit.
compilation = compilation.AddSyntaxTrees(
generatedFiles.Select(f => CSharpSyntaxTree.ParseText(f.Code, parseOptions, f.Path)));
// We have the final compilation, including the interceptors. Emit and load it, and then invoke its entry point, which contains
// the original test code with the EF LINQ query, etc.
(assemblyLoadContext, assembly) = EmitAndLoadAssembly(compilation, callerName + "_WithInterceptors");
try
{
await using var dbContext = (DbContext)Activator.CreateInstance(dbContextType, dbContextOptions)!;
var testContainer = assembly.ExportedTypes.Single(t => t.Name == "TestContainer");
var testMethod = testContainer.GetMethod("Test")!;
await (Task)testMethod.Invoke(obj: null, parameters: [dbContextOptions])!;
}
finally
{
assemblyLoadContext.Unload();
}
}
catch
{
PrintGeneratedSources();
throw;
}
if (alwaysPrintGeneratedSources)
{
PrintGeneratedSources();
}
void PrintGeneratedSources()
{
if (generatedFiles is not null)
{
foreach (var generatedFile in generatedFiles)
{
testOutputHelper.WriteLine($"Generated file {generatedFile.Path}: ");
testOutputHelper.WriteLine("");
testOutputHelper.WriteLine(generatedFile.Code);
}
}
}
static (AssemblyLoadContext, Assembly) EmitAndLoadAssembly(Compilation compilation, string assemblyLoadContextName)
{
var errorDiagnostics = compilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ToList();
if (errorDiagnostics.Count > 0)
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine("Compilation failed:").AppendLine();
foreach (var errorDiagnostic in errorDiagnostics)
{
stringBuilder.AppendLine(errorDiagnostic.ToString());
var textLines = errorDiagnostic.Location.SourceTree!.GetText().Lines;
var startLine = errorDiagnostic.Location.GetLineSpan().StartLinePosition.Line;
var endLine = errorDiagnostic.Location.GetLineSpan().EndLinePosition.Line;
if (startLine == endLine)
{
stringBuilder.Append("Line: ").AppendLine(textLines[startLine].ToString().TrimStart());
}
else
{
stringBuilder.AppendLine("Lines:");
for (var i = startLine; i <= endLine; i++)
{
stringBuilder.AppendLine(textLines[i].ToString());
}
}
}
throw new InvalidOperationException("Compilation failed:" + stringBuilder);
}
using var memoryStream = new MemoryStream();
var emitResult = compilation.Emit(memoryStream);
memoryStream.Position = 0;
errorDiagnostics = emitResult.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).ToList();
if (errorDiagnostics.Count > 0)
{
throw new InvalidOperationException(
"Compilation emit failed:" + Environment.NewLine + string.Join(Environment.NewLine, errorDiagnostics));
}
var assemblyLoadContext = new AssemblyLoadContext(assemblyLoadContextName, isCollectible: true);
var assembly = assemblyLoadContext.LoadFromStream(memoryStream);
return (assemblyLoadContext, assembly);
}
}
protected virtual IEnumerable<MetadataReference> BuildMetadataReferences()
{
var netAssemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location)!;
return new[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Queryable).Assembly.Location),
MetadataReference.CreateFromFile(typeof(IQueryable).Assembly.Location),
MetadataReference.CreateFromFile(typeof(List<>).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Regex).Assembly.Location),
MetadataReference.CreateFromFile(typeof(JsonSerializer).Assembly.Location),
MetadataReference.CreateFromFile(typeof(JavaScriptEncoder).Assembly.Location),
MetadataReference.CreateFromFile(typeof(DatabaseGeneratedAttribute).Assembly.Location),
MetadataReference.CreateFromFile(typeof(DbContext).Assembly.Location),
MetadataReference.CreateFromFile(typeof(RelationalOptionsExtension).Assembly.Location),
MetadataReference.CreateFromFile(typeof(DbConnection).Assembly.Location),
MetadataReference.CreateFromFile(typeof(IListSource).Assembly.Location),
MetadataReference.CreateFromFile(typeof(IServiceProvider).Assembly.Location),
MetadataReference.CreateFromFile(typeof(IMemoryCache).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Assert).Assembly.Location),
// This is to allow referencing types from this file, e.g. NonCompilingQueryCompiler
MetadataReference.CreateFromFile(Assembly.GetExecutingAssembly().Location),
MetadataReference.CreateFromFile(Path.Combine(netAssemblyPath, "mscorlib.dll")),
MetadataReference.CreateFromFile(Path.Combine(netAssemblyPath, "System.dll")),
MetadataReference.CreateFromFile(Path.Combine(netAssemblyPath, "System.Core.dll")),
MetadataReference.CreateFromFile(Path.Combine(netAssemblyPath, "System.Runtime.dll")),
MetadataReference.CreateFromFile(Path.Combine(netAssemblyPath, "System.Collections.dll"))
}
.Concat(BuildProviderMetadataReferences());
}
protected abstract IEnumerable<MetadataReference> BuildProviderMetadataReferences();
// Used from inside the tested code to ensure that we never end up compiling queries at runtime.
// TODO: Probably remove this later, once we have a regular mechanism for failing non-intercepted queries at runtime.
// ReSharper disable once UnusedMember.Global
|
TestContainer
|
csharp
|
abpframework__abp
|
framework/src/Volo.Abp.BlazoriseUI/AbpCrudPageBase.cs
|
{
"start": 2666,
"end": 3478
}
|
public abstract class ____<
TAppService,
TGetOutputDto,
TGetListOutputDto,
TKey,
TGetListInput,
TCreateInput,
TUpdateInput>
: AbpCrudPageBase<
TAppService,
TGetOutputDto,
TGetListOutputDto,
TKey,
TGetListInput,
TCreateInput,
TUpdateInput,
TGetListOutputDto,
TCreateInput,
TUpdateInput>
where TAppService : ICrudAppService<
TGetOutputDto,
TGetListOutputDto,
TKey,
TGetListInput,
TCreateInput,
TUpdateInput>
where TGetOutputDto : IEntityDto<TKey>
where TGetListOutputDto : IEntityDto<TKey>
where TCreateInput : class, new()
where TUpdateInput : class, new()
where TGetListInput : new()
{
}
|
AbpCrudPageBase
|
csharp
|
dotnet__maui
|
src/Essentials/src/Battery/Battery.ios.watchos.cs
|
{
"start": 277,
"end": 3603
}
|
partial class ____ : IBattery
{
#if !__WATCHOS__
NSObject levelObserver;
NSObject stateObserver;
#endif
NSObject saverStatusObserver;
void StartEnergySaverListeners()
{
saverStatusObserver = NSNotificationCenter.DefaultCenter.AddObserver(NSProcessInfo.PowerStateDidChangeNotification, PowerChangedNotification);
}
void StopEnergySaverListeners()
{
saverStatusObserver?.Dispose();
saverStatusObserver = null;
}
void PowerChangedNotification(NSNotification notification)
=> PlatformUtils.BeginInvokeOnMainThread(OnEnergySaverChanged);
public EnergySaverStatus EnergySaverStatus =>
NSProcessInfo.ProcessInfo?.LowPowerModeEnabled == true ? EnergySaverStatus.On : EnergySaverStatus.Off;
void StartBatteryListeners()
{
#if __WATCHOS__
throw new FeatureNotSupportedException();
#else
UIDevice.CurrentDevice.BatteryMonitoringEnabled = true;
levelObserver = UIDevice.Notifications.ObserveBatteryLevelDidChange(BatteryInfoChangedNotification);
stateObserver = UIDevice.Notifications.ObserveBatteryStateDidChange(BatteryInfoChangedNotification);
#endif
}
void StopBatteryListeners()
{
#if __WATCHOS__
throw new FeatureNotSupportedException();
#else
UIDevice.CurrentDevice.BatteryMonitoringEnabled = false;
levelObserver?.Dispose();
levelObserver = null;
stateObserver?.Dispose();
stateObserver = null;
#endif
}
void BatteryInfoChangedNotification(object sender, NSNotificationEventArgs args)
=> PlatformUtils.BeginInvokeOnMainThread(OnBatteryInfoChanged);
public double ChargeLevel
{
get
{
var batteryMonitoringEnabled = UIDevice.CurrentDevice.BatteryMonitoringEnabled;
UIDevice.CurrentDevice.BatteryMonitoringEnabled = true;
try
{
return UIDevice.CurrentDevice.BatteryLevel;
}
finally
{
UIDevice.CurrentDevice.BatteryMonitoringEnabled = batteryMonitoringEnabled;
}
}
}
public BatteryState State
{
get
{
var batteryMonitoringEnabled = UIDevice.CurrentDevice.BatteryMonitoringEnabled;
UIDevice.CurrentDevice.BatteryMonitoringEnabled = true;
try
{
switch (UIDevice.CurrentDevice.BatteryState)
{
case UIDeviceBatteryState.Charging:
return BatteryState.Charging;
case UIDeviceBatteryState.Full:
return BatteryState.Full;
case UIDeviceBatteryState.Unplugged:
return BatteryState.Discharging;
default:
if (ChargeLevel >= 1.0)
return BatteryState.Full;
return BatteryState.Unknown;
}
}
finally
{
UIDevice.CurrentDevice.BatteryMonitoringEnabled = batteryMonitoringEnabled;
}
}
}
public BatteryPowerSource PowerSource
{
get
{
var batteryMonitoringEnabled = UIDevice.CurrentDevice.BatteryMonitoringEnabled;
UIDevice.CurrentDevice.BatteryMonitoringEnabled = true;
try
{
switch (UIDevice.CurrentDevice.BatteryState)
{
case UIDeviceBatteryState.Full:
case UIDeviceBatteryState.Charging:
return BatteryPowerSource.AC;
case UIDeviceBatteryState.Unplugged:
return BatteryPowerSource.Battery;
default:
return BatteryPowerSource.Unknown;
}
}
finally
{
UIDevice.CurrentDevice.BatteryMonitoringEnabled = batteryMonitoringEnabled;
}
}
}
}
}
|
BatteryImplementation
|
csharp
|
dotnet__aspire
|
src/Aspire.Cli/Commands/DeployCommand.cs
|
{
"start": 391,
"end": 3113
}
|
internal sealed class ____ : PipelineCommandBase
{
private readonly Option<bool> _clearCacheOption;
public DeployCommand(IDotNetCliRunner runner, IInteractionService interactionService, IProjectLocator projectLocator, AspireCliTelemetry telemetry, IDotNetSdkInstaller sdkInstaller, IFeatures features, ICliUpdateNotifier updateNotifier, CliExecutionContext executionContext, ICliHostEnvironment hostEnvironment)
: base("deploy", DeployCommandStrings.Description, runner, interactionService, projectLocator, telemetry, sdkInstaller, features, updateNotifier, executionContext, hostEnvironment)
{
_clearCacheOption = new Option<bool>("--clear-cache")
{
Description = "Clear the deployment cache associated with the current environment and do not save deployment state"
};
Options.Add(_clearCacheOption);
}
protected override string OperationCompletedPrefix => DeployCommandStrings.OperationCompletedPrefix;
protected override string OperationFailedPrefix => DeployCommandStrings.OperationFailedPrefix;
protected override string GetOutputPathDescription() => DeployCommandStrings.OutputPathArgumentDescription;
protected override string[] GetRunArguments(string? fullyQualifiedOutputPath, string[] unmatchedTokens, ParseResult parseResult)
{
var baseArgs = new List<string> { "--operation", "publish", "--step", "deploy" };
if (fullyQualifiedOutputPath != null)
{
baseArgs.AddRange(["--output-path", fullyQualifiedOutputPath]);
}
var clearCache = parseResult.GetValue(_clearCacheOption);
if (clearCache)
{
baseArgs.AddRange(["--clear-cache", "true"]);
}
// Add --log-level and --envionment flags if specified
var logLevel = parseResult.GetValue(_logLevelOption);
if (!string.IsNullOrEmpty(logLevel))
{
baseArgs.AddRange(["--log-level", logLevel!]);
}
var includeExceptionDetails = parseResult.GetValue(_includeExceptionDetailsOption);
if (includeExceptionDetails)
{
baseArgs.AddRange(["--include-exception-details", "true"]);
}
var environment = parseResult.GetValue(_environmentOption);
if (!string.IsNullOrEmpty(environment))
{
baseArgs.AddRange(["--environment", environment!]);
}
baseArgs.AddRange(unmatchedTokens);
return [.. baseArgs];
}
protected override string GetCanceledMessage() => DeployCommandStrings.DeploymentCanceled;
protected override string GetProgressMessage(ParseResult parseResult)
{
return "Executing step deploy";
}
}
|
DeployCommand
|
csharp
|
ChilliCream__graphql-platform
|
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
|
{
"start": 1186827,
"end": 1188798
}
|
public partial class ____ : global::System.IEquatable<ShowEnvironmentCommandQueryResult>, IShowEnvironmentCommandQueryResult
{
public ShowEnvironmentCommandQueryResult(global::ChilliCream.Nitro.CommandLine.Cloud.Client.IShowEnvironmentCommandQuery_Node? node)
{
Node = node;
}
/// <summary>
/// Fetches an object given its ID.
/// </summary>
public global::ChilliCream.Nitro.CommandLine.Cloud.Client.IShowEnvironmentCommandQuery_Node? Node { get; }
public virtual global::System.Boolean Equals(ShowEnvironmentCommandQueryResult? other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (other.GetType() != GetType())
{
return false;
}
return (((Node is null && other.Node is null) || Node != null && Node.Equals(other.Node)));
}
public override global::System.Boolean Equals(global::System.Object? obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((ShowEnvironmentCommandQueryResult)obj);
}
public override global::System.Int32 GetHashCode()
{
unchecked
{
int hash = 5;
if (Node != null)
{
hash ^= 397 * Node.GetHashCode();
}
return hash;
}
}
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
|
ShowEnvironmentCommandQueryResult
|
csharp
|
EventStore__EventStore
|
src/KurrentDB.Core/Messages/ElectionMessageDtos.cs
|
{
"start": 1801,
"end": 3055
}
|
public class ____ {
public Guid ServerId { get; set; }
public string ServerHttpAddress { get; set; }
public int ServerHttpPort { get; set; }
public int View { get; set; }
public int EpochNumber { get; set; }
public long EpochPosition { get; set; }
public Guid EpochId { get; set; }
public Guid EpochLeaderInstanceId { get; set; }
public long LastCommitPosition { get; set; }
public long WriterCheckpoint { get; set; }
public long ChaserCheckpoint { get; set; }
public int NodePriority { get; set; }
public ClusterInfo ClusterInfo { get; set; }
public PrepareOkDto() {
}
public PrepareOkDto(ElectionMessage.PrepareOk message) {
ServerId = message.ServerId;
ServerHttpAddress = message.ServerHttpEndPoint.GetHost();
ServerHttpPort = message.ServerHttpEndPoint.GetPort();
View = message.View;
EpochNumber = message.EpochNumber;
EpochPosition = message.EpochPosition;
EpochId = message.EpochId;
EpochLeaderInstanceId = message.EpochLeaderInstanceId;
LastCommitPosition = message.LastCommitPosition;
WriterCheckpoint = message.WriterCheckpoint;
ChaserCheckpoint = message.ChaserCheckpoint;
NodePriority = message.NodePriority;
ClusterInfo = message.ClusterInfo;
}
}
|
PrepareOkDto
|
csharp
|
spectreconsole__spectre.console
|
src/Spectre.Console.Tests/Unit/Rendering/Borders/TableBorderTests.cs
|
{
"start": 11822,
"end": 12575
}
|
public sealed class ____
{
[Fact]
public void Should_Return_Safe_Border()
{
// Given, When
var border = TableBorder.SimpleHeavy.GetSafeBorder(safe: true);
// Then
border.ShouldBeSameAs(TableBorder.Simple);
}
}
[Fact]
[Expectation("SimpleHeavyBorder")]
public Task Should_Render_As_Expected()
{
// Given
var console = new TestConsole();
var table = Fixture.GetTable().SimpleHeavyBorder();
// When
console.Write(table);
// Then
return Verifier.Verify(console.Output);
}
}
|
TheSafeGetBorderMethod
|
csharp
|
dotnet__aspnetcore
|
src/Servers/Kestrel/Transport.NamedPipes/test/WebHostTests.cs
|
{
"start": 865,
"end": 3156
}
|
public class ____ : LoggedTest
{
[ConditionalFact]
[OSSkipCondition(OperatingSystems.Windows, SkipReason = "Test expects not supported error. Skip Windows because named pipes supports Windows.")]
public async Task ListenNamedPipeEndpoint_NonWindowsOperatingSystem_ErrorAsync()
{
// Arrange
var builder = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(o =>
{
o.ListenNamedPipe("Pipename");
})
.Configure(app =>
{
app.Run(async context =>
{
await context.Response.WriteAsync("hello, world");
});
});
});
using var host = builder.Build();
// Act
var ex = await Assert.ThrowsAsync<PlatformNotSupportedException>(() => host.StartAsync());
// Assert
Assert.Equal("Named pipes transport requires a Windows operating system.", ex.Message);
}
[Fact]
public async Task ListenNamedPipeEndpoint_CustomNamedPipeEndpointTransport()
{
// Arrange
var transport = new TestConnectionListenerFactory();
var builder = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(o =>
{
o.ListenNamedPipe("Pipename");
})
.Configure(app =>
{
app.Run(async context =>
{
await context.Response.WriteAsync("hello, world");
});
});
webHostBuilder.ConfigureServices(services =>
{
services.AddSingleton<IConnectionListenerFactory>(transport);
});
});
using var host = builder.Build();
// Act
await host.StartAsync();
await host.StopAsync();
// Assert
Assert.Equal("Pipename", transport.BoundEndPoint.PipeName);
}
|
WebHostTests
|
csharp
|
EventStore__EventStore
|
src/SchemaRegistry/KurrentDB.SchemaRegistry.Tests/Modules/Schemas/Validators/ChangeSchemaCompatibilityModeRequestValidatorTests.cs
|
{
"start": 401,
"end": 2086
}
|
public class ____ {
// Faker Faker { get; } = new();
//
// [Test]
// public void validate_with_accepted_values_should_be_valid() {
// var request = new ChangeSchemaCompatibilityModeRequest {
// SchemaName = Faker.Random.AlphaNumeric(10),
// Compatibility = Faker.Random.Enum(CompatibilityMode.Undefined)
// };
//
// var result = Instance.Validate(request);
//
// result.IsValid.Should().BeTrue();
// result.Errors.Should().BeEmpty();
// }
//
// [Test, InvalidSchemaVersionNameTestCases]
// public void validate_with_empty_name_should_not_be_valid(string name) {
// var request = new ChangeSchemaCompatibilityModeRequest {
// SchemaName = name,
// Compatibility = Faker.Random.Enum(CompatibilityMode.Undefined)
// };
//
// var result = Instance.Validate(request);
//
// result.IsValid.Should().BeFalse();
// result.Errors.Should().Contain(v => v.PropertyName == nameof(ChangeSchemaCompatibilityModeRequest.SchemaName));
// }
//
// [Test]
// public void validate_with_invalid_compatibility_mode_should_not_be_valid() {
// var request = new ChangeSchemaCompatibilityModeRequest {
// SchemaName = Faker.Random.AlphaNumeric(10),
// Compatibility = CompatibilityMode.Undefined
// };
//
// var result = Instance.Validate(request);
//
// result.IsValid.Should().BeFalse();
// result.Errors.Should().Contain(v => v.PropertyName == nameof(ChangeSchemaCompatibilityModeRequest.Compatibility));
// }
//
//
|
ChangeSchemaCompatibilityModeRequestValidatorTests
|
csharp
|
dotnet__maui
|
src/Controls/tests/BindingSourceGen.UnitTests/BindingRepresentationGenTests.cs
|
{
"start": 2261,
"end": 4407
}
|
class ____
{
public Button? Button { get; set; }
}
""";
var codeGeneratorResult = SourceGenHelpers.Run(source);
var expectedBinding = new BindingInvocationDescription(
new InterceptableLocationRecord(1, "serializedData"),
new SimpleLocation(@"Path\To\Program.cs", 3, 7),
new TypeDescription("global::Foo"),
new TypeDescription("int", IsValueType: true, IsNullable: true),
new EquatableArray<IPathPart>([
new MemberAccess("Button"),
new ConditionalAccess(new MemberAccess("Text")),
new ConditionalAccess(new MemberAccess("Length", IsValueType: true)),
]),
SetterOptions: new(IsWritable: false),
NullableContextEnabled: true,
MethodType: InterceptedMethodType.SetBinding);
AssertExtensions.BindingsAreEqual(expectedBinding, codeGeneratorResult);
}
[Fact]
public void GenerateBindingWithNullableReferenceSourceWhenNullableEnabled()
{
var source = """
using Microsoft.Maui.Controls;
var label = new Label();
label.SetBinding(Label.RotationProperty, static (Button? b) => b?.Text?.Length);
""";
var codeGeneratorResult = SourceGenHelpers.Run(source);
var expectedBinding = new BindingInvocationDescription(
new InterceptableLocationRecord(1, "serializedData"),
new SimpleLocation(@"Path\To\Program.cs", 3, 7),
new TypeDescription("global::Microsoft.Maui.Controls.Button", IsNullable: true),
new TypeDescription("int", IsValueType: true, IsNullable: true),
new EquatableArray<IPathPart>([
new ConditionalAccess(new MemberAccess("Text")),
new ConditionalAccess(new MemberAccess("Length", IsValueType: true)),
]),
SetterOptions: new(IsWritable: false),
NullableContextEnabled: true,
MethodType: InterceptedMethodType.SetBinding);
AssertExtensions.BindingsAreEqual(expectedBinding, codeGeneratorResult);
}
[Fact]
public void GenerateBindingWithNullableValueTypeWhenNullableEnabled()
{
var source = """
using Microsoft.Maui.Controls;
var label = new Label();
label.SetBinding(Label.RotationProperty, static (Foo f) => f.Value);
|
Foo
|
csharp
|
dotnet__maui
|
src/Controls/tests/Core.UnitTests/StyleSheets/BaseClassSelectorTests.cs
|
{
"start": 308,
"end": 2976
}
|
public class ____
{
IStyleSelectable Page;
IStyleSelectable StackLayout => Page.Children.First();
IStyleSelectable Label0 => StackLayout.Children.First();
IStyleSelectable Label1 => AbsoluteLayout0.Children.First();
IStyleSelectable CustomLabel0 => StackLayout.Children.Skip(1).First();
IStyleSelectable CustomLabel1 => AbsoluteLayout0.Children.Skip(1).First();
IStyleSelectable AbsoluteLayout0 => StackLayout.Children.Skip(2).First();
public BaseClassSelectorTests()
{
Page = new MockStylable
{
NameAndBases = new[] { "Page", "Layout", "VisualElement" },
Children = new List<IStyleSelectable> {
new MockStylable {
NameAndBases = new[] { "StackLayout", "Layout", "VisualElement" },
Children = new List<IStyleSelectable> {
new MockStylable {NameAndBases = new[] { "Label", "VisualElement" }, Classes = new[]{"test"}}, //Label0
new MockStylable {NameAndBases = new[] { "CustomLabel", "Label", "VisualElement" }}, //CustomLabel0
new MockStylable { //AbsoluteLayout0
NameAndBases = new[] { "AbsoluteLayout", "Layout", "VisualElement" },
Classes = new[]{"test"},
Children = new List<IStyleSelectable> {
new MockStylable {NameAndBases = new[] { "Label", "VisualElement" }, Classes = new[]{"test"}}, //Label1
new MockStylable {NameAndBases = new[] { "CustomLabel", "Label", "VisualElement" }, Classes = new[]{"test"}}, //CustomLabel1
}
}
}
}
}
};
SetParents(Page);
}
void SetParents(IStyleSelectable stylable, IStyleSelectable parent = null)
{
((MockStylable)stylable).Parent = parent;
if (stylable.Children == null)
return;
foreach (var s in stylable.Children)
SetParents(s, stylable);
}
[Theory]
[InlineData("stacklayout label", true, true, false, false, false)]
[InlineData("stacklayout>label", true, false, false, false, false)]
[InlineData("stacklayout ^label", true, true, true, true, false)]
[InlineData("stacklayout>^label", true, false, true, false, false)]
public void TestCase(string selectorString, bool label0match, bool label1match, bool customLabel0match, bool customLabel1match, bool absoluteLayout0match)
{
var selector = Selector.Parse(new CssReader(new StringReader(selectorString)));
Assert.Equal(label0match, selector.Matches(Label0));
Assert.Equal(label1match, selector.Matches(Label1));
Assert.Equal(customLabel0match, selector.Matches(CustomLabel0));
Assert.Equal(customLabel1match, selector.Matches(CustomLabel1));
Assert.Equal(absoluteLayout0match, selector.Matches(AbsoluteLayout0));
}
}
}
|
BaseClassSelectorTests
|
csharp
|
fluentassertions__fluentassertions
|
Src/FluentAssertions/Formatting/Formatter.cs
|
{
"start": 418,
"end": 7249
}
|
public static class ____
{
#region Private Definitions
private static readonly List<IValueFormatter> CustomFormatters = [];
private static readonly List<IValueFormatter> DefaultFormatters =
[
new PassthroughValueFormatter(),
new XmlReaderValueFormatter(),
new XmlNodeFormatter(),
new AttributeBasedFormatter(),
new AggregateExceptionValueFormatter(),
new XDocumentValueFormatter(),
new XElementValueFormatter(),
new XAttributeValueFormatter(),
new PropertyInfoFormatter(),
new MethodInfoFormatter(),
new NullValueFormatter(),
new GuidValueFormatter(),
new DateTimeOffsetValueFormatter(),
#if NET6_0_OR_GREATER
new DateOnlyValueFormatter(),
new TimeOnlyValueFormatter(),
new JsonNodeFormatter(),
#endif
new TimeSpanValueFormatter(),
new Int32ValueFormatter(),
new Int64ValueFormatter(),
new DoubleValueFormatter(),
new SingleValueFormatter(),
new DecimalValueFormatter(),
new ByteValueFormatter(),
new UInt32ValueFormatter(),
new UInt64ValueFormatter(),
new Int16ValueFormatter(),
new UInt16ValueFormatter(),
new SByteValueFormatter(),
new StringValueFormatter(),
new TaskFormatter(),
new PredicateLambdaExpressionValueFormatter(),
new ExpressionValueFormatter(),
new ExceptionValueFormatter(),
new MultidimensionalArrayFormatter(),
new DictionaryValueFormatter(),
new EnumerableValueFormatter(),
new EnumValueFormatter(),
new DefaultValueFormatter()
];
/// <summary>
/// Is used to detect recursive calls by <see cref="IValueFormatter"/> implementations.
/// </summary>
[ThreadStatic]
private static bool isReentry;
#endregion
/// <summary>
/// A list of objects responsible for formatting the objects represented by placeholders.
/// </summary>
public static IEnumerable<IValueFormatter> Formatters =>
AssertionScope.Current.FormattingOptions.ScopedFormatters
.Concat(CustomFormatters)
.Concat(DefaultFormatters);
/// <summary>
/// Returns a human-readable representation of a particular object.
/// </summary>
/// <param name="value">The value for which to create a <see cref="string"/>.</param>
/// <param name="options">
/// Indicates whether the formatter should use line breaks when the specific <see cref="IValueFormatter"/> supports it.
/// </param>
/// <returns>
/// A <see cref="string" /> that represents this instance.
/// </returns>
public static string ToString(object value, FormattingOptions options = null)
{
options ??= new FormattingOptions();
try
{
if (isReentry)
{
throw new InvalidOperationException(
$"Use the {nameof(FormatChild)} delegate inside a {nameof(IValueFormatter)} to recursively format children");
}
isReentry = true;
var graph = new ObjectGraph(value);
var context = new FormattingContext
{
UseLineBreaks = options.UseLineBreaks
};
FormattedObjectGraph output = new(options.MaxLines);
try
{
Format(value, output, context,
(path, childValue, childOutput)
=> FormatChild(path, childValue, childOutput, context, options, graph));
}
catch (MaxLinesExceededException)
{
}
return output.ToString();
}
finally
{
isReentry = false;
}
}
[SuppressMessage("Maintainability", "AV1561:Signature contains too many parameters")]
private static void FormatChild(string path, object value, FormattedObjectGraph output, FormattingContext context,
FormattingOptions options, ObjectGraph graph)
{
try
{
Guard.ThrowIfArgumentIsNullOrEmpty(path, nameof(path), "Formatting a child value requires a path");
if (!graph.TryPush(path, value))
{
output.AddFragment($"{{Cyclic reference to type {value.GetType()} detected}}");
}
else if (graph.Depth > options.MaxDepth)
{
output.AddLine($"Maximum recursion depth of {options.MaxDepth} was reached. " +
$" Increase {nameof(FormattingOptions.MaxDepth)} on {nameof(AssertionScope)} or {nameof(AssertionConfiguration)} to get more details.");
}
else
{
using (output.WithIndentation())
{
Format(value, output, context, (childPath, childValue, nestedOutput) =>
FormatChild(childPath, childValue, nestedOutput, context, options, graph));
}
}
}
finally
{
graph.Pop();
}
}
private static void Format(object value, FormattedObjectGraph output, FormattingContext context, FormatChild formatChild)
{
IValueFormatter firstFormatterThatCanHandleValue = Formatters.First(f => f.CanHandle(value));
firstFormatterThatCanHandleValue.Format(value, output, context, formatChild);
}
/// <summary>
/// Removes a custom formatter that was previously added through <see cref="Formatter.AddFormatter"/>.
/// </summary>
/// <remarks>
/// This method is not thread-safe and should not be invoked from within a unit test.
/// See the <see href="https://fluentassertions.com/extensibility/#thread-safety">docs</see> on how to safely use it.
/// </remarks>
public static void RemoveFormatter(IValueFormatter formatter)
{
CustomFormatters.Remove(formatter);
}
/// <summary>
/// Ensures a custom formatter is included in the chain, just before the default formatter is executed.
/// </summary>
/// <remarks>
/// This method is not thread-safe and should not be invoked from within a unit test.
/// See the <see href="https://fluentassertions.com/extensibility/#thread-safety">docs</see> on how to safely use it.
/// </remarks>
public static void AddFormatter(IValueFormatter formatter)
{
if (!CustomFormatters.Contains(formatter))
{
CustomFormatters.Insert(0, formatter);
}
}
/// <summary>
/// Tracks the objects that were formatted as well as the path in the object graph of
/// that object.
/// </summary>
/// <remarks>
/// Is used to detect the maximum recursion depth as well as cyclic references in the graph.
/// </remarks>
|
Formatter
|
csharp
|
unoplatform__uno
|
src/Uno.UWP/Devices/Sensors/Magnetometer.Android.cs
|
{
"start": 153,
"end": 1657
}
|
public partial class ____
{
private Sensor? _sensor;
private uint _reportInterval = SensorHelpers.UiReportingInterval;
private MagnetometerListener? _listener;
/// <summary>
/// Gets or sets the current report interval for the magnetometer.
/// </summary>
public uint ReportInterval
{
get => _reportInterval;
set
{
if (_reportInterval == value)
{
return;
}
lock (_readingChangedWrapper.SyncLock)
{
_reportInterval = value;
if (_readingChangedWrapper.Event != null)
{
//restart reading to apply interval
StopReading();
StartReading();
}
}
}
}
private static Magnetometer? TryCreateInstance()
{
var sensorManager = SensorHelpers.GetSensorManager();
var sensor = sensorManager.GetDefaultSensor(Android.Hardware.SensorType.MagneticField);
return sensor == null ? null : new();
}
private void StartReading()
{
var sensorManager = SensorHelpers.GetSensorManager();
_sensor = sensorManager.GetDefaultSensor(Android.Hardware.SensorType.MagneticField);
_listener = new MagnetometerListener(this);
SensorHelpers.GetSensorManager().RegisterListener(
_listener,
_sensor,
(SensorDelay)(_reportInterval * 1000));
}
private void StopReading()
{
if (_listener != null)
{
SensorHelpers.GetSensorManager().UnregisterListener(_listener, _sensor);
_listener.Dispose();
_listener = null;
}
_sensor?.Dispose();
_sensor = null;
}
|
Magnetometer
|
csharp
|
NSubstitute__NSubstitute
|
tests/NSubstitute.Acceptance.Specs/EventRaising.cs
|
{
"start": 13723,
"end": 15141
}
|
public interface ____
{
event Action ActionEvent;
event Action<int> ActionEventWithOneArg;
event VoidDelegateWithEventArgs DelegateEventWithEventArgs;
event VoidDelegateWithoutArgs DelegateEventWithoutArgs;
event VoidDelegateWithAnArg DelegateEventWithAnArg;
event VoidDelegateWithMultipleArgs DelegateEventWithMultipleArgs;
event FuncDelegateWithoutArgs FuncDelegate;
event FuncDelegateWithArgs FuncDelegateWithArgs;
event EventHandler StandardEventHandler;
event EventHandler<EventArgs> StandardGenericEventHandler;
event EventHandler<CustomEventArgs> EventHandlerWithCustomArgs;
event EventHandler<CustomEventArgsWithNoDefaultCtor> EventHandlerWithCustomArgsAndNoDefaultCtor;
event CustomEventThatDoesNotInheritFromEventHandler CustomEventThatDoesNotInheritFromEventHandler;
}
public delegate void VoidDelegateWithoutArgs();
public delegate void VoidDelegateWithEventArgs(object sender, EventArgs args);
public delegate void VoidDelegateWithAnArg(int arg);
public delegate void VoidDelegateWithMultipleArgs(int intArg, string stringArg);
public delegate int FuncDelegateWithoutArgs();
public delegate int FuncDelegateWithArgs(int intArg, string stringArg);
public delegate void CustomEventThatDoesNotInheritFromEventHandler(object sender, CustomEventArgs args);
|
IEventSamples
|
csharp
|
microsoft__garnet
|
test/Garnet.test/GarnetServerConfigTests.cs
|
{
"start": 569,
"end": 59842
}
|
public class ____
{
[Test]
public void DefaultConfigurationOptionsCoverage()
{
string json;
var streamProvider = StreamProviderFactory.GetStreamProvider(FileLocationType.EmbeddedResource, null, Assembly.GetExecutingAssembly());
using (var stream = streamProvider.Read(ServerSettingsManager.DefaultOptionsEmbeddedFileName))
{
using (var streamReader = new StreamReader(stream))
{
json = streamReader.ReadToEnd();
}
}
// Deserialize default.conf to get all defined default options
Dictionary<string, object> jsonSettings = [];
var jsonSerializerOptions = new JsonSerializerOptions
{
ReadCommentHandling = JsonCommentHandling.Skip,
NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString,
AllowTrailingCommas = true,
};
try
{
jsonSettings = JsonSerializer.Deserialize<Dictionary<string, object>>(json, jsonSerializerOptions);
}
catch (Exception e)
{
Assert.Fail($"Unable to deserialize JSON from {ServerSettingsManager.DefaultOptionsEmbeddedFileName}. Exception: {e.Message}{Environment.NewLine}{e.StackTrace}");
}
// Check that all properties in Options have a default value in defaults.conf
ClassicAssert.IsNotNull(jsonSettings);
foreach (var property in typeof(Options).GetProperties().Where(pi =>
pi.GetCustomAttribute<OptionAttribute>() != null &&
pi.GetCustomAttribute<JsonIgnoreAttribute>() == null))
{
ClassicAssert.Contains(property.Name, jsonSettings.Keys);
}
}
[Test]
public void OptionsDefaultAttributeUsage()
{
// Verify that there are no usages of the OptionsAttribute.Default property (all default values should be set in defaults.conf)
// Note that this test will not fail if the user is setting the Default property to the type's default value (yet can still cause an issue if done).
var propUsages = new List<string>();
foreach (var prop in typeof(Options).GetProperties())
{
var ignoreAttr = prop.GetCustomAttributes(typeof(JsonIgnoreAttribute)).FirstOrDefault();
if (ignoreAttr != null)
continue;
var optionAttr = (OptionAttribute)prop.GetCustomAttributes(typeof(OptionAttribute)).FirstOrDefault();
if (optionAttr == null)
continue;
if (optionAttr.Default != default)
{
propUsages.Add(prop.Name);
}
}
ClassicAssert.IsEmpty(propUsages,
$"Properties in {typeof(Options)} should not use {nameof(OptionAttribute)}.{nameof(OptionAttribute.Default)}. All default values should be specified in defaults.conf.");
}
[Test]
public void ImportExportConfigLocal()
{
TestUtils.DeleteDirectory(TestUtils.MethodTestDir, wait: true);
string dir = TestUtils.MethodTestDir;
string configPath = $"{dir}\\test1.conf";
// Help
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(["--help"], out var options, out var invalidOptions, out _, out var exitGracefully, silentMode: true);
ClassicAssert.IsFalse(parseSuccessful);
ClassicAssert.IsTrue(exitGracefully);
// Version
parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(["--version"], out options, out invalidOptions, out _, out exitGracefully, silentMode: true);
ClassicAssert.IsFalse(parseSuccessful);
ClassicAssert.IsTrue(exitGracefully);
// No import path, no command line args
// Check values match those on defaults.conf
parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(null, out options, out invalidOptions, out var optionsJson, out exitGracefully, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(invalidOptions.Count, 0);
ClassicAssert.AreEqual("32m", options.PageSize);
ClassicAssert.AreEqual("16g", options.MemorySize);
var nonDefaultOptions = JsonSerializer.Deserialize<Dictionary<string, object>>(optionsJson);
ClassicAssert.IsEmpty(nonDefaultOptions);
// No import path, include command line args, export to file
// Check values from command line override values from defaults.conf
static string GetFullExtensionBinPath(string testProjectName) => Path.GetFullPath(testProjectName, TestUtils.RootTestsProjectPath);
var binPaths = new[] { GetFullExtensionBinPath("Garnet.test"), GetFullExtensionBinPath("Garnet.test.cluster") };
var modules = new[] { Assembly.GetExecutingAssembly().Location };
var args = new[] { "--config-export-path", configPath, "-p", "4m", "-m", "128m", "-s", "2g", "--index", "128m", "--recover", "--port", "53", "--reviv-obj-bin-record-count", "2", "--reviv-fraction", "0.5", "--reviv-bin-record-counts", "1,2,3", "--extension-bin-paths", string.Join(',', binPaths), "--loadmodulecs", string.Join(',', modules) };
parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out options, out invalidOptions, out optionsJson, out exitGracefully, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(invalidOptions.Count, 0);
ClassicAssert.AreEqual("4m", options.PageSize);
ClassicAssert.AreEqual("128m", options.MemorySize);
ClassicAssert.AreEqual("2g", options.SegmentSize);
ClassicAssert.AreEqual(53, options.Port);
ClassicAssert.AreEqual(2, options.RevivObjBinRecordCount);
ClassicAssert.AreEqual(0.5, options.RevivifiableFraction);
CollectionAssert.AreEqual(new[] { 1, 2, 3 }, options.RevivBinRecordCounts);
ClassicAssert.IsTrue(options.Recover);
ClassicAssert.IsTrue(File.Exists(configPath));
CollectionAssert.AreEqual(binPaths, options.ExtensionBinPaths);
CollectionAssert.AreEqual(modules, options.LoadModuleCS);
// Validate non-default configuration options
nonDefaultOptions = JsonSerializer.Deserialize<Dictionary<string, object>>(optionsJson);
ClassicAssert.AreEqual(10, nonDefaultOptions.Count);
ClassicAssert.IsTrue(nonDefaultOptions.ContainsKey(nameof(Options.PageSize)));
ClassicAssert.AreEqual("4m", ((JsonElement)nonDefaultOptions[nameof(Options.PageSize)]).GetString());
ClassicAssert.IsTrue(nonDefaultOptions.ContainsKey(nameof(Options.Port)));
ClassicAssert.AreEqual(53, ((JsonElement)nonDefaultOptions[nameof(Options.Port)]).GetInt32());
ClassicAssert.IsTrue(nonDefaultOptions.ContainsKey(nameof(Options.RevivifiableFraction)));
ClassicAssert.AreEqual(0.5, ((JsonElement)nonDefaultOptions[nameof(Options.RevivifiableFraction)]).GetDouble());
ClassicAssert.IsTrue(nonDefaultOptions.ContainsKey(nameof(Options.RevivBinRecordCounts)));
ClassicAssert.AreEqual(new[] { 1, 2, 3 },
((JsonElement)nonDefaultOptions[nameof(Options.RevivBinRecordCounts)]).EnumerateArray()
.Select(i => i.GetInt32()));
ClassicAssert.IsTrue(nonDefaultOptions.ContainsKey(nameof(Options.Recover)));
ClassicAssert.AreEqual(true, ((JsonElement)nonDefaultOptions[nameof(Options.Recover)]).GetBoolean());
ClassicAssert.IsTrue(nonDefaultOptions.ContainsKey(nameof(Options.LoadModuleCS)));
ClassicAssert.AreEqual(modules,
((JsonElement)nonDefaultOptions[nameof(Options.LoadModuleCS)]).EnumerateArray()
.Select(m => m.GetString()));
// Import from previous export command, no command line args
// Check values from import path override values from default.conf
args = ["--config-import-path", configPath];
parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out options, out invalidOptions, out optionsJson, out exitGracefully, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(invalidOptions.Count, 0);
ClassicAssert.IsTrue(options.PageSize == "4m");
ClassicAssert.IsTrue(options.MemorySize == "128m");
CollectionAssert.AreEqual(new[] { 1, 2, 3 }, options.RevivBinRecordCounts);
CollectionAssert.AreEqual(binPaths, options.ExtensionBinPaths);
CollectionAssert.AreEqual(modules, options.LoadModuleCS);
// Validate non-default configuration options
nonDefaultOptions = JsonSerializer.Deserialize<Dictionary<string, object>>(optionsJson);
ClassicAssert.AreEqual(10, nonDefaultOptions.Count);
ClassicAssert.IsTrue(nonDefaultOptions.ContainsKey(nameof(Options.PageSize)));
ClassicAssert.AreEqual("4m", ((JsonElement)nonDefaultOptions[nameof(Options.PageSize)]).GetString());
// Import from previous export command, include command line args, export to file
// Check values from import path override values from default.conf, and values from command line override values from default.conf and import path
binPaths = [GetFullExtensionBinPath("Garnet.test")];
args = ["--config-import-path", configPath, "-p", "12m", "-s", "1g", "--recover", "false", "--index", "256m", "--port", "0", "--no-obj", "--aof", "--reviv-bin-record-counts", "4,5", "--extension-bin-paths", string.Join(',', binPaths)];
parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out options, out invalidOptions, out optionsJson, out exitGracefully, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(invalidOptions.Count, 0);
ClassicAssert.AreEqual("12m", options.PageSize);
ClassicAssert.AreEqual("128m", options.MemorySize);
ClassicAssert.AreEqual("1g", options.SegmentSize);
ClassicAssert.AreEqual(0, options.Port);
ClassicAssert.IsFalse(options.Recover);
ClassicAssert.IsTrue(options.DisableObjects);
ClassicAssert.IsTrue(options.EnableAOF);
CollectionAssert.AreEqual(new[] { 4, 5 }, options.RevivBinRecordCounts);
CollectionAssert.AreEqual(binPaths, options.ExtensionBinPaths);
// Validate non-default configuration options
nonDefaultOptions = JsonSerializer.Deserialize<Dictionary<string, object>>(optionsJson);
ClassicAssert.AreEqual(11, nonDefaultOptions.Count);
ClassicAssert.IsTrue(nonDefaultOptions.ContainsKey(nameof(Options.PageSize)));
ClassicAssert.AreEqual("12m", ((JsonElement)nonDefaultOptions[nameof(Options.PageSize)]).GetString());
ClassicAssert.IsTrue(nonDefaultOptions.ContainsKey(nameof(Options.Port)));
ClassicAssert.AreEqual(0, ((JsonElement)nonDefaultOptions[nameof(Options.Port)]).GetInt32());
ClassicAssert.IsTrue(nonDefaultOptions.ContainsKey(nameof(Options.IndexSize)));
ClassicAssert.AreEqual("256m", ((JsonElement)nonDefaultOptions[nameof(Options.IndexSize)]).GetString());
ClassicAssert.IsTrue(nonDefaultOptions.ContainsKey(nameof(Options.RevivBinRecordCounts)));
ClassicAssert.AreEqual(new[] { 4, 5 },
((JsonElement)nonDefaultOptions[nameof(Options.RevivBinRecordCounts)]).EnumerateArray()
.Select(i => i.GetInt32()));
ClassicAssert.IsFalse(nonDefaultOptions.ContainsKey(nameof(Options.Recover)));
ClassicAssert.IsTrue(nonDefaultOptions.ContainsKey(nameof(Options.DisableObjects)));
ClassicAssert.IsTrue(((JsonElement)nonDefaultOptions[nameof(Options.DisableObjects)]).GetBoolean());
// No import path, include command line args
// Check that all invalid options flagged
args = ["--bind", "1.1.1.257 127.0.0.1 -::1", "-m", "12mg", "--port", "-1", "--mutable-percent", "101", "--acl-file", "nx_dir/nx_file.txt", "--tls", "--reviv-fraction", "1.1", "--cert-file-name", "testcert.crt"];
parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out options, out invalidOptions, out _, out exitGracefully, silentMode: true);
ClassicAssert.IsFalse(parseSuccessful);
ClassicAssert.IsFalse(exitGracefully);
ClassicAssert.IsNull(options);
ClassicAssert.AreEqual(7, invalidOptions.Count);
ClassicAssert.IsTrue(invalidOptions.Contains(nameof(Options.Address)));
ClassicAssert.IsTrue(invalidOptions.Contains(nameof(Options.MemorySize)));
ClassicAssert.IsTrue(invalidOptions.Contains(nameof(Options.Port)));
ClassicAssert.IsTrue(invalidOptions.Contains(nameof(Options.MutablePercent)));
ClassicAssert.IsTrue(invalidOptions.Contains(nameof(Options.AclFile)));
ClassicAssert.IsTrue(invalidOptions.Contains(nameof(Options.RevivifiableFraction)));
ClassicAssert.IsTrue(invalidOptions.Contains(nameof(Options.CertFileName)));
TestUtils.DeleteDirectory(TestUtils.MethodTestDir);
}
[Test]
public void ImportExportRedisConfigLocal()
{
TestUtils.DeleteDirectory(TestUtils.MethodTestDir, wait: true);
var dir = TestUtils.MethodTestDir;
var garnetConfigPath = $"{dir}\\test1.conf";
var redisConfigPath = $"redis.conf";
// Import from redis.conf file, no command line args
// Check values from import path override values from default.conf
var args = new[] { "--config-import-path", redisConfigPath, "--config-import-format", "RedisConf" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out var invalidOptions, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(invalidOptions.Count, 0);
ClassicAssert.AreEqual("127.0.0.1 -::1", options.Address);
ClassicAssert.AreEqual(CommandLineBooleanOption.No, options.ProtectedMode);
ClassicAssert.AreEqual(ConnectionProtectionOption.Local, options.EnableDebugCommand);
ClassicAssert.AreEqual(ConnectionProtectionOption.Yes, options.EnableModuleCommand);
ClassicAssert.AreEqual(6379, options.Port);
ClassicAssert.AreEqual("20gb", options.MemorySize);
ClassicAssert.AreEqual("./garnet-log", options.FileLogger);
ClassicAssert.AreEqual("./", options.CheckpointDir);
ClassicAssert.IsTrue(options.EnableCluster);
ClassicAssert.AreEqual("foobared", options.Password);
ClassicAssert.AreEqual(4, options.ThreadPoolMinThreads);
ClassicAssert.AreEqual(15000, options.ClusterTimeout);
ClassicAssert.AreEqual(LogLevel.Information, options.LogLevel);
ClassicAssert.AreEqual(10, options.ReplicaSyncDelayMs);
ClassicAssert.IsTrue(options.EnableTLS);
ClassicAssert.IsTrue(options.ClientCertificateRequired);
ClassicAssert.AreEqual("testcert.pfx", options.CertFileName);
ClassicAssert.AreEqual("placeholder", options.CertPassword);
ClassicAssert.AreEqual(10000, options.SlowLogThreshold);
ClassicAssert.AreEqual(128, options.SlowLogMaxEntries);
ClassicAssert.AreEqual(32, options.MaxDatabases);
// Import from redis.conf file, include command line args
// Check values from import path override values from default.conf, and values from command line override values from default.conf and import path
args = ["--config-import-path", redisConfigPath, "--config-import-format", "RedisConf", "--config-export-path", garnetConfigPath, "-p", "12m", "--tls", "false", "--minthreads", "6", "--client-certificate-required", "true", "--max-databases", "64"];
parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out options, out invalidOptions, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(invalidOptions.Count, 0);
ClassicAssert.AreEqual("12m", options.PageSize);
ClassicAssert.AreEqual("20gb", options.MemorySize);
ClassicAssert.AreEqual("1g", options.SegmentSize);
ClassicAssert.AreEqual(6, options.ThreadPoolMinThreads);
ClassicAssert.AreEqual(10, options.ReplicaSyncDelayMs);
ClassicAssert.IsFalse(options.EnableTLS);
ClassicAssert.IsTrue(options.ClientCertificateRequired);
ClassicAssert.AreEqual("testcert.pfx", options.CertFileName);
ClassicAssert.AreEqual("placeholder", options.CertPassword);
ClassicAssert.AreEqual(10000, options.SlowLogThreshold);
ClassicAssert.AreEqual(128, options.SlowLogMaxEntries);
ClassicAssert.AreEqual(64, options.MaxDatabases);
ClassicAssert.IsTrue(File.Exists(garnetConfigPath));
TestUtils.DeleteDirectory(TestUtils.MethodTestDir, wait: true);
}
[Test]
public void ImportExportConfigAzure()
{
if (!TestUtils.IsRunningAzureTests)
{
Assert.Ignore("Azure tests are disabled.");
}
var AzureTestDirectory = $"{TestContext.CurrentContext.Test.MethodName.ToLowerInvariant()}";
var configPath = $"{AzureTestDirectory}/test1.config";
var AzureEmulatedStorageString = "UseDevelopmentStorage=true;";
// Delete blob if exists
var deviceFactory = TestUtils.AzureStorageNamedDeviceFactoryCreator.Create(AzureTestDirectory);
deviceFactory.Delete(new FileDescriptor { directoryName = "" });
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(null, out var options, out var invalidOptions, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(invalidOptions.Count, 0);
ClassicAssert.IsTrue(options.PageSize == "32m");
ClassicAssert.IsTrue(options.MemorySize == "16g");
ClassicAssert.IsNull(options.AzureStorageServiceUri);
ClassicAssert.IsNull(options.AzureStorageManagedIdentity);
ClassicAssert.AreNotEqual(DeviceType.AzureStorage, options.GetDeviceType());
var args = new[] { "--storage-string", AzureEmulatedStorageString, "--use-azure-storage-for-config-export", "true", "--config-export-path", configPath, "-p", "4m", "-m", "128m", "--storage-service-uri", "https://demo.blob.core.windows.net", "--storage-managed-identity", "demo" };
parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out options, out invalidOptions, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(invalidOptions.Count, 0);
ClassicAssert.IsTrue(options.PageSize == "4m");
ClassicAssert.IsTrue(options.MemorySize == "128m");
ClassicAssert.IsTrue(options.AzureStorageServiceUri == "https://demo.blob.core.windows.net");
ClassicAssert.IsTrue(options.AzureStorageManagedIdentity == "demo");
args = ["--storage-string", AzureEmulatedStorageString, "--use-azure-storage-for-config-import", "true", "--config-import-path", configPath];
parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out options, out invalidOptions, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(invalidOptions.Count, 0);
ClassicAssert.IsTrue(options.PageSize == "4m");
ClassicAssert.IsTrue(options.MemorySize == "128m");
ClassicAssert.IsTrue(options.AzureStorageServiceUri == "https://demo.blob.core.windows.net");
ClassicAssert.IsTrue(options.AzureStorageManagedIdentity == "demo");
// Delete blob
deviceFactory.Delete(new FileDescriptor { directoryName = "" });
}
[Test]
public void AzureStorageConfiguration()
{
// missing both storage-string and storage-service-uri
var args = new string[] { "--use-azure-storage", "true" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out var invalidOptions, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(invalidOptions.Count, 0);
Assert.Throws<InvalidAzureConfiguration>(() => options.GetServerOptions());
// valid storage-string
args = ["--use-azure-storage", "--storage-string", "UseDevelopmentStorage=true;"];
parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out options, out invalidOptions, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(invalidOptions.Count, 0);
Assert.DoesNotThrow(() => options.GetServerOptions());
// secure service-uri with managed-identity
args = ["--use-azure-storage", "--storage-service-uri", "https://demo.blob.core.windows.net", "--storage-managed-identity", "demo"];
parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out options, out invalidOptions, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(invalidOptions.Count, 0);
Assert.DoesNotThrow(() => options.GetServerOptions());
// secure service-uri with workload-identity and no managed-identity
args = ["--use-azure-storage", "--storage-service-uri", "https://demo.blob.core.windows.net"];
parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out options, out invalidOptions, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(invalidOptions.Count, 0);
Assert.DoesNotThrow(() => options.GetServerOptions());
// insecure service-uri with managed-identity
args = ["--use-azure-storage", "--storage-service-uri", "http://demo.blob.core.windows.net", "--storage-managed-identity", "demo"];
parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out options, out invalidOptions, out _, out _, silentMode: true);
ClassicAssert.IsFalse(parseSuccessful);
ClassicAssert.AreEqual(invalidOptions.Count, 1);
ClassicAssert.AreEqual(invalidOptions[0], nameof(Options.AzureStorageServiceUri));
// using both storage-string and managed-identity
args = ["--use-azure-storage", "--storage-string", "UseDevelopmentStorage", "--storage-managed-identity", "demo", "--storage-service-uri", "https://demo.blob.core.windows.net"];
parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out options, out invalidOptions, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(invalidOptions.Count, 0);
Assert.Throws<InvalidAzureConfiguration>(() => options.GetServerOptions());
}
[Test]
public void LuaMemoryOptions()
{
// Command line
{
// Defaults to Native with no limit
{
var args = new[] { "--lua" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaMemoryManagementMode.Native, options.LuaMemoryManagementMode);
ClassicAssert.IsNull(options.LuaScriptMemoryLimit);
}
// Native with limit rejected
{
var args = new[] { "--lua", "--lua-script-memory-limit", "10m" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out _, out _, out _, out _, silentMode: true);
ClassicAssert.IsFalse(parseSuccessful);
}
// Tracked with no limit works
{
var args = new[] { "--lua", "--lua-memory-management-mode", "Tracked" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaMemoryManagementMode.Tracked, options.LuaMemoryManagementMode);
ClassicAssert.IsNull(options.LuaScriptMemoryLimit);
}
// Tracked with limit works
{
var args = new[] { "--lua", "--lua-memory-management-mode", "Tracked", "--lua-script-memory-limit", "10m" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaMemoryManagementMode.Tracked, options.LuaMemoryManagementMode);
ClassicAssert.AreEqual("10m", options.LuaScriptMemoryLimit);
}
// Tracked with bad limit rejected
{
var args = new[] { "--lua", "--lua-memory-management-mode", "Tracked", "--lua-script-memory-limit", "10Q" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out _, out _, out _, out _, silentMode: true);
ClassicAssert.IsFalse(parseSuccessful);
}
// Managed with no limit works
{
var args = new[] { "--lua", "--lua-memory-management-mode", "Managed" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaMemoryManagementMode.Managed, options.LuaMemoryManagementMode);
ClassicAssert.IsNull(options.LuaScriptMemoryLimit);
}
// Managed with limit works
{
var args = new[] { "--lua", "--lua-memory-management-mode", "Managed", "--lua-script-memory-limit", "10m" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaMemoryManagementMode.Managed, options.LuaMemoryManagementMode);
ClassicAssert.AreEqual("10m", options.LuaScriptMemoryLimit);
}
// Managed with bad limit rejected
{
var args = new[] { "--lua", "--lua-memory-management-mode", "Managed", "--lua-script-memory-limit", "10Q" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out _, out _, out _, out _, silentMode: true);
ClassicAssert.IsFalse(parseSuccessful);
}
}
// Garnet.conf
{
// Defaults to Native with no limit
{
const string JSON = @"{ ""EnableLua"": true }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaMemoryManagementMode.Native, options.LuaMemoryManagementMode);
ClassicAssert.IsNull(options.LuaScriptMemoryLimit);
}
// Native with limit rejected
{
const string JSON = @"{ ""EnableLua"": true, ""LuaScriptMemoryLimit"": ""10m"" }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out _, out _, out _);
ClassicAssert.IsFalse(parseSuccessful);
}
// Tracked with no limit works
{
const string JSON = @"{ ""EnableLua"": true, ""LuaMemoryManagementMode"": ""Tracked"" }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaMemoryManagementMode.Tracked, options.LuaMemoryManagementMode);
ClassicAssert.IsNull(options.LuaScriptMemoryLimit);
}
// Tracked with limit works
{
const string JSON = @"{ ""EnableLua"": true, ""LuaMemoryManagementMode"": ""Tracked"", ""LuaScriptMemoryLimit"": ""10m"" }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaMemoryManagementMode.Tracked, options.LuaMemoryManagementMode);
ClassicAssert.AreEqual("10m", options.LuaScriptMemoryLimit);
}
// Tracked with bad limit rejected
{
const string JSON = @"{ ""EnableLua"": true, ""LuaMemoryManagementMode"": ""Tracked"", ""LuaScriptMemoryLimit"": ""10Q"" }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out _, out _, out _);
ClassicAssert.IsFalse(parseSuccessful);
}
// Managed with no limit works
{
const string JSON = @"{ ""EnableLua"": true, ""LuaMemoryManagementMode"": ""Managed"" }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaMemoryManagementMode.Managed, options.LuaMemoryManagementMode);
ClassicAssert.IsNull(options.LuaScriptMemoryLimit);
}
// Managed with limit works
{
const string JSON = @"{ ""EnableLua"": true, ""LuaMemoryManagementMode"": ""Managed"", ""LuaScriptMemoryLimit"": ""10m"" }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaMemoryManagementMode.Managed, options.LuaMemoryManagementMode);
ClassicAssert.AreEqual("10m", options.LuaScriptMemoryLimit);
}
// Managed with bad limit rejected
{
const string JSON = @"{ ""EnableLua"": true, ""LuaMemoryManagementMode"": ""Managed"", ""LuaScriptMemoryLimit"": ""10Q"" }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out _, out _);
ClassicAssert.IsFalse(parseSuccessful);
}
}
}
[Test]
public void LuaTimeoutOptions()
{
// Command line args
{
// No value is accepted
{
var args = new[] { "--lua" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(0, options.LuaScriptTimeoutMs);
}
// Positive accepted
{
var args = new[] { "--lua", "--lua-script-timeout", "10" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(10, options.LuaScriptTimeoutMs);
}
// > 0 and < 10 rejected
for (var ms = 1; ms < 10; ms++)
{
var args = new[] { "--lua", "--lua-script-timeout", ms.ToString() };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out _, out _, out _, out _, silentMode: true);
ClassicAssert.IsFalse(parseSuccessful);
}
// Negative rejected
{
var args = new[] { "--lua", "--lua-script-timeout", "-10" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out _, out _, out _, out _, silentMode: true);
ClassicAssert.IsFalse(parseSuccessful);
}
}
// Garnet.conf
{
// No value is accepted
{
const string JSON = @"{ ""EnableLua"": true }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(0, options.LuaScriptTimeoutMs);
}
// Positive accepted
{
const string JSON = @"{ ""EnableLua"": true, ""LuaScriptTimeoutMs"": 10 }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(10, options.LuaScriptTimeoutMs);
}
// > 0 and < 10 rejected
for (var ms = 1; ms < 10; ms++)
{
var json = $@"{{ ""EnableLua"": true, ""LuaScriptTimeoutMs"": {ms} }}";
var parseSuccessful = TryParseGarnetConfOptions(json, out _, out _, out _);
ClassicAssert.IsFalse(parseSuccessful);
}
// Negative rejected
{
const string JSON = @"{ ""EnableLua"": true, ""LuaScriptTimeoutMs"": -10 }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out _, out _, out _);
ClassicAssert.IsFalse(parseSuccessful);
}
}
}
[Test]
public void LuaLoggingOptions()
{
// Command line args
{
// No value is accepted
{
var args = new[] { "--lua" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaLoggingMode.Enable, options.LuaLoggingMode);
}
// Enable accepted
{
var args = new[] { "--lua", "--lua-logging-mode", "Enable" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaLoggingMode.Enable, options.LuaLoggingMode);
}
// Silent accepted
{
var args = new[] { "--lua", "--lua-logging-mode", "Silent" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaLoggingMode.Silent, options.LuaLoggingMode);
}
// Disable accepted
{
var args = new[] { "--lua", "--lua-logging-mode", "Disable" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaLoggingMode.Disable, options.LuaLoggingMode);
}
// Invalid rejected
{
var args = new[] { "--lua", "--lua-logging-mode", "Foo" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _);
ClassicAssert.IsFalse(parseSuccessful);
}
}
// JSON args
{
// No value is accepted
{
const string JSON = @"{ ""EnableLua"": true }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaLoggingMode.Enable, options.LuaLoggingMode);
}
// Enable accepted
{
const string JSON = @"{ ""EnableLua"": true, ""LuaLoggingMode"": ""Enable"" }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaLoggingMode.Enable, options.LuaLoggingMode);
}
// Silent accepted
{
const string JSON = @"{ ""EnableLua"": true, ""LuaLoggingMode"": ""Silent"" }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaLoggingMode.Silent, options.LuaLoggingMode);
}
// Disable accepted
{
const string JSON = @"{ ""EnableLua"": true, ""LuaLoggingMode"": ""Disable"" }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(LuaLoggingMode.Disable, options.LuaLoggingMode);
}
// Invalid rejected
{
const string JSON = @"{ ""EnableLua"": true, ""LuaLoggingMode"": ""Foo"" }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsFalse(parseSuccessful);
}
}
}
[Test]
public void LuaAllowedFunctions()
{
// Command line args
{
// No value is accepted
{
var args = new[] { "--lua" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(0, options.LuaAllowedFunctions.Count());
}
// One option works
{
var args = new[] { "--lua", "--lua-allowed-functions", "os" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(1, options.LuaAllowedFunctions.Count());
ClassicAssert.IsTrue(options.LuaAllowedFunctions.Contains("os"));
}
// Multiple option works
{
var args = new[] { "--lua", "--lua-allowed-functions", "os,assert,rawget" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(3, options.LuaAllowedFunctions.Count());
ClassicAssert.IsTrue(options.LuaAllowedFunctions.Contains("os"));
ClassicAssert.IsTrue(options.LuaAllowedFunctions.Contains("assert"));
ClassicAssert.IsTrue(options.LuaAllowedFunctions.Contains("rawget"));
}
// Invalid rejected
{
var args = new[] { "--lua", "--lua-allowed-functions" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _);
ClassicAssert.IsFalse(parseSuccessful);
}
}
// JSON args
{
// No value is accepted
{
const string JSON = @"{ ""EnableLua"": true }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(0, options.LuaAllowedFunctions.Count());
}
// One option works
{
const string JSON = @"{ ""EnableLua"": true, ""LuaAllowedFunctions"": [""os""] }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(1, options.LuaAllowedFunctions.Count());
ClassicAssert.IsTrue(options.LuaAllowedFunctions.Contains("os"));
}
// Multiple option works
{
const string JSON = @"{ ""EnableLua"": true, ""LuaAllowedFunctions"": [""os"", ""assert"", ""rawget""] }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.EnableLua);
ClassicAssert.AreEqual(3, options.LuaAllowedFunctions.Count());
ClassicAssert.IsTrue(options.LuaAllowedFunctions.Contains("os"));
ClassicAssert.IsTrue(options.LuaAllowedFunctions.Contains("assert"));
ClassicAssert.IsTrue(options.LuaAllowedFunctions.Contains("rawget"));
}
// Invalid rejected
{
const string JSON = @"{ ""EnableLua"": true, ""LuaAllowedFunctions"": { } }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsFalse(parseSuccessful);
}
}
}
[Test]
public void ClusterReplicationReestablishmentTimeout()
{
// Command line args
{
// No value is accepted
{
var args = Array.Empty<string>();
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(0, options.ClusterReplicationReestablishmentTimeout);
}
// 0 accepted
{
var args = new[] { "--cluster-replication-reestablishment-timeout", "0" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(0, options.ClusterReplicationReestablishmentTimeout);
}
// Positive accepted
{
var args = new[] { "--cluster-replication-reestablishment-timeout", "30" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(30, options.ClusterReplicationReestablishmentTimeout);
}
// Negative rejected
{
var args = new[] { "--cluster-replication-reestablishment-timeout", "-1" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _);
ClassicAssert.IsFalse(parseSuccessful);
}
// Invalid rejected
{
var args = new[] { "--cluster-replication-reestablishment-timeout", "foo" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _);
ClassicAssert.IsFalse(parseSuccessful);
}
}
// JSON args
{
// No value is accepted
{
const string JSON = @"{ }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(0, options.ClusterReplicationReestablishmentTimeout);
}
// 0 accepted
{
const string JSON = @"{ ""ClusterReplicationReestablishmentTimeout"": 0 }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(0, options.ClusterReplicationReestablishmentTimeout);
}
// Positive accepted
{
const string JSON = @"{ ""ClusterReplicationReestablishmentTimeout"": 30 }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(30, options.ClusterReplicationReestablishmentTimeout);
}
// Negative rejected
{
const string JSON = @"{ ""ClusterReplicationReestablishmentTimeout"": -1 }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsFalse(parseSuccessful);
}
// Invalid rejected
{
const string JSON = @"{ ""ClusterReplicationReestablishmentTimeout"": ""foo"" }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsFalse(parseSuccessful);
}
}
}
[Test]
public void ClusterReplicaResumeWithData()
{
// Command line args
{
// Default accepted
{
var args = Array.Empty<string>();
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsFalse(options.ClusterReplicaResumeWithData);
}
// Switch is accepted
{
var args = new[] { "--cluster-replica-resume-with-data" };
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.ClusterReplicaResumeWithData);
}
}
// JSON args
{
// Default accepted
{
const string JSON = @"{ }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsFalse(options.ClusterReplicaResumeWithData);
}
// False is accepted
{
const string JSON = @"{ ""ClusterReplicaResumeWithData"": false }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsFalse(options.ClusterReplicaResumeWithData);
}
// True is accepted
{
const string JSON = @"{ ""ClusterReplicaResumeWithData"": true }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.IsTrue(options.ClusterReplicaResumeWithData);
}
// Invalid rejected
{
const string JSON = @"{ ""ClusterReplicaResumeWithData"": ""foo"" }";
var parseSuccessful = TryParseGarnetConfOptions(JSON, out var options, out var invalidOptions, out var exitGracefully);
ClassicAssert.IsFalse(parseSuccessful);
}
}
}
/// <summary>
/// Import a garnet.conf file with the given contents
/// </summary>
private static bool TryParseGarnetConfOptions(string json, out Options options, out List<string> invalidOptions, out bool exitGracefully)
{
var tempPath = Path.GetTempFileName();
try
{
File.WriteAllText(tempPath, json);
return ServerSettingsManager.TryParseCommandLineArguments(["--config-import-path", tempPath], out options, out invalidOptions, out _, out exitGracefully, silentMode: true);
}
finally
{
try
{
File.Delete(tempPath);
}
catch
{
// Best effort
}
}
}
[Test]
public void UnixSocketPath_CanParseValidPath()
{
string[] args = ["--unixsocket", "./config-parse-test.sock"];
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out _, out _, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
}
[Test]
public void UnixSocketPath_InvalidPathFails()
{
// Socket path directory does not exists
string[] args = ["--unixsocket", "./does-not-exists/config-parse-test.sock"];
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out _, out _, out _, out _, silentMode: true);
ClassicAssert.IsFalse(parseSuccessful);
}
[Test]
public void UnixSocketPermission_CanParseValidPermission()
{
if (OperatingSystem.IsWindows())
return;
string[] args = ["--unixsocketperm", "777"];
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out var options, out _, out _, out _, silentMode: true);
ClassicAssert.IsTrue(parseSuccessful);
ClassicAssert.AreEqual(777, options.UnixSocketPermission);
}
[Test]
public void UnixSocketPermission_InvalidPermissionFails()
{
if (OperatingSystem.IsWindows())
return;
string[] args = ["--unixsocketperm", "888"];
var parseSuccessful = ServerSettingsManager.TryParseCommandLineArguments(args, out _, out _, out _, out _, silentMode: true);
ClassicAssert.IsFalse(parseSuccessful);
}
[Test]
[TestCase(ConnectionProtectionOption.No)]
[TestCase(ConnectionProtectionOption.Local)]
[TestCase(ConnectionProtectionOption.Yes)]
public async Task ConnectionProtectionTest(ConnectionProtectionOption connectionProtectionOption)
{
List<IPAddress> addresses = [IPAddress.IPv6Loopback, IPAddress.Loopback];
var hostname = TestUtils.GetHostName();
var address = Dns.GetHostAddresses(hostname).Where(x => !IPAddress.IsLoopback(x)).FirstOrDefault();
if (address == default)
{
if (connectionProtectionOption == ConnectionProtectionOption.Local)
Assert.Ignore("No nonloopback address");
}
else
{
addresses.Add(address);
}
var endpoints = addresses.Select(address => new IPEndPoint(address, TestUtils.TestPort)).ToArray();
var server = TestUtils.CreateGarnetServer(TestUtils.MethodTestDir, endpoints: endpoints,
enableDebugCommand: connectionProtectionOption);
server.Start();
foreach (var endpoint in endpoints)
{
var shouldfail = connectionProtectionOption == ConnectionProtectionOption.No ||
(!IPAddress.IsLoopback(endpoint.Address) && connectionProtectionOption == ConnectionProtectionOption.Local);
var client = TestUtils.GetGarnetClientSession(endPoint: endpoint);
client.Connect();
try
{
var result = await client.ExecuteAsync("DEBUG", "LOG", "Loopback test");
if (shouldfail)
Assert.Fail("Connection protection should have not allowed the command to run");
else
ClassicAssert.AreEqual("OK", result);
}
catch (Exception ex)
{
if (shouldfail)
ClassicAssert.AreEqual("ERR", ex.Message[0..3]);
else
Assert.Fail("Connection protection should have allowed command from this address");
}
finally
{
client.Dispose();
}
}
server.Dispose();
}
[Test]
public async Task MultiTcpSocketTest()
{
TestUtils.DeleteDirectory(TestUtils.MethodTestDir, wait: true);
var hostname = TestUtils.GetHostName();
var addresses = Dns.GetHostAddresses(hostname);
addresses = [.. addresses, IPAddress.IPv6Loopback, IPAddress.Loopback];
var endpoints = addresses.Distinct().Select(address => new IPEndPoint(address, TestUtils.TestPort)).ToArray();
var server = TestUtils.CreateGarnetServer(TestUtils.MethodTestDir, endpoints: endpoints);
server.Start();
var clients = endpoints.Select(endpoint => TestUtils.GetGarnetClientSession(endPoint: endpoint)).ToArray();
foreach (var client in clients)
{
client.Connect();
var result = await client.ExecuteAsync("PING");
ClassicAssert.AreEqual("PONG", result);
client.Dispose();
}
server.Dispose();
TestUtils.DeleteDirectory(TestUtils.MethodTestDir);
}
}
}
|
GarnetServerConfigTests
|
csharp
|
abpframework__abp
|
templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/MyProjectNameHttpApiHostModule.cs
|
{
"start": 1605,
"end": 8380
}
|
public class ____ : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
var configuration = context.Services.GetConfiguration();
var hostingEnvironment = context.Services.GetHostingEnvironment();
ConfigureConventionalControllers();
ConfigureAuthentication(context, configuration);
ConfigureCache(configuration);
ConfigureVirtualFileSystem(context);
ConfigureDataProtection(context, configuration, hostingEnvironment);
ConfigureDistributedLocking(context, configuration);
ConfigureCors(context, configuration);
ConfigureSwaggerServices(context, configuration);
}
private void ConfigureCache(IConfiguration configuration)
{
Configure<AbpDistributedCacheOptions>(options => { options.KeyPrefix = "MyProjectName:"; });
}
private void ConfigureVirtualFileSystem(ServiceConfigurationContext context)
{
var hostingEnvironment = context.Services.GetHostingEnvironment();
if (hostingEnvironment.IsDevelopment())
{
Configure<AbpVirtualFileSystemOptions>(options =>
{
options.FileSets.ReplaceEmbeddedByPhysical<MyProjectNameDomainSharedModule>(
Path.Combine(hostingEnvironment.ContentRootPath,
$"..{Path.DirectorySeparatorChar}MyCompanyName.MyProjectName.Domain.Shared"));
options.FileSets.ReplaceEmbeddedByPhysical<MyProjectNameDomainModule>(
Path.Combine(hostingEnvironment.ContentRootPath,
$"..{Path.DirectorySeparatorChar}MyCompanyName.MyProjectName.Domain"));
options.FileSets.ReplaceEmbeddedByPhysical<MyProjectNameApplicationContractsModule>(
Path.Combine(hostingEnvironment.ContentRootPath,
$"..{Path.DirectorySeparatorChar}MyCompanyName.MyProjectName.Application.Contracts"));
options.FileSets.ReplaceEmbeddedByPhysical<MyProjectNameApplicationModule>(
Path.Combine(hostingEnvironment.ContentRootPath,
$"..{Path.DirectorySeparatorChar}MyCompanyName.MyProjectName.Application"));
});
}
}
private void ConfigureConventionalControllers()
{
Configure<AbpAspNetCoreMvcOptions>(options =>
{
options.ConventionalControllers.Create(typeof(MyProjectNameApplicationModule).Assembly);
});
}
private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration)
{
context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddAbpJwtBearer(options =>
{
options.Authority = configuration["AuthServer:Authority"];
options.RequireHttpsMetadata = configuration.GetValue<bool>("AuthServer:RequireHttpsMetadata");
options.Audience = "MyProjectName";
});
context.Services.Configure<AbpClaimsPrincipalFactoryOptions>(options =>
{
options.IsDynamicClaimsEnabled = true;
});
}
private static void ConfigureSwaggerServices(ServiceConfigurationContext context, IConfiguration configuration)
{
context.Services.AddAbpSwaggerGenWithOAuth(
configuration["AuthServer:Authority"]!,
new Dictionary<string, string>
{
{"MyProjectName", "MyProjectName API"}
},
options =>
{
options.SwaggerDoc("v1", new OpenApiInfo { Title = "MyProjectName API", Version = "v1" });
options.DocInclusionPredicate((docName, description) => true);
options.CustomSchemaIds(type => type.FullName);
});
}
private void ConfigureDataProtection(
ServiceConfigurationContext context,
IConfiguration configuration,
IWebHostEnvironment hostingEnvironment)
{
var dataProtectionBuilder = context.Services.AddDataProtection().SetApplicationName("MyProjectName");
if (!hostingEnvironment.IsDevelopment())
{
var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]!);
dataProtectionBuilder.PersistKeysToStackExchangeRedis(redis, "MyProjectName-Protection-Keys");
}
}
private void ConfigureDistributedLocking(
ServiceConfigurationContext context,
IConfiguration configuration)
{
context.Services.AddSingleton<IDistributedLockProvider>(sp =>
{
var connection = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]!);
return new RedisDistributedSynchronizationProvider(connection.GetDatabase());
});
}
private void ConfigureCors(ServiceConfigurationContext context, IConfiguration configuration)
{
context.Services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder
.WithOrigins(configuration["App:CorsOrigins"]?
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.Select(o => o.RemovePostFix("/"))
.ToArray() ?? Array.Empty<string>())
.WithAbpExposedHeaders()
.SetIsOriginAllowedToAllowWildcardSubdomains()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
}
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
var app = context.GetApplicationBuilder();
var env = context.GetEnvironment();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAbpRequestLocalization();
app.UseCorrelationId();
app.MapAbpStaticAssets();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
if (MultiTenancyConsts.IsEnabled)
{
app.UseMultiTenancy();
}
app.UseUnitOfWork();
app.UseDynamicClaims();
app.UseAuthorization();
app.UseSwagger();
app.UseAbpSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "MyProjectName API");
var configuration = context.GetConfiguration();
options.OAuthClientId(configuration["AuthServer:SwaggerClientId"]);
options.OAuthScopes("MyProjectName");
});
app.UseAuditing();
app.UseAbpSerilogEnrichers();
app.UseConfiguredEndpoints();
}
}
|
MyProjectNameHttpApiHostModule
|
csharp
|
dotnetcore__FreeSql
|
Examples/base_entity/Program.cs
|
{
"start": 3540,
"end": 3771
}
|
public class ____
{
[Column(IsIdentity = true)]
public int Id { get; set; }
[Column(MapType = typeof(JToken))]
public Customer Customer { get; set; }
}
|
SomeEntity
|
csharp
|
cake-build__cake
|
src/Cake.Core/Scripting/CodeGen/GenericParameterConstraintEmitter.cs
|
{
"start": 2085,
"end": 3257
}
|
struct ____ will return System.ValueType.
// it's not necessarily to emit that as syntax in a generated method
if (constraint == typeof(System.ValueType))
{
continue;
}
tokens.Add(constraint.GetFullName());
}
}
else
{
// if it's declared a struct, we can't use any other constraints (inherits/implements or default ctor)
// special considerations? reference/value
if (paramAttributes.HasFlag(GenericParameterAttributes.ReferenceTypeConstraint))
{
tokens.Add("class");
}
// iterate type constraints
foreach (var constraint in argument.GetTypeInfo().GetGenericParameterConstraints())
{
tokens.Add(constraint.GetFullName());
}
// default constructor has to come last, can't be used in conjunction w/
|
constraint
|
csharp
|
mongodb__mongo-csharp-driver
|
src/MongoDB.Bson/Serialization/Serializers/BsonArraySerializer.cs
|
{
"start": 725,
"end": 3648
}
|
public sealed class ____ : BsonValueSerializerBase<BsonArray>, IBsonArraySerializer
{
// private static fields
private static BsonArraySerializer __instance = new BsonArraySerializer();
// constructors
/// <summary>
/// Initializes a new instance of the BsonArraySerializer class.
/// </summary>
public BsonArraySerializer()
: base(BsonType.Array)
{
}
// public static properties
/// <summary>
/// Gets an instance of the BsonArraySerializer class.
/// </summary>
public static BsonArraySerializer Instance
{
get { return __instance; }
}
// public methods
/// <summary>
/// Deserializes a value.
/// </summary>
/// <param name="context">The deserialization context.</param>
/// <param name="args">The deserialization args.</param>
/// <returns>A deserialized value.</returns>
protected override BsonArray DeserializeValue(BsonDeserializationContext context, BsonDeserializationArgs args)
{
var bsonReader = context.Reader;
bsonReader.ReadStartArray();
var array = new BsonArray();
while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
{
var item = BsonValueSerializer.Instance.Deserialize(context);
array.Add(item);
}
bsonReader.ReadEndArray();
return array;
}
/// <summary>
/// Tries to get the serialization info for the individual items of the array.
/// </summary>
/// <param name="serializationInfo">The serialization information.</param>
/// <returns>
/// <c>true</c> if the serialization info exists; otherwise <c>false</c>.
/// </returns>
public bool TryGetItemSerializationInfo(out BsonSerializationInfo serializationInfo)
{
serializationInfo = new BsonSerializationInfo(
null,
BsonValueSerializer.Instance,
typeof(BsonValue));
return true;
}
// protected methods
/// <summary>
/// Serializes a value.
/// </summary>
/// <param name="context">The serialization context.</param>
/// <param name="args">The serialization args.</param>
/// <param name="value">The object.</param>
protected override void SerializeValue(BsonSerializationContext context, BsonSerializationArgs args, BsonArray value)
{
var bsonWriter = context.Writer;
bsonWriter.WriteStartArray();
for (int i = 0; i < value.Count; i++)
{
BsonValueSerializer.Instance.Serialize(context, value[i]);
}
bsonWriter.WriteEndArray();
}
}
}
|
BsonArraySerializer
|
csharp
|
dotnet__aspnetcore
|
src/OpenApi/src/Transformers/DelegateOpenApiOperationTransformer.cs
|
{
"start": 179,
"end": 810
}
|
internal sealed class ____ : IOpenApiOperationTransformer
{
private readonly Func<OpenApiOperation, OpenApiOperationTransformerContext, CancellationToken, Task> _transformer;
public DelegateOpenApiOperationTransformer(Func<OpenApiOperation, OpenApiOperationTransformerContext, CancellationToken, Task> transformer)
{
_transformer = transformer;
}
public async Task TransformAsync(OpenApiOperation operation, OpenApiOperationTransformerContext context, CancellationToken cancellationToken)
{
await _transformer(operation, context, cancellationToken);
}
}
|
DelegateOpenApiOperationTransformer
|
csharp
|
AvaloniaUI__Avalonia
|
src/Avalonia.Base/Diagnostics/Diagnostic.Consts.cs
|
{
"start": 2233,
"end": 2851
}
|
public static class ____
{
public const string Style = nameof(Style);
public const string SelectorResult = nameof(SelectorResult);
public const string Key = nameof(Key);
public const string ThemeVariant = nameof(ThemeVariant);
public const string Result = nameof(Result);
public const string Activator = nameof(Activator);
public const string IsActive = nameof(IsActive);
public const string Selector = nameof(Selector);
public const string Control = nameof(Control);
public const string RoutedEvent = nameof(RoutedEvent);
}
}
|
Tags
|
csharp
|
nunit__nunit
|
src/NUnitFramework/tests/Attributes/ParameterizedTestFixtureTests.cs
|
{
"start": 2581,
"end": 4893
}
|
public class ____
{
private TestSuite _fixture;
[SetUp]
public void MakeFixture()
{
_fixture = TestBuilder.MakeFixture(typeof(NUnit.TestData.ParameterizedTestFixture));
}
[Test]
public void TopLevelSuiteIsNamedCorrectly()
{
Assert.That(_fixture.Name, Is.EqualTo("ParameterizedTestFixture"));
Assert.That(_fixture.FullName, Is.EqualTo("NUnit.TestData.ParameterizedTestFixture"));
}
[Test]
public void SuiteHasCorrectNumberOfInstances()
{
Assert.That(_fixture.Tests, Has.Count.EqualTo(2));
}
[Test]
public void FixtureInstancesAreNamedCorrectly()
{
var names = new List<string>();
var fullnames = new List<string>();
foreach (Test test in _fixture.Tests)
{
names.Add(test.Name);
fullnames.Add(test.FullName);
}
Assert.That(names, Is.EquivalentTo(new[]
{
"ParameterizedTestFixture(1)", "ParameterizedTestFixture(2)"
}));
Assert.That(fullnames, Is.EquivalentTo(new[]
{
"NUnit.TestData.ParameterizedTestFixture(1)", "NUnit.TestData.ParameterizedTestFixture(2)"
}));
}
[Test]
public void MethodWithoutParamsIsNamedCorrectly()
{
TestSuite instance = (TestSuite)_fixture.Tests[0];
Test? method = TestFinder.Find("MethodWithoutParams", instance, false);
Assert.That(method, Is.Not.Null);
Assert.That(method.FullName, Is.EqualTo(instance.FullName + ".MethodWithoutParams"));
}
[Test]
public void MethodWithParamsIsNamedCorrectly()
{
TestSuite instance = (TestSuite)_fixture.Tests[0];
TestSuite? method = (TestSuite?)TestFinder.Find("MethodWithParams", instance, false);
Assert.That(method, Is.Not.Null);
Test testcase = (Test)method.Tests[0];
Assert.That(testcase.Name, Is.EqualTo("MethodWithParams(10,20)"));
Assert.That(testcase.FullName, Is.EqualTo(instance.FullName + ".MethodWithParams(10,20)"));
}
}
|
ParameterizedTestFixtureNamingTests
|
csharp
|
SixLabors__ImageSharp
|
src/ImageSharp/Processing/Processors/Normalization/GrayscaleLevelsRowOperation{TPixel}.cs
|
{
"start": 541,
"end": 2392
}
|
struct ____<TPixel> : IRowOperation<Vector4>
where TPixel : unmanaged, IPixel<TPixel>
{
private readonly Configuration configuration;
private readonly Rectangle bounds;
private readonly IMemoryOwner<int> histogramBuffer;
private readonly Buffer2D<TPixel> source;
private readonly int luminanceLevels;
[MethodImpl(InliningOptions.ShortMethod)]
public GrayscaleLevelsRowOperation(
Configuration configuration,
Rectangle bounds,
IMemoryOwner<int> histogramBuffer,
Buffer2D<TPixel> source,
int luminanceLevels)
{
this.configuration = configuration;
this.bounds = bounds;
this.histogramBuffer = histogramBuffer;
this.source = source;
this.luminanceLevels = luminanceLevels;
}
/// <inheritdoc/>
[MethodImpl(InliningOptions.ShortMethod)]
public int GetRequiredBufferLength(Rectangle bounds) => bounds.Width;
/// <inheritdoc/>
[MethodImpl(InliningOptions.ShortMethod)]
public void Invoke(int y, Span<Vector4> span)
{
Span<Vector4> vectorBuffer = span.Slice(0, this.bounds.Width);
ref Vector4 vectorRef = ref MemoryMarshal.GetReference(vectorBuffer);
ref int histogramBase = ref MemoryMarshal.GetReference(this.histogramBuffer.GetSpan());
int levels = this.luminanceLevels;
Span<TPixel> pixelRow = this.source.DangerousGetRowSpan(y);
PixelOperations<TPixel>.Instance.ToVector4(this.configuration, pixelRow, vectorBuffer);
for (int x = 0; x < this.bounds.Width; x++)
{
Vector4 vector = Unsafe.Add(ref vectorRef, (uint)x);
int luminance = ColorNumerics.GetBT709Luminance(ref vector, levels);
Interlocked.Increment(ref Unsafe.Add(ref histogramBase, (uint)luminance));
}
}
}
|
GrayscaleLevelsRowOperation
|
csharp
|
dotnet__orleans
|
test/Benchmarks/Ping/StatelessWorkerBenchmark.cs
|
{
"start": 282,
"end": 3495
}
|
public class ____ : IDisposable
{
private readonly IHost _host;
private readonly IGrainFactory _grainFactory;
public StatelessWorkerBenchmark()
{
_host = new HostBuilder()
.UseOrleans((_, siloBuilder) => siloBuilder
.UseLocalhostClustering())
.Build();
_host.StartAsync().GetAwaiter().GetResult();
_grainFactory = _host.Services.GetRequiredService<IGrainFactory>();
}
public void Dispose()
{
_host.StopAsync().GetAwaiter().GetResult();
_host.Dispose();
}
public async Task RunAsync()
{
await Run<IMonotonicGrain, SWMonotonicGrain>(_grainFactory.GetGrain<IMonotonicGrain>(0));
await Run<IAdaptiveGrain, SWAdaptiveGrain>(_grainFactory.GetGrain<IAdaptiveGrain>(0));
}
private async static Task Run<T, H>(T grain)
where T : IProcessorGrain
where H : BaseGrain<H>
{
Console.WriteLine($"Executing benchmark for {typeof(H).Name}");
using var cts = new CancellationTokenSource();
var statsCollector = Task.Run(async () =>
{
while (!cts.Token.IsCancellationRequested)
{
await Task.Delay(1, cts.Token);
BaseGrain<H>.UpdateStats();
}
}, cts.Token);
var tasks = new List<Task>();
const int ConcurrencyLevel = 100;
const double Lambda = 10.0d;
for (var i = 0; i < ConcurrencyLevel; i++)
{
// For a Poisson process with rate λ (tasks / sec in our case), the time between arrivals is
// exponentially distributed with density: f(t) = λe^(-λt), t >= 0; and the interarrival
// time can be generated as: Δt = -ln(U) / λ, where U is uniformly distributed on (0, 1)
var u = Random.Shared.NextDouble();
var delaySec = -Math.Log(u > 0 ? u : double.Epsilon) / Lambda;
var delayMs = (int)(1000 * delaySec);
await Task.Delay(delayMs);
tasks.Add(grain.Process());
}
await Task.WhenAll(tasks);
const int CooldownCycles = 10;
for (var i = 1; i <= CooldownCycles; i++)
{
var cooldownCycle = $"({i}/{CooldownCycles})";
Console.WriteLine($"\nWaiting for cooldown {cooldownCycle}\n");
var cooldownMs = (int)(0.1 * Math.Ceiling(BenchmarkConstants.ProcessDelayMs *
((double)ConcurrencyLevel / BenchmarkConstants.MaxWorkersLimit)));
await Task.Delay(cooldownMs);
Console.WriteLine($"Stats {cooldownCycle}:");
Console.WriteLine($" Active Workers: {BaseGrain<H>.GetActiveWorkers()}");
Console.WriteLine($" Average Workers: {BaseGrain<H>.GetAverageActiveWorkers()}");
Console.WriteLine($" Maximum Workers: {BaseGrain<H>.GetMaxActiveWorkers()}");
Console.Write("\n---------------------------------------------------------------------\n");
}
cts.Cancel();
try
{
await statsCollector;
}
catch (OperationCanceledException)
{
}
BaseGrain<H>.Stop();
}
|
StatelessWorkerBenchmark
|
csharp
|
ChilliCream__graphql-platform
|
src/HotChocolate/Core/test/Types.Tests/Configuration/TypeDiscoveryHandlerTests.cs
|
{
"start": 118,
"end": 884
}
|
public class ____
{
// https://github.com/ChilliCream/graphql-platform/issues/5942
[Fact]
public async Task Ensure_Inputs_Are_Not_Used_As_Outputs()
{
var schema =
await new ServiceCollection()
.AddGraphQLServer()
.AddQueryType<Query>()
.AddType<Foo>()
.BuildSchemaAsync();
schema.MatchInlineSnapshot(
"""
schema {
query: Query
}
type Query {
foo(foo: TestMeInput!): TestMe!
}
type TestMe {
bar: String!
}
input TestMeInput {
bar: String!
}
""");
}
|
TypeDiscoveryHandlerTests
|
csharp
|
dotnet__efcore
|
src/EFCore/Metadata/Internal/TypeBaseExtensions.cs
|
{
"start": 647,
"end": 3421
}
|
public static class ____
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static bool UseEagerSnapshots(this IReadOnlyTypeBase complexType)
=> complexType.GetChangeTrackingStrategy() is ChangeTrackingStrategy.Snapshot or ChangeTrackingStrategy.ChangedNotifications;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static string ShortNameChain(this IReadOnlyTypeBase structuralType)
=> (structuralType is IReadOnlyComplexType { ComplexProperty: var complexProperty })
? complexProperty.DeclaringType.ShortNameChain() + (complexProperty.IsCollection ? "[]" : ".") + structuralType.ShortName()
: structuralType.ShortName();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static T CheckContains<T>(this IReadOnlyTypeBase structuralType, T property)
where T : IReadOnlyPropertyBase
{
Check.NotNull(property);
return !property.DeclaringType.IsAssignableFrom(structuralType)
&& (!((IRuntimeTypeBase)property.DeclaringType).ContainingEntryType.IsAssignableFrom(structuralType)
|| property.DeclaringType is IComplexType { ComplexProperty.IsCollection: true })
&& structuralType.ClrType != typeof(object) // For testing
? throw new InvalidOperationException(
CoreStrings.PropertyDoesNotBelong(property.Name, property.DeclaringType.DisplayName(), structuralType.DisplayName()))
: property;
}
}
|
TypeBaseExtensions
|
csharp
|
dotnet__orleans
|
test/Grains/TestGrainInterfaces/GetGrainInterfaces.cs
|
{
"start": 577,
"end": 672
}
|
public interface ____ : IGrainWithStringKey
{
Task<bool> Foo();
}
|
IStringGrain
|
csharp
|
smartstore__Smartstore
|
src/Smartstore.Web.Common/Models/Catalog/IListActions.cs
|
{
"start": 654,
"end": 761
}
|
public enum ____
{
Mini,
Grid,
List,
Compare
}
}
|
ProductSummaryViewMode
|
csharp
|
HangfireIO__Hangfire
|
src/Hangfire.Core/States/AwaitingState.cs
|
{
"start": 2490,
"end": 3117
}
|
class ____
/// the specified parent job id and next state.
/// </summary>
/// <param name="parentId">The identifier of a background job to wait for.</param>
/// <param name="nextState">The next state for the continuation.</param>
// TODO: Warning inconsistency - everywhere else is OnlyOnSucceededState
public AwaitingState([NotNull] string parentId, [NotNull] IState nextState)
: this(parentId, nextState, JobContinuationOptions.OnAnyFinishedState)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AwaitingState"/>
|
with
|
csharp
|
dotnet__efcore
|
test/EFCore.Cosmos.FunctionalTests/ReloadTest.cs
|
{
"start": 210,
"end": 1598
}
|
public class ____ : IClassFixture<ReloadTest.CosmosReloadTestFixture>
{
public static readonly IEnumerable<object[]> IsAsyncData = [[false], [true]];
private void AssertSql(params string[] expected)
=> Fixture.TestSqlLoggerFactory.AssertBaseline(expected);
protected void ClearLog()
=> Fixture.TestSqlLoggerFactory.Clear();
protected CosmosReloadTestFixture Fixture { get; }
public ReloadTest(CosmosReloadTestFixture fixture)
{
Fixture = fixture;
ClearLog();
}
[ConditionalFact]
public async Task Entity_reference_can_be_reloaded()
{
using var context = CreateContext();
var entry = await context.AddAsync(new Item { Id = 1337, PartitionKey = "Foo" });
await context.SaveChangesAsync();
var itemJson = entry.Property<JObject>("__jObject").CurrentValue;
itemJson["unmapped"] = 2;
await entry.ReloadAsync();
AssertSql(
"""
@p='1337'
SELECT VALUE
{
"Id" : c["Id"],
"PartitionKey" : c["PartitionKey"],
"$type" : c["$type"],
"id0" : c["id"],
"" : c
}
FROM root c
WHERE (c["Id"] = @p)
OFFSET 0 LIMIT 1
""");
itemJson = entry.Property<JObject>("__jObject").CurrentValue;
Assert.Null(itemJson["unmapped"]);
}
protected ReloadTestContext CreateContext()
=> Fixture.CreateContext();
|
ReloadTest
|
csharp
|
dotnet__orleans
|
src/api/Orleans.Transactions.TestKit.Base/Orleans.Transactions.TestKit.Base.cs
|
{
"start": 63917,
"end": 65781
}
|
partial class ____ : global::Orleans.Serialization.Codecs.IFieldCodec<Invokable_IFaultInjectionTransactionTestGrain_GrainReference_8389970A>, global::Orleans.Serialization.Codecs.IFieldCodec
{
public Codec_Invokable_IFaultInjectionTransactionTestGrain_GrainReference_8389970A(global::Orleans.Serialization.Serializers.ICodecProvider codecProvider, global::Orleans.Serialization.Activators.IActivator<Invokable_IFaultInjectionTransactionTestGrain_GrainReference_8389970A> _activator) { }
public void Deserialize<TReaderInput>(ref global::Orleans.Serialization.Buffers.Reader<TReaderInput> reader, Invokable_IFaultInjectionTransactionTestGrain_GrainReference_8389970A instance) { }
public Invokable_IFaultInjectionTransactionTestGrain_GrainReference_8389970A ReadValue<TReaderInput>(ref global::Orleans.Serialization.Buffers.Reader<TReaderInput> reader, global::Orleans.Serialization.WireProtocol.Field field) { throw null; }
public void Serialize<TBufferWriter>(ref global::Orleans.Serialization.Buffers.Writer<TBufferWriter> writer, Invokable_IFaultInjectionTransactionTestGrain_GrainReference_8389970A instance)
where TBufferWriter : System.Buffers.IBufferWriter<byte> { }
public void WriteField<TBufferWriter>(ref global::Orleans.Serialization.Buffers.Writer<TBufferWriter> writer, uint fieldIdDelta, System.Type expectedType, Invokable_IFaultInjectionTransactionTestGrain_GrainReference_8389970A value)
where TBufferWriter : System.Buffers.IBufferWriter<byte> { }
}
[System.CodeDom.Compiler.GeneratedCode("OrleansCodeGen", "9.0.0.0")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public sealed
|
Codec_Invokable_IFaultInjectionTransactionTestGrain_GrainReference_8389970A
|
csharp
|
neuecc__MessagePack-CSharp
|
tests/MessagePack.SourceGenerator.Tests/Resources/SystemCollectionsObjectModelCollection/Formatters.MessagePack.GeneratedMessagePackResolver.AFormatter.g.cs
|
{
"start": 323,
"end": 1687
}
|
internal sealed class ____ : MsgPack::Formatters.IMessagePackFormatter<global::A>
{
public void Serialize(ref MsgPack::MessagePackWriter writer, global::A value, MsgPack::MessagePackSerializerOptions options)
{
if (value == null)
{
writer.WriteNil();
return;
}
MsgPack::IFormatterResolver formatterResolver = options.Resolver;
writer.WriteArrayHeader(1);
MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<global::System.Collections.ObjectModel.Collection<int>>(formatterResolver).Serialize(ref writer, value.SampleCollection, options);
}
public global::A Deserialize(ref MsgPack::MessagePackReader reader, MsgPack::MessagePackSerializerOptions options)
{
if (reader.TryReadNil())
{
return null;
}
options.Security.DepthStep(ref reader);
MsgPack::IFormatterResolver formatterResolver = options.Resolver;
var length = reader.ReadArrayHeader();
var ____result = new global::A();
for (int i = 0; i < length; i++)
{
switch (i)
{
case 0:
____result.SampleCollection = MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<global::System.Collections.ObjectModel.Collection<int>>(formatterResolver).Deserialize(ref reader, options);
break;
default:
reader.Skip();
break;
}
}
reader.Depth--;
return ____result;
}
}
}
}
|
AFormatter
|
csharp
|
mongodb__mongo-csharp-driver
|
tests/MongoDB.Bson.Tests/Serialization/Serializers/AnimalHierarchyWithAttributesTests.cs
|
{
"start": 1409,
"end": 4558
}
|
public class ____ : Cat
{
}
[Fact]
public void TestDeserializeBear()
{
var document = new BsonDocument
{
{ "_id", ObjectId.Empty },
{ "_t", new BsonArray { "Animal", "Bear" } },
{ "Age", 123 },
{ "Name", "Panda Bear" }
};
var bson = document.ToBson();
var rehydrated = (Bear)BsonSerializer.Deserialize<Animal>(bson);
Assert.IsType<Bear>(rehydrated);
var json = rehydrated.ToJson<Animal>(writerSettings: new JsonWriterSettings { OutputMode = JsonOutputMode.Shell }, args: new BsonSerializationArgs { SerializeIdFirst = true });
var expected = "{ '_id' : ObjectId('000000000000000000000000'), '_t' : ['Animal', 'Bear'], 'Age' : 123, 'Name' : 'Panda Bear' }".Replace("'", "\"");
Assert.Equal(expected, json);
Assert.True(bson.SequenceEqual(rehydrated.ToBson<Animal>(args: new BsonSerializationArgs { SerializeIdFirst = true })));
}
[Fact]
public void TestDeserializeTiger()
{
var document = new BsonDocument
{
{ "_id", ObjectId.Empty },
{ "_t", new BsonArray { "Animal", "Cat", "Tiger" } },
{ "Age", 234 },
{ "Name", "Striped Tiger" }
};
var bson = document.ToBson();
var rehydrated = (Tiger)BsonSerializer.Deserialize<Animal>(bson);
Assert.IsType<Tiger>(rehydrated);
var json = rehydrated.ToJson<Animal>(writerSettings: new JsonWriterSettings { OutputMode = JsonOutputMode.Shell }, args: new BsonSerializationArgs { SerializeIdFirst = true });
var expected = "{ '_id' : ObjectId('000000000000000000000000'), '_t' : ['Animal', 'Cat', 'Tiger'], 'Age' : 234, 'Name' : 'Striped Tiger' }".Replace("'", "\"");
Assert.Equal(expected, json);
Assert.True(bson.SequenceEqual(rehydrated.ToBson<Animal>(args: new BsonSerializationArgs { SerializeIdFirst = true })));
}
[Fact]
public void TestDeserializeLion()
{
var document = new BsonDocument
{
{ "_id", ObjectId.Empty },
{ "_t", new BsonArray { "Animal", "Cat", "Lion" } },
{ "Age", 234 },
{ "Name", "King Lion" }
};
var bson = document.ToBson();
var rehydrated = (Lion)BsonSerializer.Deserialize<Animal>(bson);
Assert.IsType<Lion>(rehydrated);
var json = rehydrated.ToJson<Animal>(writerSettings: new JsonWriterSettings { OutputMode = JsonOutputMode.Shell }, args: new BsonSerializationArgs { SerializeIdFirst = true });
var expected = "{ '_id' : ObjectId('000000000000000000000000'), '_t' : ['Animal', 'Cat', 'Lion'], 'Age' : 234, 'Name' : 'King Lion' }".Replace("'", "\"");
Assert.Equal(expected, json);
Assert.True(bson.SequenceEqual(rehydrated.ToBson<Animal>(args: new BsonSerializationArgs { SerializeIdFirst = true })));
}
}
}
|
Lion
|
csharp
|
AvaloniaUI__Avalonia
|
src/Avalonia.Base/Animation/IAnimator.cs
|
{
"start": 186,
"end": 628
}
|
internal interface ____ : IList<AnimatorKeyFrame>
{
/// <summary>
/// The target property.
/// </summary>
AvaloniaProperty? Property {get; set;}
/// <summary>
/// Applies the current KeyFrame group to the specified control.
/// </summary>
IDisposable? Apply(Animation animation, Animatable control, IClock? clock, IObservable<bool> match, Action? onComplete);
}
}
|
IAnimator
|
csharp
|
dotnetcore__WTM
|
demo/WalkingTec.Mvvm.Demo/Areas/_Admin/ViewModels/FrameworkGroupVMs/FrameworkGroupMDVM.cs
|
{
"start": 391,
"end": 3351
}
|
public class ____ : BaseVM
{
[Display(Name = "_Admin.GroupCode")]
public string GroupCode { get; set; }
public List<GroupDp> DpLists { get; set; }
public FrameworkGroupMDVM()
{
}
protected override void InitVM()
{
DpLists = new List<GroupDp>();
foreach (var item in Wtm.DataPrivilegeSettings)
{
DpListVM list = new DpListVM();
list.Searcher = new DpSearcher();
list.Searcher.TableName = item.ModelName;
DpLists.Add(new GroupDp { DpName = item.PrivillegeName, List = list, SelectedIds = new List<string>() });
}
var alldp = DC.Set<DataPrivilege>().Where(x => x.GroupCode == GroupCode).ToList();
foreach (var item in DpLists)
{
var select = alldp.Where(x => x.TableName == item.List.Searcher.TableName).Select(x => x.RelateId).ToList();
if(select.Count == 0)
{
item.IsAll = null;
}
else if (select.Contains(null))
{
item.IsAll = true;
}
else
{
item.IsAll = false;
item.SelectedIds = select;
}
}
}
public bool DoChange()
{
List<Guid> oldIDs = DC.Set<DataPrivilege>().Where(x => x.GroupCode == GroupCode).Select(x => x.ID).ToList();
foreach (var oldid in oldIDs)
{
DataPrivilege dp = new DataPrivilege { ID = oldid };
DC.Set<DataPrivilege>().Attach(dp);
DC.DeleteEntity(dp);
}
foreach (var item in DpLists)
{
if(item.IsAll == true)
{
DataPrivilege dp = new DataPrivilege();
dp.RelateId = null;
dp.GroupCode = GroupCode;
dp.TableName = item.List.Searcher.TableName;
dp.TenantCode = LoginUserInfo.CurrentTenant;
DC.Set<DataPrivilege>().Add(dp);
}
if (item.IsAll == false && item.SelectedIds != null)
{
foreach (var id in item.SelectedIds)
{
DataPrivilege dp = new DataPrivilege();
dp.RelateId = id;
dp.GroupCode = GroupCode;
dp.TableName = item.List.Searcher.TableName;
dp.TenantCode = LoginUserInfo.CurrentTenant;
DC.Set<DataPrivilege>().Add(dp);
}
}
}
DC.SaveChanges();
Wtm.RemoveUserCacheByGroup(GroupCode).Wait();
return true;
}
}
|
FrameworkGroupMDVM
|
csharp
|
EventStore__EventStore
|
src/KurrentDB.Core.Tests/Http/PersistentSubscription/feed.cs
|
{
"start": 3780,
"end": 5379
}
|
class ____(string contentType) : SpecificationWithLongFeed {
private JObject _feed;
private List<JToken> _entries;
protected override async Task When() {
var allMessagesFeedLink = String.Format("{0}/{1}", _subscriptionEndpoint, _numberOfEvents);
_feed = await GetJson<JObject>(allMessagesFeedLink, contentType);
_entries = _feed != null ? _feed["entries"].ToList() : new List<JToken>();
}
[Test]
public void returns_ok_status_code() {
Assert.AreEqual(HttpStatusCode.OK, _lastResponse.StatusCode);
}
[Test]
public void contains_all_the_events() {
Assert.AreEqual(_numberOfEvents, _entries.Count);
}
[Test]
public void the_ackAll_link_is_to_correct_uri() {
var ids = String.Format("ids={0}", String.Join(",", _eventIds.ToArray()));
var ackAllLink = String.Format("subscriptions/{0}/{1}/ack", TestStreamName, SubscriptionGroupName);
Assert.AreEqual(MakeUrl(ackAllLink, ids), GetLink(_feed, "ackAll"));
}
[Test]
public void the_nackAll_link_is_to_correct_uri() {
var ids = String.Format("ids={0}", String.Join(",", _eventIds.ToArray()));
var nackAllLink = String.Format("subscriptions/{0}/{1}/nack", TestStreamName, SubscriptionGroupName);
Assert.AreEqual(MakeUrl(nackAllLink, ids), GetLink(_feed, "nackAll"));
}
[Test]
public void all_entries_have_retry_count_element() {
var allEntriesHaveRetryCount = _feed["entries"].All(entry => entry["retryCount"] != null);
Assert.True(allEntriesHaveRetryCount);
}
}
[Category("LongRunning")]
[TestFixture(ContentType.CompetingJson)]
[TestFixture(ContentType.LegacyCompetingJson)]
|
when_retrieving_a_feed_with_events
|
csharp
|
npgsql__efcore.pg
|
src/EFCore.PG/Infrastructure/Internal/NpgsqlModelValidator.cs
|
{
"start": 632,
"end": 11835
}
|
public class ____ : RelationalModelValidator
{
/// <summary>
/// The backend version to target.
/// </summary>
private readonly Version _postgresVersion;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public NpgsqlModelValidator(
ModelValidatorDependencies dependencies,
RelationalModelValidatorDependencies relationalDependencies,
INpgsqlSingletonOptions npgsqlSingletonOptions)
: base(dependencies, relationalDependencies)
{
_postgresVersion = npgsqlSingletonOptions.PostgresVersion;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override void Validate(IModel model, IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)
{
base.Validate(model, logger);
ValidateIdentityVersionCompatibility(model);
ValidateIndexIncludeProperties(model);
}
/// <summary>
/// Validates that identity columns are used only with PostgreSQL 10.0 or later.
/// </summary>
/// <param name="model">The model to validate.</param>
protected virtual void ValidateIdentityVersionCompatibility(IModel model)
{
if (_postgresVersion.AtLeast(10))
{
return;
}
var strategy = model.GetValueGenerationStrategy();
if (strategy is NpgsqlValueGenerationStrategy.IdentityAlwaysColumn or NpgsqlValueGenerationStrategy.IdentityByDefaultColumn)
{
throw new InvalidOperationException(
$"'{strategy}' requires PostgreSQL 10.0 or later. "
+ "If you're using an older version, set PostgreSQL compatibility mode by calling "
+ $"'optionsBuilder.{nameof(NpgsqlDbContextOptionsBuilder.SetPostgresVersion)}()' in your model's OnConfiguring. "
+ "See the docs for more info.");
}
foreach (var property in model.GetEntityTypes().SelectMany(e => e.GetProperties()))
{
var propertyStrategy = property.GetValueGenerationStrategy();
if (propertyStrategy is NpgsqlValueGenerationStrategy.IdentityAlwaysColumn
or NpgsqlValueGenerationStrategy.IdentityByDefaultColumn)
{
throw new InvalidOperationException(
$"{property.DeclaringType}.{property.Name}: '{propertyStrategy}' requires PostgreSQL 10.0 or later.");
}
}
}
/// <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>
protected override void ValidateValueGeneration(
IEntityType entityType,
IKey key,
IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)
{
if (entityType.GetTableName() != null
&& (string?)entityType[RelationalAnnotationNames.MappingStrategy] == RelationalAnnotationNames.TpcMappingStrategy)
{
foreach (var storeGeneratedProperty in key.Properties.Where(
p => (p.ValueGenerated & ValueGenerated.OnAdd) != 0
&& p.GetValueGenerationStrategy() != NpgsqlValueGenerationStrategy.Sequence))
{
logger.TpcStoreGeneratedIdentityWarning(storeGeneratedProperty);
}
}
}
/// <inheritdoc/>
protected override void ValidateTypeMappings(
IModel model,
IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)
{
base.ValidateTypeMappings(model, logger);
foreach (var entityType in model.GetEntityTypes())
{
foreach (var property in entityType.GetFlattenedDeclaredProperties())
{
var strategy = property.GetValueGenerationStrategy();
var propertyType = property.ClrType;
switch (strategy)
{
case NpgsqlValueGenerationStrategy.None:
break;
case NpgsqlValueGenerationStrategy.IdentityByDefaultColumn:
case NpgsqlValueGenerationStrategy.IdentityAlwaysColumn:
if (!NpgsqlPropertyExtensions.IsCompatibleWithValueGeneration(property))
{
throw new InvalidOperationException(
NpgsqlStrings.IdentityBadType(
property.Name, property.DeclaringType.DisplayName(), propertyType.ShortDisplayName()));
}
break;
case NpgsqlValueGenerationStrategy.SequenceHiLo:
case NpgsqlValueGenerationStrategy.Sequence:
case NpgsqlValueGenerationStrategy.SerialColumn:
if (!NpgsqlPropertyExtensions.IsCompatibleWithValueGeneration(property))
{
throw new InvalidOperationException(
NpgsqlStrings.SequenceBadType(
property.Name, property.DeclaringType.DisplayName(), propertyType.ShortDisplayName()));
}
break;
default:
throw new UnreachableException();
}
}
}
}
/// <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>
protected virtual void ValidateIndexIncludeProperties(IModel model)
{
foreach (var index in model.GetEntityTypes().SelectMany(t => t.GetDeclaredIndexes()))
{
var includeProperties = index.GetIncludeProperties();
if (includeProperties?.Count > 0)
{
var notFound = includeProperties
.FirstOrDefault(i => index.DeclaringEntityType.FindProperty(i) is null);
if (notFound is not null)
{
throw new InvalidOperationException(
NpgsqlStrings.IncludePropertyNotFound(index.DeclaringEntityType.DisplayName(), notFound));
}
var duplicate = includeProperties
.GroupBy(i => i)
.Where(g => g.Count() > 1)
.Select(y => y.Key)
.FirstOrDefault();
if (duplicate is not null)
{
throw new InvalidOperationException(
NpgsqlStrings.IncludePropertyDuplicated(index.DeclaringEntityType.DisplayName(), duplicate));
}
var inIndex = includeProperties
.FirstOrDefault(i => index.Properties.Any(p => i == p.Name));
if (inIndex is not null)
{
throw new InvalidOperationException(
NpgsqlStrings.IncludePropertyInIndex(index.DeclaringEntityType.DisplayName(), inIndex));
}
}
}
}
/// <inheritdoc />
protected override void ValidateStoredProcedures(
IModel model,
IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)
{
base.ValidateStoredProcedures(model, logger);
foreach (var entityType in model.GetEntityTypes())
{
if (entityType.GetDeleteStoredProcedure() is { } deleteStoredProcedure)
{
ValidateSproc(deleteStoredProcedure, logger);
}
if (entityType.GetInsertStoredProcedure() is { } insertStoredProcedure)
{
ValidateSproc(insertStoredProcedure, logger);
}
if (entityType.GetUpdateStoredProcedure() is { } updateStoredProcedure)
{
ValidateSproc(updateStoredProcedure, logger);
}
}
static void ValidateSproc(IStoredProcedure sproc, IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)
{
var entityType = sproc.EntityType;
var storeObjectIdentifier = sproc.GetStoreIdentifier();
if (sproc.ResultColumns.Any())
{
throw new InvalidOperationException(
NpgsqlStrings.StoredProcedureResultColumnsNotSupported(
entityType.DisplayName(),
storeObjectIdentifier.DisplayName()));
}
if (sproc.IsRowsAffectedReturned)
{
throw new InvalidOperationException(
NpgsqlStrings.StoredProcedureReturnValueNotSupported(
entityType.DisplayName(),
storeObjectIdentifier.DisplayName()));
}
}
}
/// <inheritdoc />
protected override void ValidateCompatible(
IProperty property,
IProperty duplicateProperty,
string columnName,
in StoreObjectIdentifier storeObject,
IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)
{
base.ValidateCompatible(property, duplicateProperty, columnName, storeObject, logger);
if (property.GetCompressionMethod(storeObject) != duplicateProperty.GetCompressionMethod(storeObject))
{
throw new InvalidOperationException(
NpgsqlStrings.DuplicateColumnCompressionMethodMismatch(
duplicateProperty.DeclaringType.DisplayName(),
duplicateProperty.Name,
property.DeclaringType.DisplayName(),
property.Name,
columnName,
storeObject.DisplayName()));
}
}
}
|
NpgsqlModelValidator
|
csharp
|
RicoSuter__NSwag
|
src/NSwag.Generation.Tests/Processors/OperationSummaryAndDescriptionProcessorTests.cs
|
{
"start": 340,
"end": 4138
}
|
public class ____
{
[OpenApiOperation("\r\n\t This method has a summary. \r\n\t", "\r\n\t This method has a description. \r\n\t")]
public void DocumentedMethodWithOpenApiOperationAttribute()
{
}
[Description("\r\n\t This method has a description. \r\n\t")]
public void DocumentedMethodWithDescriptionAttribute()
{
}
/// <summary>
/// This method has a summary.
/// </summary>
/// <remarks>
/// This method has a description.
/// </remarks>
public void DocumentedMethodWithSummary()
{
}
}
[Fact]
public void Process_TrimsWhitespaceFromOpenApiOperationSummary()
{
//// Arrange
var controllerType = typeof(DocumentedController);
var methodInfo = controllerType.GetMethod(nameof(DocumentedController.DocumentedMethodWithOpenApiOperationAttribute));
var context = GetContext(controllerType, methodInfo);
var processor = new OperationSummaryAndDescriptionProcessor();
//// Act
processor.Process(context);
// Assert
var summary = context.OperationDescription.Operation.Summary;
Assert.Equal("This method has a summary.", summary);
var description = context.OperationDescription.Operation.Description;
Assert.Equal("This method has a description.", description);
}
[Fact]
public void Process_TrimsWhitespaceFromDescription()
{
//// Arrange
var controllerType = typeof(DocumentedController);
var methodInfo = controllerType.GetMethod(nameof(DocumentedController.DocumentedMethodWithDescriptionAttribute));
var context = GetContext(controllerType, methodInfo);
var processor = new OperationSummaryAndDescriptionProcessor();
//// Act
processor.Process(context);
// Assert
var summary = context.OperationDescription.Operation.Summary;
Assert.Equal("This method has a description.", summary);
var description = context.OperationDescription.Operation.Description;
Assert.Null(description);
}
[Fact]
public void Process_TrimsWhitespaceFromSummary()
{
//// Arrange
var controllerType = typeof(DocumentedController);
var methodInfo = controllerType.GetMethod(nameof(DocumentedController.DocumentedMethodWithSummary));
var context = GetContext(controllerType, methodInfo);
var processor = new OperationSummaryAndDescriptionProcessor();
//// Act
processor.Process(context);
// Assert
var summary = context.OperationDescription.Operation.Summary;
Assert.Equal("This method has a summary.", summary);
var description = context.OperationDescription.Operation.Description;
Assert.Equal("This method has a description.", description);
}
private OperationProcessorContext GetContext(Type controllerType, MethodInfo methodInfo)
{
var document = new OpenApiDocument();
var operationDescription = new OpenApiOperationDescription { Operation = new OpenApiOperation() };
var settings = new OpenApiDocumentGeneratorSettings
{
SchemaSettings = new NewtonsoftJsonSchemaGeneratorSettings()
};
return new OperationProcessorContext(document, operationDescription, controllerType, methodInfo, null, null, settings, null);
}
}
}
|
DocumentedController
|
csharp
|
grandnode__grandnode2
|
src/Web/Grand.Web.Admin/Models/Customers/CustomerTagProductModel.cs
|
{
"start": 530,
"end": 2012
}
|
public class ____ : BaseModel
{
[GrandResourceDisplayName("Admin.Catalog.Products.List.SearchProductName")]
public string SearchProductName { get; set; }
[GrandResourceDisplayName("Admin.Catalog.Products.List.SearchCategory")]
[UIHint("Category")]
public string SearchCategoryId { get; set; }
[GrandResourceDisplayName("Admin.Catalog.Products.List.Brand")]
[UIHint("Brand")]
public string SearchBrandId { get; set; }
[UIHint("Collection")]
[GrandResourceDisplayName("Admin.Catalog.Products.List.SearchCollection")]
public string SearchCollectionId { get; set; }
[GrandResourceDisplayName("Admin.Catalog.Products.List.SearchStore")]
public string SearchStoreId { get; set; }
[GrandResourceDisplayName("Admin.Catalog.Products.List.SearchVendor")]
public string SearchVendorId { get; set; }
[GrandResourceDisplayName("Admin.Catalog.Products.List.SearchProductType")]
public int SearchProductTypeId { get; set; }
public IList<SelectListItem> AvailableStores { get; set; } = new List<SelectListItem>();
public IList<SelectListItem> AvailableVendors { get; set; } = new List<SelectListItem>();
public IList<SelectListItem> AvailableProductTypes { get; set; } = new List<SelectListItem>();
public string CustomerTagId { get; set; }
public string[] SelectedProductIds { get; set; }
}
}
|
AddProductModel
|
csharp
|
dotnet__aspnetcore
|
src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/ValidationsGenerator.SkipValidation.cs
|
{
"start": 17670,
"end": 17836
}
|
public class ____
{
[Range(10, 100)]
public int IntegerWithRange { get; set; } = 10;
}
// This should have generated validation code
[SkipValidation]
|
ComplexType
|
csharp
|
dotnet__maui
|
src/Controls/tests/TestCases.HostApp/Issues/Issue18740Entry.xaml.cs
|
{
"start": 42,
"end": 161
}
|
public partial class ____ : ContentPage
{
public Issue18740Entry()
{
InitializeComponent();
}
}
}
|
Issue18740Entry
|
csharp
|
DuendeSoftware__IdentityServer
|
identity-server/test/IdentityServer.IntegrationTests/Common/BrowserHandler.cs
|
{
"start": 363,
"end": 3058
}
|
public class ____ : DelegatingHandler
{
private CookieContainer _cookieContainer = new CookieContainer();
public bool AllowCookies { get; set; } = true;
public bool AllowAutoRedirect { get; set; } = true;
public int ErrorRedirectLimit { get; set; } = 20;
public int StopRedirectingAfter { get; set; } = int.MaxValue;
public BrowserHandler(HttpMessageHandler next)
: base(next)
{
}
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await SendCookiesAsync(request, cancellationToken);
var redirectCount = 0;
while (AllowAutoRedirect &&
(300 <= (int)response.StatusCode && (int)response.StatusCode < 400) &&
redirectCount < StopRedirectingAfter)
{
if (redirectCount >= ErrorRedirectLimit)
{
throw new InvalidOperationException(string.Format("Too many redirects. Error limit = {0}", redirectCount));
}
var location = response.Headers.Location;
if (!location.IsAbsoluteUri)
{
location = new Uri(response.RequestMessage.RequestUri, location);
}
request = new HttpRequestMessage(HttpMethod.Get, location);
response = await SendCookiesAsync(request, cancellationToken).ConfigureAwait(false);
redirectCount++;
}
return response;
}
internal Cookie GetCookie(string uri, string name) => _cookieContainer.GetCookies(new Uri(uri)).FirstOrDefault(x => x.Name == name);
internal void RemoveCookie(string uri, string name)
{
var cookie = _cookieContainer.GetCookies(new Uri(uri)).FirstOrDefault(x => x.Name == name);
if (cookie != null)
{
cookie.Expired = true;
}
}
protected async Task<HttpResponseMessage> SendCookiesAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (AllowCookies)
{
var cookieHeader = _cookieContainer.GetCookieHeader(request.RequestUri);
if (!string.IsNullOrEmpty(cookieHeader))
{
request.Headers.Add("Cookie", cookieHeader);
}
}
var response = await base.SendAsync(request, cancellationToken);
if (AllowCookies && response.Headers.Contains("Set-Cookie"))
{
var responseCookieHeader = string.Join(',', response.Headers.GetValues("Set-Cookie"));
_cookieContainer.SetCookies(request.RequestUri, responseCookieHeader);
}
return response;
}
}
|
BrowserHandler
|
csharp
|
ChilliCream__graphql-platform
|
src/HotChocolate/Data/test/Data.Tests/PagingHelperIntegrationTests.cs
|
{
"start": 46446,
"end": 46996
}
|
public static class ____
{
[UsePaging]
public static async Task<Connection<Product>> GetProducts(
[Parent] Brand brand,
ProductsByBrandDataLoader dataLoader,
ISelection selection,
PagingArguments arguments,
CancellationToken cancellationToken)
=> await dataLoader
.With(arguments)
.Select(selection)
.LoadAsync(brand.Id, cancellationToken)
.ToConnectionAsync();
}
|
BrandExtensionsWithSelect
|
csharp
|
dotnet__efcore
|
test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTest.ModelSnapshot.cs
|
{
"start": 20158,
"end": 20320
}
|
private class ____ : Animal
{
public Animal FavoriteAnimal { get; set; }
public ICollection<Pet> Pets { get; } = new List<Pet>();
}
|
Human
|
csharp
|
xunit__xunit
|
src/xunit.v2.tests/Sdk/Frameworks/TheoryDiscovererTests.cs
|
{
"start": 12719,
"end": 12862
}
|
class ____
{
[Theory(Skip = "I have data")]
[InlineData(42)]
[InlineData(2112)]
public void TestMethod(int value) { }
}
|
SkippedWithData
|
csharp
|
dotnet__efcore
|
test/EFCore.Tests/ChangeTracking/Internal/StateManagerTest.cs
|
{
"start": 19541,
"end": 26558
}
|
private class ____
{
public int? Id1 { get; set; }
public int? Id2 { get; set; }
public int? AlternateId1 { get; set; }
public int? AlternateId2 { get; set; }
public string Value { get; set; }
public CompositeKeyOwned Owned { get; set; }
}
[ConditionalFact]
public void StartTracking_is_no_op_if_entity_is_already_tracked()
{
var model = BuildModel();
var categoryType = model.FindEntityType(typeof(Category));
var stateManager = CreateStateManager(model);
var category = new Category { Id = 77, PrincipalId = 777 };
var snapshot = new Snapshot<int, string, int>(77, "Bjork", 777);
var entry = stateManager.StartTrackingFromQuery(categoryType, category, snapshot);
Assert.Same(entry, stateManager.StartTrackingFromQuery(categoryType, category, snapshot));
}
[ConditionalFact]
public void StartTracking_throws_for_invalid_entity_key()
{
var model = BuildModel();
var stateManager = CreateStateManager(model);
var entry = stateManager.GetOrCreateEntry(
new Dogegory { Id = null });
Assert.Equal(
CoreStrings.InvalidKeyValue("Dogegory", "Id"),
Assert.Throws<InvalidOperationException>(() => stateManager.StartTracking(entry)).Message);
}
[ConditionalFact]
public void StartTracking_throws_for_invalid_alternate_key()
{
var model = BuildModel();
var stateManager = CreateStateManager(model);
var entry = stateManager.GetOrCreateEntry(
new Category { Id = 77, PrincipalId = null });
Assert.Equal(
CoreStrings.InvalidAlternateKeyValue("Category", "PrincipalId"),
Assert.Throws<InvalidOperationException>(() => stateManager.StartTracking(entry)).Message);
}
[ConditionalFact]
public void Can_get_existing_entry_even_if_state_not_yet_set()
{
var stateManager = CreateStateManager(BuildModel());
var category = new Category { Id = 1 };
var entry = stateManager.GetOrCreateEntry(category);
var entry2 = stateManager.GetOrCreateEntry(category);
Assert.Same(entry, entry2);
Assert.Equal(EntityState.Detached, entry.EntityState);
}
[ConditionalFact]
public void Can_stop_tracking_and_then_start_tracking_again()
{
var stateManager = CreateStateManager(BuildModel());
var category = new Category { Id = 1, PrincipalId = 777 };
var entry = stateManager.GetOrCreateEntry(category);
entry.SetEntityState(EntityState.Added);
entry.SetEntityState(EntityState.Detached);
entry.SetEntityState(EntityState.Added);
var entry2 = stateManager.GetOrCreateEntry(category);
Assert.Same(entry, entry2);
}
[ConditionalFact]
public void Can_stop_tracking_and_then_start_tracking_using_a_new_state_entry()
{
var stateManager = CreateStateManager(BuildModel());
var category = new Category { Id = 1, PrincipalId = 777 };
var entry = stateManager.GetOrCreateEntry(category);
entry.SetEntityState(EntityState.Added);
entry.SetEntityState(EntityState.Detached);
var entry2 = stateManager.GetOrCreateEntry(category);
Assert.NotSame(entry, entry2);
entry2.SetEntityState(EntityState.Added);
}
[ConditionalFact]
public void StopTracking_releases_reference_to_entry()
{
var stateManager = CreateStateManager(BuildModel());
var category = new Category { Id = 1, PrincipalId = 777 };
var entry = stateManager.GetOrCreateEntry(category);
entry.SetEntityState(EntityState.Added);
entry.SetEntityState(EntityState.Detached);
var entry2 = stateManager.GetOrCreateEntry(category);
entry2.SetEntityState(EntityState.Added);
Assert.NotSame(entry, entry2);
Assert.Equal(EntityState.Detached, entry.EntityState);
}
[ConditionalFact]
public void Throws_on_attempt_to_start_tracking_entity_with_null_key()
{
var stateManager = CreateStateManager(BuildModel());
var entity = new Dogegory();
var entry = stateManager.GetOrCreateEntry(entity);
Assert.Equal(
CoreStrings.InvalidKeyValue("Dogegory", "Id"),
Assert.Throws<InvalidOperationException>(() => stateManager.StartTracking(entry)).Message);
}
[ConditionalFact]
public void Throws_on_attempt_to_start_tracking_with_wrong_manager()
{
var model = BuildModel();
var stateManager = CreateStateManager(model);
var stateManager2 = CreateStateManager(model);
var entry = stateManager.GetOrCreateEntry(new Category());
Assert.Equal(
CoreStrings.WrongStateManager(nameof(Category)),
Assert.Throws<InvalidOperationException>(() => stateManager2.StartTracking(entry)).Message);
}
[ConditionalFact]
public void Will_get_new_entry_if_another_entity_with_the_same_key_is_already_tracked()
{
var stateManager = CreateStateManager(BuildModel());
Assert.NotSame(
stateManager.GetOrCreateEntry(
new Category { Id = 77 }),
stateManager.GetOrCreateEntry(
new Category { Id = 77 }));
}
[ConditionalFact]
public void Can_get_all_entities()
{
var stateManager = CreateStateManager(BuildModel());
var productId1 = new Guid("984ade3c-2f7b-4651-a351-642e92ab7146");
var productId2 = new Guid("0edc9136-7eed-463b-9b97-bdb9648ab877");
stateManager.StartTracking(
stateManager.GetOrCreateEntry(
new Category { Id = 77, PrincipalId = 777 }))
.SetEntityState(EntityState.Unchanged);
stateManager.StartTracking(
stateManager.GetOrCreateEntry(
new Category { Id = 78, PrincipalId = 778 }))
.SetEntityState(EntityState.Unchanged);
stateManager.StartTracking(
stateManager.GetOrCreateEntry(
new Product { Id = productId1 }))
.SetEntityState(EntityState.Unchanged);
stateManager.StartTracking(
stateManager.GetOrCreateEntry(
new Product { Id = productId2 }))
.SetEntityState(EntityState.Unchanged);
Assert.Equal(4, stateManager.Entries.Count());
Assert.Equal(
new[] { 77, 78 },
stateManager.Entries
.Select(e => e.Entity)
.OfType<Category>()
.Select(e => e.Id)
.OrderBy(k => k)
.ToArray());
Assert.Equal(
new[] { productId2, productId1 },
stateManager.Entries
.Select(e => e.Entity)
.OfType<Product>()
.Select(e => e.Id)
.OrderBy(k => k)
.ToArray());
}
|
CompositeKey
|
csharp
|
nunit__nunit
|
src/NUnitFramework/framework/Exceptions/ResultStateException.cs
|
{
"start": 304,
"end": 1386
}
|
public abstract class ____ : Exception
{
/// <param name="message">The error message that explains
/// the reason for the exception</param>
protected ResultStateException(string message) : base(message)
{
}
/// <param name="message">The error message that explains
/// the reason for the exception</param>
/// <param name="inner">The exception that caused the
/// current exception</param>
public ResultStateException(string message, Exception? inner) : base(message, inner)
{
}
#if !NET8_0_OR_GREATER
/// <summary>
/// Serialization Constructor
/// </summary>
protected ResultStateException(System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context)
{
}
#endif
/// <summary>
/// Gets the ResultState provided by this exception
/// </summary>
public abstract ResultState ResultState { get; }
}
}
|
ResultStateException
|
csharp
|
bitwarden__server
|
src/Billing/Models/FreshdeskWebhookModel.cs
|
{
"start": 164,
"end": 462
}
|
public class ____
{
[JsonPropertyName("ticket_id")]
public string TicketId { get; set; }
[JsonPropertyName("ticket_contact_email")]
public string TicketContactEmail { get; set; }
[JsonPropertyName("ticket_tags")]
public string TicketTags { get; set; }
}
|
FreshdeskWebhookModel
|
csharp
|
dotnet__aspnetcore
|
src/Mvc/Mvc.ViewFeatures/test/Rendering/HtmlHelperListBoxExtensionsTest.cs
|
{
"start": 314,
"end": 8095
}
|
public class ____
{
private static readonly List<SelectListItem> BasicSelectList = new List<SelectListItem>
{
new SelectListItem("Zero", "0"),
new SelectListItem("One", "1"),
new SelectListItem("Two", "2"),
new SelectListItem("Three", "3"),
};
[Fact]
public void ListBox_FindsSelectList()
{
// Arrange
var expectedHtml = "<select id=\"HtmlEncode[[Property1]]\" multiple=\"HtmlEncode[[multiple]]\" name=\"HtmlEncode[[Property1]]\">" +
"<option value=\"HtmlEncode[[0]]\">HtmlEncode[[Zero]]</option>" + Environment.NewLine +
"<option value=\"HtmlEncode[[1]]\">HtmlEncode[[One]]</option>" + Environment.NewLine +
"<option selected=\"HtmlEncode[[selected]]\" value=\"HtmlEncode[[2]]\">HtmlEncode[[Two]]</option>" + Environment.NewLine +
"<option value=\"HtmlEncode[[3]]\">HtmlEncode[[Three]]</option>" + Environment.NewLine +
"</select>";
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.ModelState.SetModelValue("Property1", 2, "2");
helper.ViewData["Property1"] = BasicSelectList;
// Act
var listBoxResult = helper.ListBox("Property1");
// Assert
Assert.Equal(expectedHtml, HtmlContentUtilities.HtmlContentToString(listBoxResult));
}
[Fact]
public void ListBox_UsesSpecifiedExpressionAndSelectList()
{
// Arrange
var expectedHtml = "<select id=\"HtmlEncode[[Property3]]\" multiple=\"HtmlEncode[[multiple]]\" name=\"HtmlEncode[[Property3]]\">" +
"<option selected=\"HtmlEncode[[selected]]\" value=\"HtmlEncode[[4]]\">HtmlEncode[[Four]]</option>" + Environment.NewLine +
"<option value=\"HtmlEncode[[5]]\">HtmlEncode[[Five]]</option>" + Environment.NewLine +
"</select>";
var selectList = new List<SelectListItem>
{
new SelectListItem("Four", "4"),
new SelectListItem("Five", "5"),
};
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property3 = new List<string> { "4" } };
// Act
var listBoxResult = helper.ListBox("Property3", selectList);
// Assert
Assert.Equal(expectedHtml, HtmlContentUtilities.HtmlContentToString(listBoxResult));
}
[Fact]
public void ListBox_UsesSpecifiedSelectExpressionAndListAndHtmlAttributes()
{
// Arrange
var expectedHtml = "<select id=\"HtmlEncode[[Property2]]\" Key=\"HtmlEncode[[Value]]\" multiple=\"HtmlEncode[[multiple]]\" name=\"HtmlEncode[[Property2]]\">" +
"<option value=\"HtmlEncode[[4]]\">HtmlEncode[[Four]]</option>" + Environment.NewLine +
"<option selected=\"HtmlEncode[[selected]]\" value=\"HtmlEncode[[5]]\">HtmlEncode[[Five]]</option>" + Environment.NewLine +
"</select>";
var selectList = new List<SelectListItem>
{
new SelectListItem("Four", "4"),
new SelectListItem("Five", "5"),
};
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData["Property2"] = new List<string> { "1", "2", "5" };
// Act
var listBoxResult = helper.ListBox("Property2", selectList, new { Key = "Value", name = "CustomName" });
// Assert
Assert.Equal(expectedHtml, HtmlContentUtilities.HtmlContentToString(listBoxResult));
}
[Fact]
public void ListBoxFor_NullSelectListFindsListFromViewData()
{
// Arrange
var expectedHtml = "<select id=\"HtmlEncode[[Property1]]\" multiple=\"HtmlEncode[[multiple]]\" name=\"HtmlEncode[[Property1]]\">" +
"<option value=\"HtmlEncode[[0]]\">HtmlEncode[[Zero]]</option>" + Environment.NewLine +
"<option value=\"HtmlEncode[[1]]\">HtmlEncode[[One]]</option>" + Environment.NewLine +
"<option value=\"HtmlEncode[[2]]\">HtmlEncode[[Two]]</option>" + Environment.NewLine +
"<option value=\"HtmlEncode[[3]]\">HtmlEncode[[Three]]</option>" + Environment.NewLine +
"</select>";
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData["Property1"] = BasicSelectList;
// Act
var listBoxForResult = helper.ListBoxFor(m => m.Property1, null);
// Assert
Assert.Equal(expectedHtml, HtmlContentUtilities.HtmlContentToString(listBoxForResult));
}
[Fact]
public void ListBoxFor_UsesSpecifiedExpressionAndSelectList()
{
// Arrange
var expectedHtml = "<select id=\"HtmlEncode[[Property3]]\" multiple=\"HtmlEncode[[multiple]]\" name=\"HtmlEncode[[Property3]]\">" +
"<option selected=\"HtmlEncode[[selected]]\" value=\"HtmlEncode[[4]]\">HtmlEncode[[Four]]</option>" + Environment.NewLine +
"<option selected=\"HtmlEncode[[selected]]\" value=\"HtmlEncode[[5]]\">HtmlEncode[[Five]]</option>" + Environment.NewLine +
"</select>";
var selectList = new List<SelectListItem>
{
new SelectListItem("Four", "4"),
new SelectListItem("Five", "5"),
};
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property3 = new List<string> { "0", "4", "5" } };
// Act
var listBoxForResult = helper.ListBoxFor(m => m.Property3, selectList);
// Assert
Assert.Equal(expectedHtml, HtmlContentUtilities.HtmlContentToString(listBoxForResult));
}
[Fact]
public void ListBoxFor_UsesSpecifiedExpressionAndSelectListAndHtmlAttributes()
{
// Arrange
var expectedHtml = "<select id=\"HtmlEncode[[Property3]]\" Key=\"HtmlEncode[[Value]]\" multiple=\"HtmlEncode[[multiple]]\" name=\"HtmlEncode[[Property3]]\">" +
"<option value=\"HtmlEncode[[4]]\">HtmlEncode[[Four]]</option>" + Environment.NewLine +
"<option value=\"HtmlEncode[[5]]\">HtmlEncode[[Five]]</option>" + Environment.NewLine +
"</select>";
var selectList = new List<SelectListItem>
{
new SelectListItem("Four", "4"),
new SelectListItem("Five", "5"),
};
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData["Property3"] = new List<string> { "0", "2" };
// Act
var listBoxForResult = helper.ListBoxFor(m => m.Property3, selectList, new { Key = "Value", name = "CustomName" });
// Assert
Assert.Equal(expectedHtml, HtmlContentUtilities.HtmlContentToString(listBoxForResult));
}
|
HtmlHelperListBoxExtensionsTest
|
csharp
|
microsoft__PowerToys
|
src/modules/launcher/Wox.Plugin/ISettingProvider.cs
|
{
"start": 326,
"end": 552
}
|
public interface ____
{
Control CreateSettingPanel();
void UpdateSettings(PowerLauncherPluginSettings settings);
IEnumerable<PluginAdditionalOption> AdditionalOptions { get; }
}
}
|
ISettingProvider
|
csharp
|
ChilliCream__graphql-platform
|
src/HotChocolate/Core/src/Types/Configuration/RegisteredType.cs
|
{
"start": 172,
"end": 2615
}
|
partial class ____ : IHasRuntimeType
{
private readonly TypeRegistry _typeRegistry;
private readonly TypeLookup _typeLookup;
private List<TypeDependency>? _conditionals;
public RegisteredType(
TypeSystemObject type,
bool isInferred,
TypeRegistry typeRegistry,
TypeLookup typeLookup,
IDescriptorContext descriptorContext,
TypeInterceptor typeInterceptor,
string? scope)
{
Type = type;
_typeRegistry = typeRegistry;
_typeLookup = typeLookup;
IsInferred = isInferred;
DescriptorContext = descriptorContext;
TypeInterceptor = typeInterceptor;
IsExtension = Type is ITypeDefinitionExtension;
IsSchema = Type is Schema;
Scope = scope;
if (type is ITypeDefinition typeDefinition)
{
IsNamedType = true;
IsIntrospectionType = typeDefinition.IsIntrospectionType();
Kind = typeDefinition.Kind;
}
else if (type is DirectiveType)
{
IsDirectiveType = true;
Kind = TypeKind.Directive;
}
}
public TypeSystemObject Type { get; }
public TypeKind? Kind { get; }
public Type RuntimeType
=> Type is IHasRuntimeType hasClrType
? hasClrType.RuntimeType
: typeof(object);
public List<TypeReference> References { get; } = [];
public List<TypeDependency> Dependencies { get; } = [];
public List<TypeDependency> Conditionals => _conditionals ??= [];
public bool IsInferred { get; }
public bool IsExtension { get; }
public bool IsNamedType { get; }
public bool IsDirectiveType { get; }
public bool IsIntrospectionType { get; }
public bool IsSchema { get; }
public bool IsType => IsNamedType;
public bool IsDirective => IsDirectiveType;
public List<ISchemaError> Errors => _errors ??= [];
public bool HasErrors => _errors is { Count: > 0 };
public void ClearConditionals()
{
if (_conditionals is { Count: > 0 })
{
_conditionals.Clear();
}
}
public override string? ToString()
{
if (IsSchema)
{
return "Schema";
}
if (Type is INameProvider { Name: { Length: > 0 } name })
{
return IsDirective ? $"@{name}" : name;
}
return Type.ToString();
}
}
|
RegisteredType
|
csharp
|
dotnetcore__FreeSql
|
Extensions/FreeSql.Extensions.BaseEntity/BaseEntityAsync.cs
|
{
"start": 753,
"end": 2058
}
|
public abstract class ____<TEntity, TKey> : BaseEntityAsync<TEntity> where TEntity : class
{
static BaseEntityAsync()
{
var keyType = typeof(TKey).NullableTypeOrThis();
if (keyType == typeof(int) || keyType == typeof(long))
ConfigEntity(typeof(TEntity), t => t.Property("Id").IsIdentity(true));
}
/// <summary>
/// Primary key <br />
/// 主键
/// </summary>
[Column(Position = 1)]
public virtual TKey Id { get; set; }
#if !NET40
/// <summary>
/// Get data based on the value of the primary key <br />
/// 根据主键值获取数据
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static async Task<TEntity> FindAsync(TKey id)
{
var item = await Select.WhereDynamic(id).FirstAsync();
(item as BaseEntity<TEntity>)?.Attach();
return item;
}
#endif
}
/// <summary>
/// Entity base class, including CreateTime/UpdateTime/IsDeleted, and async CRUD methods.
/// <para></para>
/// 包括 CreateTime/UpdateTime/IsDeleted、以及 CRUD 异步方法的实体基类
/// </summary>
/// <typeparam name="TEntity"></typeparam>
[Table(DisableSyncStructure = true)]
|
BaseEntityAsync
|
csharp
|
CommunityToolkit__Maui
|
src/CommunityToolkit.Maui.UnitTests/Views/Popup/PopupPageTests.cs
|
{
"start": 20593,
"end": 20917
}
|
sealed class ____ : IPopupOptions
{
public bool CanBeDismissedByTappingOutsideOfPopup { get; set; }
public Color PageOverlayColor { get; set; } = Colors.Transparent;
public Action? OnTappingOutsideOfPopup { get; set; }
public Shape? Shape { get; set; }
public Shadow? Shadow { get; set; } = null;
}
}
|
MockPopupOptions
|
csharp
|
EventStore__EventStore
|
src/KurrentDB.Core/TransactionLog/ITransactionFileChaser.cs
|
{
"start": 341,
"end": 543
}
|
public interface ____ : IDisposable {
ICheckpoint Checkpoint { get; }
void Open();
ValueTask<SeqReadResult> TryReadNext(CancellationToken token);
void Close();
void Flush();
}
|
ITransactionFileChaser
|
csharp
|
reactiveui__ReactiveUI
|
src/ReactiveUI/ReactiveObject/ReactiveObject.cs
|
{
"start": 565,
"end": 4675
}
|
public class ____ : IReactiveNotifyPropertyChanged<IReactiveObject>, IHandleObservableErrors, IReactiveObject
{
private bool _propertyChangingEventsSubscribed;
private bool _propertyChangedEventsSubscribed;
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveObject"/> class.
/// </summary>
public ReactiveObject()
{
}
/// <inheritdoc/>
public event PropertyChangingEventHandler? PropertyChanging
{
add
{
if (!_propertyChangingEventsSubscribed)
{
this.SubscribePropertyChangingEvents();
_propertyChangingEventsSubscribed = true;
}
PropertyChangingHandler += value;
}
remove => PropertyChangingHandler -= value;
}
/// <inheritdoc/>
public event PropertyChangedEventHandler? PropertyChanged
{
add
{
if (!_propertyChangedEventsSubscribed)
{
this.SubscribePropertyChangedEvents();
_propertyChangedEventsSubscribed = true;
}
PropertyChangedHandler += value;
}
remove => PropertyChangedHandler -= value;
}
[SuppressMessage("Roslynator", "RCS1159:Use EventHandler<T>", Justification = "Long term design.")]
private event PropertyChangingEventHandler? PropertyChangingHandler;
[SuppressMessage("Roslynator", "RCS1159:Use EventHandler<T>", Justification = "Long term design.")]
private event PropertyChangedEventHandler? PropertyChangedHandler;
/// <inheritdoc />
[IgnoreDataMember]
[JsonIgnore]
#if !MONO
[Browsable(false)]
[Display(Order = -1, AutoGenerateField = false, AutoGenerateFilter = false)]
#endif
public IObservable<IReactivePropertyChangedEventArgs<IReactiveObject>> Changing =>
Volatile.Read(ref field) ?? Interlocked.CompareExchange(ref field, ((IReactiveObject)this).GetChangingObservable(), null) ?? field;
/// <inheritdoc />
[IgnoreDataMember]
[JsonIgnore]
#if !MONO
[Browsable(false)]
[Display(Order = -1, AutoGenerateField = false, AutoGenerateFilter = false)]
#endif
public IObservable<IReactivePropertyChangedEventArgs<IReactiveObject>> Changed =>
Volatile.Read(ref field) ?? Interlocked.CompareExchange(ref field, ((IReactiveObject)this).GetChangedObservable(), null) ?? field;
/// <inheritdoc/>
[IgnoreDataMember]
[JsonIgnore]
#if !MONO
[Browsable(false)]
[Display(Order = -1, AutoGenerateField = false, AutoGenerateFilter = false)]
#endif
public IObservable<Exception> ThrownExceptions =>
Volatile.Read(ref field) ?? Interlocked.CompareExchange(ref field, this.GetThrownExceptionsObservable(), null) ?? field;
/// <inheritdoc/>
void IReactiveObject.RaisePropertyChanging(PropertyChangingEventArgs args) =>
PropertyChangingHandler?.Invoke(this, args);
/// <inheritdoc/>
void IReactiveObject.RaisePropertyChanged(PropertyChangedEventArgs args) =>
PropertyChangedHandler?.Invoke(this, args);
/// <inheritdoc/>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("This method uses reflection to access properties by name.")]
[RequiresDynamicCode("This method uses reflection to access properties by name.")]
#endif
public IDisposable SuppressChangeNotifications() => // TODO: Create Test
IReactiveObjectExtensions.SuppressChangeNotifications(this);
/// <summary>
/// Determines if change notifications are enabled or not.
/// </summary>
/// <returns>A value indicating whether change notifications are enabled.</returns>
public bool AreChangeNotificationsEnabled() => // TODO: Create Test
IReactiveObjectExtensions.AreChangeNotificationsEnabled(this);
/// <summary>
/// Delays notifications until the return IDisposable is disposed.
/// </summary>
/// <returns>A disposable which when disposed will send delayed notifications.</returns>
public IDisposable DelayChangeNotifications() =>
IReactiveObjectExtensions.DelayChangeNotifications(this);
}
|
ReactiveObject
|
csharp
|
pythonnet__pythonnet
|
src/testing/nonexportable.cs
|
{
"start": 62,
"end": 127
}
|
class ____ not be visible to Python
[PyExport(false)]
|
should
|
csharp
|
EventStore__EventStore
|
src/KurrentDB.Core/TransactionLog/Scavenging/Interfaces/IChunkManagerForChunkExecutor.cs
|
{
"start": 829,
"end": 970
}
|
public interface ____ {
ValueTask<bool> SwitchInChunks(IReadOnlyList<string> locators, CancellationToken token);
}
|
IChunkManagerForChunkRemover
|
csharp
|
dotnet__maui
|
src/Controls/tests/Xaml.UnitTests/NativeViewsAndBindings.rt.xaml.cs
|
{
"start": 8061,
"end": 8283
}
|
class
____ TNativeWrapper : View
{
if (BindableObjectProxy<TNativeView>.BindableObjectProxies.TryGetValue(nativeView, out BindableObjectProxy<TNativeView> proxy))
proxy.TransferAttachedPropertiesTo(wrapper);
}
|
where
|
csharp
|
microsoft__semantic-kernel
|
dotnet/test/VectorData/AzureAISearch.ConformanceTests/TypeTests/AzureAISearchEmbeddingTypeTests.cs
|
{
"start": 323,
"end": 531
}
|
public class ____(AzureAISearchEmbeddingTypeTests.Fixture fixture)
: EmbeddingTypeTests<string>(fixture), IClassFixture<AzureAISearchEmbeddingTypeTests.Fixture>
{
public new
|
AzureAISearchEmbeddingTypeTests
|
csharp
|
OrchardCMS__OrchardCore
|
src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Services/ElasticsearchQueryService.cs
|
{
"start": 261,
"end": 2807
}
|
public class ____
{
private readonly ElasticsearchIndexManager _elasticIndexManager;
private readonly ILogger _logger;
public ElasticsearchQueryService(
ElasticsearchIndexManager elasticIndexManager,
ILogger<ElasticsearchQueryService> logger)
{
_elasticIndexManager = elasticIndexManager;
_logger = logger;
}
public async Task PopulateResultAsync(ElasticsearchSearchContext context, SearchResult result)
{
var searchResult = await _elasticIndexManager.SearchAsync(context);
result.ContentItemIds = [];
if (searchResult?.TopDocs is null || searchResult.TopDocs.Count == 0)
{
return;
}
result.TotalCount = searchResult.TotalCount;
result.Highlights = [];
foreach (var item in searchResult.TopDocs)
{
if (!item.Value.TryGetPropertyValue(nameof(ContentItem.ContentItemId), out var id) ||
!id.TryGetValue<string>(out var contentItemId))
{
continue;
}
if (item.Highlights is not null && item.Highlights.Count > 0)
{
result.Highlights[contentItemId] = item.Highlights;
}
result.ContentItemIds.Add(contentItemId);
}
}
public async Task<IList<string>> GetContentItemIdsAsync(ElasticsearchSearchContext request)
{
var results = await _elasticIndexManager.SearchAsync(request);
if (results?.TopDocs is null || results.TopDocs.Count == 0)
{
return [];
}
var contentItemIds = new List<string>();
foreach (var item in results.TopDocs)
{
if (!item.Value.TryGetPropertyValue(nameof(ContentItem.ContentItemId), out var id) ||
!id.TryGetValue<string>(out var contentItemId))
{
continue;
}
contentItemIds.Add(contentItemId);
}
return contentItemIds;
}
public Task<ElasticsearchResult> SearchAsync(IndexProfile index, string query)
{
ArgumentNullException.ThrowIfNull(index);
ArgumentException.ThrowIfNullOrEmpty(query);
try
{
return _elasticIndexManager.SearchAsync(index, query);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while querying elastic with exception: {Message}", ex.Message);
}
return Task.FromResult(new ElasticsearchResult());
}
}
|
ElasticsearchQueryService
|
csharp
|
dotnet__aspnetcore
|
src/Localization/Localization/src/Internal/AssemblyWrapper.cs
|
{
"start": 510,
"end": 952
}
|
internal class ____
#pragma warning restore CA1852 // Seal internal types
{
public AssemblyWrapper(Assembly assembly)
{
ArgumentNullThrowHelper.ThrowIfNull(assembly);
Assembly = assembly;
}
public Assembly Assembly { get; }
public virtual string FullName => Assembly.FullName!;
public virtual Stream? GetManifestResourceStream(string name) => Assembly.GetManifestResourceStream(name);
}
|
AssemblyWrapper
|
csharp
|
dotnet__maui
|
src/Controls/tests/TestCases.HostApp/Issues/XFIssue/Issue2976.cs
|
{
"start": 1167,
"end": 1310
}
|
class ____ by the native platform
/// and is therefore faster than building a custom ViewCell in Microsoft.Maui.Controls.
/// </summary>
|
provided
|
csharp
|
dotnet__orleans
|
src/Orleans.Core.Abstractions/Runtime/RequestContext.cs
|
{
"start": 6651,
"end": 7925
}
|
struct ____ : IDisposable
{
private readonly Guid _originalReentrancyId;
private readonly Guid _newReentrancyId;
public ReentrancySection(Guid originalReentrancyId, Guid newReentrancyId)
{
_originalReentrancyId = originalReentrancyId;
_newReentrancyId = newReentrancyId;
if (newReentrancyId != originalReentrancyId)
{
ReentrancyId = newReentrancyId;
}
if (newReentrancyId != Guid.Empty)
{
var grain = RuntimeContext.Current as ICallChainReentrantGrainContext;
grain?.OnEnterReentrantSection(_newReentrancyId);
}
}
public void Dispose()
{
if (_newReentrancyId != Guid.Empty)
{
var grain = RuntimeContext.Current as ICallChainReentrantGrainContext;
grain?.OnExitReentrantSection(_newReentrancyId);
}
if (_newReentrancyId != _originalReentrancyId)
{
ReentrancyId = _originalReentrancyId;
}
}
}
}
}
|
ReentrancySection
|
csharp
|
mongodb__mongo-csharp-driver
|
src/MongoDB.Driver/Authentication/Gssapi/Sspi/AuthIdentityFlag.cs
|
{
"start": 726,
"end": 988
}
|
internal enum ____
{
/// <summary>
/// SEC_WINNT_AUTH_IDENTITY_ANSI
/// </summary>
Ansi = 0x1,
/// <summary>
/// SEC_WINNT_AUTH_IDENTITY_UNICODE
/// </summary>
Unicode = 0x2
}
}
|
AuthIdentityFlag
|
csharp
|
NSubstitute__NSubstitute
|
src/NSubstitute/Raise.cs
|
{
"start": 105,
"end": 3328
}
|
public static class ____
{
/// <summary>
/// Raise an event for an <c>EventHandler<TEventArgs></c> event with the provided <paramref name="sender"/> and <paramref name="eventArgs"/>.
/// </summary>
public static EventHandlerWrapper<TEventArgs> EventWith<TEventArgs>(object sender, TEventArgs eventArgs) where TEventArgs : EventArgs
{
return new EventHandlerWrapper<TEventArgs>(sender, eventArgs);
}
/// <summary>
/// Raise an event for an <c>EventHandler<TEventArgs></c> event with the substitute as the sender and the provided <paramref name="eventArgs" />.
/// </summary>
public static EventHandlerWrapper<TEventArgs> EventWith<TEventArgs>(TEventArgs eventArgs) where TEventArgs : EventArgs
{
return new EventHandlerWrapper<TEventArgs>(eventArgs);
}
/// <summary>
/// Raise an event for an <c>EventHandler<EventArgsT></c> event with the substitute as the sender
/// and with a default instance of <typeparamref name="TEventArgs" />.
/// </summary>
public static EventHandlerWrapper<TEventArgs> EventWith<TEventArgs>() where TEventArgs : EventArgs
{
return new EventHandlerWrapper<TEventArgs>();
}
/// <summary>
/// Raise an event for an <c>EventHandler</c> or <c>EventHandler<EventArgs></c> event with the substitute
/// as the sender and with empty <c>EventArgs</c>.
/// </summary>
public static EventHandlerWrapper<EventArgs> Event()
{
return new EventHandlerWrapper<EventArgs>();
}
/// <summary>
/// Raise an event of type <typeparamref name="THandler" /> with the provided arguments. If no arguments are provided
/// NSubstitute will try to provide reasonable defaults.
/// </summary>
public static DelegateEventWrapper<THandler> Event<THandler>(params object[] arguments)
{
var normalizedArgs = FixParamsArrayAmbiguity(arguments, typeof(THandler));
return new DelegateEventWrapper<THandler>(normalizedArgs);
}
/// <summary>
/// If delegate takes single parameter of array type, it's impossible to distinguish
/// whether input array represents all arguments, or the first argument only.
/// If we find that ambiguity might happen, we wrap user input in an extra array.
/// </summary>
private static object[] FixParamsArrayAmbiguity(object[] arguments, Type delegateType)
{
ParameterInfo[] invokeMethodParameters = delegateType.GetInvokeMethod().GetParameters();
if (invokeMethodParameters.Length != 1)
{
return arguments;
}
Type singleParameterType = invokeMethodParameters[0].ParameterType;
if (!singleParameterType.IsArray)
{
return arguments;
}
// Check if native non-params syntax was used.
// This way actual value is already wrapped in array and we don't need to extra-wrap it.
if (arguments.Length == 1 && singleParameterType.IsInstanceOfType(arguments[0]))
{
return arguments;
}
if (singleParameterType.IsInstanceOfType(arguments))
{
return [arguments];
}
return arguments;
}
}
|
Raise
|
csharp
|
dotnet__machinelearning
|
src/Microsoft.ML.Data/Evaluators/MulticlassClassificationEvaluator.cs
|
{
"start": 2414,
"end": 7001
}
|
public enum ____
{
[EnumValueDisplay(MulticlassClassificationEvaluator.AccuracyMicro)]
AccuracyMicro,
[EnumValueDisplay(MulticlassClassificationEvaluator.AccuracyMacro)]
AccuracyMacro,
[EnumValueDisplay(MulticlassClassificationEvaluator.LogLoss)]
LogLoss,
[EnumValueDisplay(MulticlassClassificationEvaluator.LogLossReduction)]
LogLossReduction,
}
internal const string LoadName = "MultiClassClassifierEvaluator";
private readonly int? _outputTopKAcc;
private readonly bool _names;
public MulticlassClassificationEvaluator(IHostEnvironment env, Arguments args)
: base(env, LoadName)
{
Host.AssertValue(args, "args");
Host.CheckUserArg(args.OutputTopKAcc == null || args.OutputTopKAcc > 0, nameof(args.OutputTopKAcc));
_outputTopKAcc = args.OutputTopKAcc;
_names = args.Names;
}
private protected override void CheckScoreAndLabelTypes(RoleMappedSchema schema)
{
var score = schema.GetUniqueColumn(AnnotationUtils.Const.ScoreValueKind.Score);
var scoreType = score.Type as VectorDataViewType;
if (scoreType == null || scoreType.Size < 2 || scoreType.ItemType != NumberDataViewType.Single)
throw Host.ExceptSchemaMismatch(nameof(schema), "score", score.Name, "vector of two or more items of type Single", score.Type.ToString());
Host.CheckParam(schema.Label.HasValue, nameof(schema), "Could not find the label column");
var labelType = schema.Label.Value.Type;
if (labelType != NumberDataViewType.Single && labelType.GetKeyCount() <= 0)
throw Host.ExceptSchemaMismatch(nameof(schema), "label", schema.Label.Value.Name, "Single or Key", labelType.ToString());
}
private protected override Aggregator GetAggregatorCore(RoleMappedSchema schema, string stratName)
{
var score = schema.GetUniqueColumn(AnnotationUtils.Const.ScoreValueKind.Score);
int numClasses = score.Type.GetVectorSize();
Host.Assert(numClasses > 0);
var classNames = GetClassNames(schema);
return new Aggregator(Host, classNames, numClasses, schema.Weight != null, _outputTopKAcc, stratName);
}
private ReadOnlyMemory<char>[] GetClassNames(RoleMappedSchema schema)
{
ReadOnlyMemory<char>[] names;
// Get the label names from the score column if they exist, or use the default names.
var scoreInfo = schema.GetUniqueColumn(AnnotationUtils.Const.ScoreValueKind.Score);
var mdType = schema.Schema[scoreInfo.Index].Annotations.Schema.GetColumnOrNull(AnnotationUtils.Kinds.SlotNames)?.Type as VectorDataViewType;
var labelNames = default(VBuffer<ReadOnlyMemory<char>>);
if (mdType != null && mdType.IsKnownSize && mdType.ItemType is TextDataViewType)
{
schema.Schema[scoreInfo.Index].Annotations.GetValue(AnnotationUtils.Kinds.SlotNames, ref labelNames);
names = new ReadOnlyMemory<char>[labelNames.Length];
labelNames.CopyTo(names);
}
else
{
var score = schema.GetColumns(AnnotationUtils.Const.ScoreValueKind.Score);
Host.Assert(Utils.Size(score) == 1);
int numClasses = score[0].Type.GetVectorSize();
Host.Assert(numClasses > 0);
names = Enumerable.Range(0, numClasses).Select(i => i.ToString().AsMemory()).ToArray();
}
return names;
}
private protected override IRowMapper CreatePerInstanceRowMapper(RoleMappedSchema schema)
{
Host.CheckParam(schema.Label.HasValue, nameof(schema), "Schema must contain a label column");
var scoreInfo = schema.GetUniqueColumn(AnnotationUtils.Const.ScoreValueKind.Score);
int numClasses = scoreInfo.Type.GetVectorSize();
return new MulticlassPerInstanceEvaluator(Host, schema.Schema, scoreInfo, schema.Label.Value.Name);
}
public override IEnumerable<MetricColumn> GetOverallMetricColumns()
{
yield return new MetricColumn("AccuracyMicro", AccuracyMicro);
yield return new MetricColumn("AccuracyMacro", AccuracyMacro);
yield return new MetricColumn("TopKAccuracy", TopKAccuracy);
yield return new MetricColumn("LogLoss<
|
Metrics
|
csharp
|
ChilliCream__graphql-platform
|
src/HotChocolate/Fusion-vnext/src/Fusion.Utilities/Rewriters/DocumentRewriter.cs
|
{
"start": 235,
"end": 26469
}
|
public sealed class ____(ISchemaDefinition schema, bool removeStaticallyExcludedSelections = false)
{
private static readonly FieldNode s_typeNameField =
new FieldNode(
null,
new NameNode(IntrospectionFieldNames.TypeName),
null,
[new DirectiveNode("fusion__empty")],
ImmutableArray<ArgumentNode>.Empty,
null);
public DocumentNode RewriteDocument(DocumentNode document, string? operationName = null)
{
var operation = document.GetOperation(operationName);
var operationType = schema.GetOperationType(operation.Operation);
var fragmentLookup = CreateFragmentLookup(document);
var newSelectionSet = RewriteSelectionSet(
operation.SelectionSet,
operationType,
fragmentLookup);
var newOperation = new OperationDefinitionNode(
null,
operation.Name,
operation.Description,
operation.Operation,
operation.VariableDefinitions,
RewriteDirectives(operation.Directives),
newSelectionSet);
return new DocumentNode([newOperation]);
}
private SelectionSetNode RewriteSelectionSet(
SelectionSetNode selectionSetNode,
ITypeDefinition type,
Dictionary<string, FragmentDefinitionNode>? fragmentLookup)
{
var context = new Context(null, null, type, null, fragmentLookup ?? []);
CollectSelections(selectionSetNode, context);
var newSelections = RewriteSelections(context) ?? [s_typeNameField];
var newSelectionSetNode = new SelectionSetNode(newSelections);
return newSelectionSetNode;
}
#region Collecting
private void CollectSelections(SelectionSetNode selectionSet, Context context)
{
foreach (var selection in selectionSet.Selections)
{
if (removeStaticallyExcludedSelections && IsStaticallySkipped(selection))
{
continue;
}
switch (selection)
{
case FieldNode field:
CollectField(field, context);
break;
case InlineFragmentNode inlineFragment:
CollectInlineFragment(inlineFragment, context);
break;
case FragmentSpreadNode fragmentSpread:
CollectFragmentSpread(fragmentSpread, context);
break;
}
}
}
private void CollectField(FieldNode fieldNode, Context context)
{
var (conditional, directives) = DivideDirectives(
fieldNode,
Types.DirectiveLocation.Field);
if (conditional is not null)
{
if (IsStaticallySkipped(conditional, context, out conditional))
{
return;
}
if (conditional is not null)
{
context = context.GetOrAddConditionalContext(conditional);
}
}
fieldNode = new FieldNode(
fieldNode.Name,
fieldNode.Alias,
directives ?? [],
RewriteArguments(fieldNode.Arguments),
fieldNode.SelectionSet);
var fieldName = fieldNode.Name.Value;
ITypeDefinition? fieldType = null;
if (fieldNode.SelectionSet is not null && context.Type is IComplexTypeDefinition complexType)
{
var field = complexType.Fields[fieldName];
fieldType = field.Type.AsTypeDefinition();
}
var fieldContext = GetOrAddContextForField(context, fieldNode, fieldType);
if (fieldContext is not null && fieldNode.SelectionSet is not null)
{
CollectSelections(fieldNode.SelectionSet, fieldContext);
}
}
private void CollectInlineFragment(InlineFragmentNode inlineFragment, Context context)
{
var typeCondition = inlineFragment.TypeCondition is not null
? schema.Types[inlineFragment.TypeCondition.Name.Value]
: context.Type;
var (conditional, directives) = DivideDirectives(
inlineFragment,
Types.DirectiveLocation.InlineFragment);
CollectFragment(
inlineFragment.SelectionSet,
typeCondition,
conditional,
directives,
context);
}
private void CollectFragmentSpread(FragmentSpreadNode fragmentSpread, Context context)
{
var fragmentDefinition = context.GetFragmentDefinition(fragmentSpread.Name.Value);
var typeCondition = schema.Types[fragmentDefinition.TypeCondition.Name.Value];
var (conditional, directives) = DivideDirectives(
fragmentSpread,
Types.DirectiveLocation.InlineFragment);
CollectFragment(
fragmentDefinition.SelectionSet,
typeCondition,
conditional,
directives,
context);
}
private void CollectFragment(
SelectionSetNode selectionSet,
ITypeDefinition typeCondition,
Conditional? conditional,
IReadOnlyList<DirectiveNode>? otherDirectives,
Context context)
{
if (conditional is not null)
{
if (IsStaticallySkipped(conditional, context, out conditional))
{
return;
}
if (conditional is not null)
{
context = context.GetOrAddConditionalContext(conditional);
}
}
var isTypeRefinement = !typeCondition.IsAssignableFrom(context.Type);
var fragmentContext = context;
if (isTypeRefinement || otherDirectives is not null)
{
var inlineFragment = new InlineFragmentNode(
null,
isTypeRefinement
? new NamedTypeNode(typeCondition.Name)
: null,
otherDirectives ?? [],
selectionSet);
fragmentContext = GetOrAddContextForFragment(context, inlineFragment, typeCondition);
}
CollectSelections(selectionSet, fragmentContext);
}
private static Context? GetOrAddContextForField(Context context, FieldNode fieldNode, ITypeDefinition? fieldType)
{
if (context.IsConditionalContext)
{
var unconditionalContext = context.UnconditionalContext;
if (unconditionalContext.HasField(fieldNode, out var unconditionalFieldContext))
{
if (fieldNode.SelectionSet is null)
{
return null;
}
if (unconditionalFieldContext is null)
{
throw new InvalidOperationException("Expected to have a field context");
}
var conditionalContextBelowUnconditionalFieldContext =
RecreateConditionalContextHierarchy(unconditionalFieldContext, context);
return conditionalContextBelowUnconditionalFieldContext;
}
if (!context.HasField(fieldNode, out var fieldContext))
{
fieldContext = context.AddField(fieldNode, fieldType);
unconditionalContext.RecordReferenceInConditionalContext(fieldNode, context);
}
return fieldContext;
}
else
{
if (!context.HasField(fieldNode, out var fieldContext))
{
fieldContext = context.AddField(fieldNode, fieldType);
}
if (context.TryGetConditionalContextsWithReferences(fieldNode, out var conditionalContexts))
{
foreach (var conditionalContext in conditionalContexts)
{
if (fieldContext is not null
&& conditionalContext.HasField(fieldNode, out var conditionalFieldContext)
&& conditionalFieldContext is not null)
{
var conditionalContextBelowUnconditionalField =
RecreateConditionalContextHierarchy(fieldContext, conditionalContext);
MergeContexts(conditionalFieldContext, conditionalContextBelowUnconditionalField);
}
conditionalContext.RemoveField(fieldNode);
}
context.RemoveReferenceToConditionalContext(fieldNode);
}
return fieldContext;
}
}
private static Context GetOrAddContextForFragment(
Context context,
InlineFragmentNode inlineFragmentNode,
ITypeDefinition typeCondition)
{
if (context.IsConditionalContext)
{
var unconditionalContext = context.UnconditionalContext;
if (unconditionalContext.HasFragment(inlineFragmentNode, out var unconditionalFragmentContext))
{
var conditionalContextBelowUnconditionalFragmentContext =
RecreateConditionalContextHierarchy(unconditionalFragmentContext, context);
return conditionalContextBelowUnconditionalFragmentContext;
}
if (!context.HasFragment(inlineFragmentNode, out var fragmentContext))
{
fragmentContext = context.AddFragment(inlineFragmentNode, typeCondition);
unconditionalContext.RecordReferenceInConditionalContext(inlineFragmentNode, context);
}
return fragmentContext;
}
else
{
if (!context.HasFragment(inlineFragmentNode, out var fragmentContext))
{
fragmentContext = context.AddFragment(inlineFragmentNode, typeCondition);
}
if (context.TryGetConditionalContextsWithReferences(inlineFragmentNode, out var conditionalContexts))
{
foreach (var conditionalContext in conditionalContexts)
{
if (conditionalContext.HasFragment(inlineFragmentNode,
out var conditionalFragmentContext))
{
var conditionalContextBelowUnconditionalFragment =
RecreateConditionalContextHierarchy(fragmentContext, conditionalContext);
MergeContexts(conditionalFragmentContext, conditionalContextBelowUnconditionalFragment);
}
conditionalContext.RemoveFragment(inlineFragmentNode);
}
context.RemoveReferenceToConditionalContext(inlineFragmentNode);
}
return fragmentContext;
}
}
/// <summary>
/// Rebuilds the conditional directive hierarchy of <paramref name="sourceContext"/> into
/// <paramref name="targetContext"/>, returning the innermost, rebuilt conditional context.
/// </summary>
private static Context RecreateConditionalContextHierarchy(Context targetContext, Context sourceContext)
{
var conditionalStack = new Stack<Context>();
var current = sourceContext;
while (current?.IsConditionalContext == true)
{
conditionalStack.Push(current);
current = current.Parent;
}
while (conditionalStack.TryPop(out var conditionalContext))
{
targetContext = targetContext.GetOrAddConditionalContext(conditionalContext.Conditional!);
}
return targetContext;
}
private static void MergeContexts(Context source, Context target)
{
if (source.Conditionals is not null)
{
foreach (var (conditional, conditionalContext) in source.Conditionals)
{
var targetConditionalContext = target.GetOrAddConditionalContext(conditional);
MergeContexts(conditionalContext, targetConditionalContext);
}
}
if (source.Fields is not null)
{
foreach (var (_, fieldContextLookup) in source.Fields)
{
foreach (var (fieldNode, fieldContext) in fieldContextLookup)
{
if (!target.HasField(fieldNode, out var targetFieldContext))
{
targetFieldContext = GetOrAddContextForField(target, fieldNode, fieldContext?.Type);
}
if (fieldContext is not null && targetFieldContext is not null)
{
MergeContexts(fieldContext, targetFieldContext);
}
}
}
}
if (source.Fragments is not null)
{
foreach (var (_, fragmentContextLookup) in source.Fragments)
{
foreach (var (inlineFragmentNode, fragmentContext) in fragmentContextLookup)
{
if (!target.HasFragment(inlineFragmentNode, out var targetFragmentContext))
{
targetFragmentContext = GetOrAddContextForFragment(
target,
inlineFragmentNode,
fragmentContext.Type);
}
MergeContexts(fragmentContext, targetFragmentContext);
}
}
}
}
private (Conditional? Conditional, IReadOnlyList<DirectiveNode>? Directives) DivideDirectives(
IHasDirectives directiveProvider,
Types.DirectiveLocation targetLocation)
{
if (directiveProvider.Directives.Count == 0)
{
return (null, null);
}
Conditional? conditional = null;
List<DirectiveNode>? directives = null;
foreach (var directive in directiveProvider.Directives)
{
if (schema.DirectiveDefinitions.TryGetDirective(directive.Name.Value, out var directiveDefinition)
&& !directiveDefinition.Locations.HasFlag(targetLocation))
{
continue;
}
var rewrittenDirective = RewriteDirective(directive);
if (directive.Name.Value.Equals(DirectiveNames.Skip.Name, StringComparison.Ordinal))
{
if (directive.Arguments is [{ Value: BooleanValueNode }])
{
continue;
}
conditional ??= new Conditional();
conditional.Skip = rewrittenDirective;
continue;
}
if (directive.Name.Value.Equals(DirectiveNames.Include.Name, StringComparison.Ordinal))
{
if (directive.Arguments is [{ Value: BooleanValueNode }])
{
continue;
}
conditional ??= new Conditional();
conditional.Include = rewrittenDirective;
continue;
}
if (directive.Name.Value.Equals(DirectiveNames.Defer.Name, StringComparison.Ordinal))
{
var ifArgument = directive.Arguments
.FirstOrDefault(a => a.Name.Value.Equals("if", StringComparison.Ordinal));
if (ifArgument?.Value is BooleanValueNode { Value: false })
{
continue;
}
}
directives ??= [];
directives.Add(rewrittenDirective);
}
return (conditional, directives);
}
/// <summary>
/// Checks whether a parent context already contains an opposite conditional part
/// with the same variable value, e.g. <c>@skip(if: $value) :: @include(if: $value)</c>.
/// <br/>
/// If that's the case, the child conditional will always be skipped, so we can statically
/// skip the selection this conditional is on.
/// <br/>
/// Additionally, we check whether a part of the conditional already exists in a parent context.
/// <br/>
/// In a hierarchy like <c>@skip(if: $skip) -> something -> @skip(if: $skip)</c>,
/// we can get rid of the second @skip, since it will always be included.
/// </summary>
private static bool IsStaticallySkipped(
Conditional conditional,
Context context,
out Conditional? newConditional)
{
newConditional = conditional;
var current = context;
do
{
if (current.Conditional is { } parentConditional)
{
if (parentConditional.Skip is not null)
{
if (newConditional.Skip?.Equals(parentConditional.Skip, SyntaxComparison.Syntax) == true)
{
// If the parent has exactly the same @skip, we can remove the new one.
newConditional.Skip = null;
}
else if (ConditionalDirectiveHasSameVariable(parentConditional.Skip, newConditional.Include))
{
// If the parent has a @skip with the same variable as the new @include,
// the new @include will never be included, so the selection its on
// can be statically removed.
return true;
}
}
if (parentConditional.Include is not null)
{
if (newConditional.Include?.Equals(parentConditional.Include, SyntaxComparison.Syntax) == true)
{
// If the parent has exactly the same @include, we can remove the new one.
newConditional.Include = null;
}
else if (ConditionalDirectiveHasSameVariable(parentConditional.Include, newConditional.Skip))
{
// If the parent has a @include with the same variable as the new @skip,
// the new @skip will never be included, so the selection its on
// can be statically removed.
return true;
}
}
if (newConditional.Skip is null && newConditional.Include is null)
{
// Both of the @skip and @include in the new conditional have already
// appeared on a parent, so we can get rid of the entire conditional.
newConditional = null;
break;
}
}
current = current.Parent;
} while (current is not null);
return false;
}
private static bool ConditionalDirectiveHasSameVariable(DirectiveNode directive1, DirectiveNode? directive2)
{
if (directive2 is null)
{
return false;
}
var if1 = directive1.Arguments[0];
var if2 = directive2.Arguments[0];
return if1.Value.Equals(if2.Value, SyntaxComparison.Syntax);
}
private static bool IsStaticallySkipped(IHasDirectives directiveProvider)
{
if (directiveProvider.Directives.Count == 0)
{
return false;
}
foreach (var directive in directiveProvider.Directives)
{
if (directive.Name.Value.Equals(DirectiveNames.Skip.Name, StringComparison.Ordinal)
&& directive.Arguments is [{ Value: BooleanValueNode { Value: true } }])
{
return true;
}
if (directive.Name.Value.Equals(DirectiveNames.Include.Name, StringComparison.Ordinal)
&& directive.Arguments is [{ Value: BooleanValueNode { Value: false } }])
{
return true;
}
}
return false;
}
private static Dictionary<string, FragmentDefinitionNode> CreateFragmentLookup(DocumentNode document)
{
var lookup = new Dictionary<string, FragmentDefinitionNode>();
foreach (var definition in document.Definitions)
{
if (definition is FragmentDefinitionNode fragmentDef)
{
lookup.Add(fragmentDef.Name.Value, fragmentDef);
}
}
return lookup;
}
#endregion
#region Rewriting
private List<ISelectionNode>? RewriteSelections(Context context)
{
List<ISelectionNode>? selections = null;
if (context.Fields is not null)
{
foreach (var (_, fieldContextLookup) in context.Fields)
{
foreach (var (fieldNode, fieldContext) in fieldContextLookup)
{
var newFieldNode = RewriteField(fieldNode, fieldContext);
if (newFieldNode is null)
{
continue;
}
selections ??= [];
selections.Add(newFieldNode);
}
}
}
if (context.Fragments is not null)
{
foreach (var (_, fragmentContextLookup) in context.Fragments)
{
foreach (var (inlineFragmentNode, fragmentContext) in fragmentContextLookup)
{
var newInlineFragmentNode = RewriteInlineFragment(
inlineFragmentNode,
fragmentContext);
if (newInlineFragmentNode is null)
{
continue;
}
selections ??= [];
selections.Add(newInlineFragmentNode);
}
}
}
if (context.Conditionals is not null)
{
foreach (var (conditional, conditionalContext) in context.Conditionals)
{
var conditionalSelection = RewriteConditional(conditional, conditionalContext);
if (conditionalSelection is null)
{
continue;
}
selections ??= [];
selections.Add(conditionalSelection);
}
}
return selections;
}
private ISelectionNode? RewriteConditional(
Conditional conditional,
Context context)
{
var conditionalSelections = RewriteSelections(context);
if (conditionalSelections is null)
{
return null;
}
var conditionalDirectives = conditional.ToDirectives();
// If we only have a single selection and this selection does not have directives of its own,
// we can push the conditional directives down on it.
// Otherwise we return an inline fragment with all the conditional selections.
return conditionalSelections switch
{
[FieldNode { Directives.Count: 0 } fieldNode] => fieldNode
.WithDirectives([.. fieldNode.Directives, .. conditionalDirectives]),
[InlineFragmentNode { Directives.Count: 0 } inlineFragmentNode] => inlineFragmentNode
.WithDirectives([.. inlineFragmentNode.Directives, .. conditionalDirectives]),
_ => new InlineFragmentNode(
null,
null,
conditionalDirectives.ToArray(),
new SelectionSetNode(conditionalSelections))
};
}
private FieldNode? RewriteField(
FieldNode fieldNode,
Context? fieldContext)
{
if (fieldNode.SelectionSet is null)
{
return fieldNode;
}
if (fieldContext is null)
{
throw new InvalidOperationException("Expected to have field context");
}
var fieldSelections = RewriteSelections(fieldContext);
if (fieldSelections is null)
{
if (!removeStaticallyExcludedSelections)
{
return null;
}
fieldSelections = [s_typeNameField];
}
return fieldNode.WithSelectionSet(new SelectionSetNode(fieldSelections));
}
private InlineFragmentNode? RewriteInlineFragment(
InlineFragmentNode inlineFragmentNode,
Context fragmentContext)
{
var fragmentSelections = RewriteSelections(fragmentContext);
if (fragmentSelections is null)
{
if (!removeStaticallyExcludedSelections)
{
return null;
}
fragmentSelections = [s_typeNameField];
}
return inlineFragmentNode.WithSelectionSet(new SelectionSetNode(fragmentSelections));
}
private static IReadOnlyList<DirectiveNode> RewriteDirectives(IReadOnlyList<DirectiveNode> directives)
{
if (directives.Count == 0)
{
return directives;
}
if (directives.Count == 1)
{
return ImmutableArray<DirectiveNode>.Empty.Add(RewriteDirective(directives[0]));
}
var buffer = new DirectiveNode[directives.Count];
for (var i = 0; i < buffer.Length; i++)
{
buffer[i] = RewriteDirective(directives[i]);
}
return ImmutableArray.Create(buffer);
}
private static DirectiveNode RewriteDirective(DirectiveNode directive)
{
return new DirectiveNode(directive.Name.Value, RewriteArguments(directive.Arguments));
}
private static IReadOnlyList<ArgumentNode> RewriteArguments(IReadOnlyList<ArgumentNode> arguments)
{
if (arguments.Count == 0)
{
return arguments;
}
if (arguments.Count == 1)
{
return ImmutableArray<ArgumentNode>.Empty.Add(arguments[0].WithLocation(null));
}
var buffer = new ArgumentNode[arguments.Count];
for (var i = 0; i < buffer.Length; i++)
{
buffer[i] = arguments[i].WithLocation(null);
}
return ImmutableArray.Create(buffer);
}
#endregion
[DebuggerDisplay(
"{Type.Name}, Fields: {Fields?.Count}, Fragments: {Fragments?.Count}, Conditionals: {Conditionals?.Count}")]
|
DocumentRewriter
|
csharp
|
dotnet__BenchmarkDotNet
|
samples/BenchmarkDotNet.Samples/IntroUnicode.cs
|
{
"start": 623,
"end": 1004
}
|
private class ____ : ManualConfig
{
public Config() => AddLogger(ConsoleLogger.Unicode);
}
[Benchmark]
public long Foo()
{
long waitUntil = Stopwatch.GetTimestamp() + 1000;
while (Stopwatch.GetTimestamp() < waitUntil) { }
return waitUntil;
}
}
// *** Fluent Config ***
|
Config
|
csharp
|
ChilliCream__graphql-platform
|
src/HotChocolate/Adapters/test/Adapters.Mcp.Tests/FusionIntegrationTests.cs
|
{
"start": 802,
"end": 8998
}
|
public sealed class ____ : IntegrationTestBase
{
[Fact]
public async Task ListTools_AfterSchemaUpdate_ReturnsUpdatedTools()
{
// arrange
var storage = new TestOperationToolStorage();
await storage.AddOrUpdateToolAsync(
new OperationToolDefinition(
Utf8GraphQLParser.Parse(
await File.ReadAllTextAsync("__resources__/GetBooksWithTitle1.graphql"))));
var subgraph = CreateSubgraph([]);
var schemaDocument = await subgraph.Services.GetSchemaAsync();
var schemaComposer =
new SchemaComposer(
[new SourceSchemaText(schemaDocument.Name, schemaDocument.ToString())],
new SchemaComposerOptions(),
new CompositionLog());
var result = schemaComposer.Compose();
var schema = result.Value;
var initialConfig =
new FusionConfiguration(
schema.ToSyntaxNode(),
new JsonDocumentOwner(JsonDocument.Parse("{ }"), new EmptyMemoryOwner()));
var configProvider = new TestFusionConfigurationProvider(initialConfig);
var builder = new WebHostBuilder()
.ConfigureServices(
services => services
.AddRouting()
.AddGraphQLGatewayServer()
.AddConfigurationProvider(_ => configProvider)
.AddMcp()
.AddMcpToolStorage(storage))
.Configure(
app => app
.UseRouting()
.UseEndpoints(endpoints => endpoints.MapGraphQLMcp()));
var server = new TestServer(builder);
var mcpClient1 = await CreateMcpClientAsync(server.CreateClient());
var mcpClient2 = await CreateMcpClientAsync(server.CreateClient());
var listChangedResetEvent1 = new ManualResetEventSlim(false);
var listChangedResetEvent2 = new ManualResetEventSlim(false);
mcpClient1.RegisterNotificationHandler(
NotificationMethods.ToolListChangedNotification,
async (_, _) =>
{
listChangedResetEvent1.Set();
await ValueTask.CompletedTask;
});
mcpClient2.RegisterNotificationHandler(
NotificationMethods.ToolListChangedNotification,
async (_, _) =>
{
listChangedResetEvent2.Set();
await ValueTask.CompletedTask;
});
// act
var tools = await mcpClient1.ListToolsAsync();
((MutableObjectTypeDefinition)schema.Types["Book"]).Fields["title"].Description = "Description";
var newConfig =
new FusionConfiguration(
schema.ToSyntaxNode(),
new JsonDocumentOwner(JsonDocument.Parse("{ }"), new EmptyMemoryOwner()));
configProvider.UpdateConfiguration(newConfig);
IList<McpClientTool>? updatedTools = null;
if (listChangedResetEvent1.Wait(TimeSpan.FromSeconds(5)))
{
var mcpClient3 = await CreateMcpClientAsync(server.CreateClient());
updatedTools = await mcpClient3.ListToolsAsync();
}
var secondClientNotified = listChangedResetEvent2.Wait(TimeSpan.FromSeconds(5));
// assert
Assert.NotNull(updatedTools);
JsonSerializer.Serialize(
tools.Concat(updatedTools).Select(
t =>
new
{
t.Name,
t.Title,
t.Description,
t.JsonSchema,
t.ReturnJsonSchema
}),
JsonSerializerOptions)
.ReplaceLineEndings("\n")
.MatchSnapshot(extension: ".json");
Assert.True(secondClientNotified);
}
protected override async Task<TestServer> CreateTestServerAsync(
IOperationToolStorage storage,
ITypeDefinition[]? additionalTypes = null,
McpDiagnosticEventListener? diagnosticEventListener = null,
Action<McpServerOptions>? configureMcpServerOptions = null,
Action<IMcpServerBuilder>? configureMcpServer = null)
{
var subgraph = CreateSubgraph(additionalTypes);
var schemaDocument = await subgraph.Services.GetSchemaAsync();
var schemaComposer =
new SchemaComposer(
[new SourceSchemaText(schemaDocument.Name, schemaDocument.ToString())],
new SchemaComposerOptions(),
new CompositionLog());
var result = schemaComposer.Compose();
var builder = new WebHostBuilder()
.ConfigureServices(
services =>
{
services
.AddHeaderPropagation(options => options.Headers.Add("Authorization"))
.AddLogging()
.AddRouting()
.AddAuthentication();
services
.AddHttpClient(schemaDocument.Name)
.AddHeaderPropagation()
.ConfigurePrimaryHttpMessageHandler(() => subgraph.CreateHandler());
var builder =
services
.AddGraphQLGatewayServer()
.ModifyRequestOptions(o => o.IncludeExceptionDetails = true)
.AddInMemoryConfiguration(result.Value.ToSyntaxNode())
.AddHttpClientConfiguration(
schemaDocument.Name,
new Uri("http://localhost:5000/graphql"))
.AddMcp(configureMcpServerOptions, configureMcpServer)
.AddMcpToolStorage(storage);
if (diagnosticEventListener is not null)
{
builder.AddDiagnosticEventListener(_ => diagnosticEventListener);
}
})
.Configure(
app => app
.UseRouting()
.UseHeaderPropagation()
.UseAuthentication()
.UseEndpoints(endpoints => endpoints.MapGraphQLMcp()));
return new TestServer(builder);
}
private static TestServer CreateSubgraph(ITypeDefinition[]? additionalTypes)
{
var builder = new WebHostBuilder()
.ConfigureServices(
services =>
{
services
.AddLogging()
.AddRouting()
.AddAuthentication()
.AddJwtBearer(
o => o.TokenValidationParameters =
new TokenValidationParameters
{
ValidIssuer = TokenIssuer,
ValidAudience = TokenAudience,
IssuerSigningKey = TokenKey
});
var builder =
services
.AddGraphQLServer()
.AddAuthorization()
.AddQueryType<TestSchema.Query>()
.AddMutationType<TestSchema.Mutation>()
.AddInterfaceType<TestSchema.IPet>()
.AddUnionType<TestSchema.IPet>()
.AddObjectType<TestSchema.Cat>()
.AddObjectType<TestSchema.Dog>();
if (additionalTypes is not null)
{
builder.AddTypes(additionalTypes);
}
})
.Configure(
app => app
.UseRouting()
.UseAuthentication()
.UseEndpoints(endpoints => endpoints.MapGraphQL()));
return new TestServer(builder);
}
|
FusionIntegrationTests
|
csharp
|
AvaloniaUI__Avalonia
|
src/Avalonia.Base/Rendering/SceneGraph/CustomDrawOperation.cs
|
{
"start": 132,
"end": 1068
}
|
public interface ____ : IEquatable<ICustomDrawOperation>, IDisposable
{
/// <summary>
/// Gets the bounds of the visible content in the node in global coordinates.
/// </summary>
Rect Bounds { get; }
/// <summary>
/// Hit test the geometry in this node.
/// </summary>
/// <param name="p">The point in global coordinates.</param>
/// <returns>True if the point hits the node's geometry; otherwise false.</returns>
/// <remarks>
/// This method does not recurse to childs, if you want
/// to hit test children they must be hit tested manually.
/// </remarks>
bool HitTest(Point p);
/// <summary>
/// Renders the node to a drawing context.
/// </summary>
/// <param name="context">The drawing context.</param>
void Render(ImmediateDrawingContext context);
}
}
|
ICustomDrawOperation
|
csharp
|
microsoft__garnet
|
test/Garnet.test.cluster/RedirectTests/BaseCommand.cs
|
{
"start": 61009,
"end": 61617
}
|
internal class ____ : BaseCommand
{
public override bool IsArrayCommand => false;
public override bool ArrayResponse => false;
public override string Command => nameof(GEOADD);
public override string[] GetSingleSlotRequest()
{
var ssk = GetSingleSlotKeys;
return [ssk[0], "13.361389", "38.115556", "city"];
}
public override string[] GetCrossSlotRequest() => throw new NotImplementedException();
public override ArraySegment<string>[] SetupSingleSlotRequest() => throw new NotImplementedException();
}
|
GEOADD
|
csharp
|
dotnet__efcore
|
test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTest.cs
|
{
"start": 404501,
"end": 413744
}
|
protected class ____;
[ConditionalFact]
public void SeedData_and_PK_rename()
=> Execute(
_ => { },
source => source.Entity(
"EntityWithTwoProperties",
x =>
{
x.Property<int>("Key");
x.Property<int>("Value1");
x.Property<string>("Value2");
x.HasKey("Key");
}),
target => target.Entity(
"EntityWithTwoProperties",
x =>
{
x.Property<int>("Id");
x.Property<int>("Value1");
x.Property<string>("Value2");
x.HasData(
new { Id = 42, Value1 = 32 });
}),
upOps => Assert.Collection(
upOps,
o =>
{
var operation = Assert.IsType<RenameColumnOperation>(o);
Assert.Equal("EntityWithTwoProperties", operation.Table);
Assert.Equal("Key", operation.Name);
Assert.Equal("Id", operation.NewName);
},
o =>
{
var m = Assert.IsType<InsertDataOperation>(o);
Assert.Equal(new[] { "Id", "Value1", "Value2" }, m.Columns);
Assert.Null(m.ColumnTypes);
AssertMultidimensionalArray(
m.Values,
v => Assert.Equal(42, v),
v => Assert.Equal(32, v),
Assert.Null);
}),
downOps => Assert.Collection(
downOps,
o =>
{
var m = Assert.IsType<DeleteDataOperation>(o);
Assert.Equal(new[] { "Id" }, m.KeyColumns);
Assert.Null(m.KeyColumnTypes);
AssertMultidimensionalArray(
m.KeyValues,
v => Assert.Equal(42, v));
},
o =>
{
var operation = Assert.IsType<RenameColumnOperation>(o);
Assert.Equal("EntityWithTwoProperties", operation.Table);
Assert.Equal("Id", operation.Name);
Assert.Equal("Key", operation.NewName);
}));
[ConditionalFact]
public void SeedData_and_change_PK_type()
=> Execute(
_ => { },
source => source.Entity(
"EntityWithTwoProperties",
x =>
{
x.Property<string>("Key");
x.Property<int>("Value1");
x.Property<string>("Value2");
x.HasKey("Key");
}),
target => target.Entity(
"EntityWithTwoProperties",
x =>
{
x.Property<int>("Id");
x.Property<int>("Value1");
x.Property<string>("Value2");
x.HasData(
new { Id = 42, Value1 = 32 });
}),
upOps => Assert.Collection(
upOps,
o =>
{
var operation = Assert.IsType<DropPrimaryKeyOperation>(o);
Assert.Equal("EntityWithTwoProperties", operation.Table);
Assert.Equal("PK_EntityWithTwoProperties", operation.Name);
},
o =>
{
var operation = Assert.IsType<DropColumnOperation>(o);
Assert.Equal("EntityWithTwoProperties", operation.Table);
Assert.Equal("Key", operation.Name);
},
o =>
{
var operation = Assert.IsType<AddColumnOperation>(o);
Assert.Equal("EntityWithTwoProperties", operation.Table);
Assert.Equal("Id", operation.Name);
},
o =>
{
var operation = Assert.IsType<AddPrimaryKeyOperation>(o);
Assert.Equal("EntityWithTwoProperties", operation.Table);
Assert.Equal("PK_EntityWithTwoProperties", operation.Name);
Assert.Equal(new[] { "Id" }, operation.Columns);
},
o =>
{
var m = Assert.IsType<InsertDataOperation>(o);
AssertMultidimensionalArray(
m.Values,
v => Assert.Equal(42, v),
v => Assert.Equal(32, v),
Assert.Null);
}),
downOps => Assert.Collection(
downOps,
o =>
{
var operation = Assert.IsType<DropPrimaryKeyOperation>(o);
Assert.Equal("EntityWithTwoProperties", operation.Table);
Assert.Equal("PK_EntityWithTwoProperties", operation.Name);
},
o =>
{
var m = Assert.IsType<DeleteDataOperation>(o);
Assert.Equal(new[] { "Id" }, m.KeyColumns);
Assert.Equal(new[] { "default_int_mapping" }, m.KeyColumnTypes);
AssertMultidimensionalArray(
m.KeyValues,
v => Assert.Equal(42, v));
},
o =>
{
var operation = Assert.IsType<DropColumnOperation>(o);
Assert.Equal("EntityWithTwoProperties", operation.Table);
Assert.Equal("Id", operation.Name);
},
o =>
{
var operation = Assert.IsType<AddColumnOperation>(o);
Assert.Equal("EntityWithTwoProperties", operation.Table);
Assert.Equal("Key", operation.Name);
},
o =>
{
var operation = Assert.IsType<AddPrimaryKeyOperation>(o);
Assert.Equal("EntityWithTwoProperties", operation.Table);
Assert.Equal("PK_EntityWithTwoProperties", operation.Name);
Assert.Equal(new[] { "Key" }, operation.Columns);
}));
[ConditionalFact]
public void SeedData_binary_change()
=> Execute(
_ => { },
source => source.Entity(
"EntityWithTwoProperties",
x =>
{
x.Property<int>("Id");
x.Property<byte[]>("Value1");
x.HasData(
new { Id = 42, Value1 = new byte[] { 2, 1 } });
}),
target => target.Entity(
"EntityWithTwoProperties",
x =>
{
x.Property<int>("Id");
x.Property<byte[]>("Value1");
x.HasData(
new { Id = 42, Value1 = new byte[] { 1, 2 } });
}),
upOps => Assert.Collection(
upOps,
o =>
{
var m = Assert.IsType<UpdateDataOperation>(o);
AssertMultidimensionalArray(
m.KeyValues,
v => Assert.Equal(42, v));
AssertMultidimensionalArray(
m.Values,
v => Assert.Equal(new byte[] { 1, 2 }, v));
}),
downOps => Assert.Collection(
downOps,
o =>
{
var m = Assert.IsType<UpdateDataOperation>(o);
AssertMultidimensionalArray(
m.KeyValues,
v => Assert.Equal(42, v));
AssertMultidimensionalArray(
m.Values,
v => Assert.Equal(new byte[] { 2, 1 }, v));
}));
[ConditionalFact]
public void SeedData_binary_change_custom_comparer()
=> Execute(
source => source.Entity(
"EntityWithTwoProperties",
x =>
{
x.Property<int>("Id");
x.Property<byte[]>("Value1").HasConversion(typeof(byte[]), null, new RightmostValueComparer());
}),
source => source.Entity(
"EntityWithTwoProperties",
x =>
{
x.HasData(
new { Id = 42, Value1 = new byte[] { 0, 1 } });
}),
target => target.Entity(
"EntityWithTwoProperties",
x =>
{
x.HasData(
new { Id = 42, Value1 = new byte[] { 1 } });
}),
upOps => Assert.Empty(upOps),
downOps => Assert.Empty(downOps));
|
SomeOwnedEntity
|
csharp
|
scriban__scriban
|
src/Scriban/Runtime/CustomFunction.Generated.cs
|
{
"start": 37481,
"end": 38322
}
|
private partial class ____ : DynamicCustomFunction
{
private delegate bool InternalDelegate(string arg0);
private readonly InternalDelegate _delegate;
public Functionbool_string(MethodInfo method) : base(method)
{
_delegate = (InternalDelegate)method.CreateDelegate(typeof(InternalDelegate));
}
public override object Invoke(TemplateContext context, ScriptNode callerContext, ScriptArray arguments, ScriptBlockStatement blockStatement)
{
var arg0 = (string)arguments[0];
return _delegate(arg0);
}
}
/// <summary>
/// Optimized custom function for: bool (TemplateContext, SourceSpan, IEnumerable, object, Object[])
/// </summary>
|
Functionbool_string
|
csharp
|
ServiceStack__ServiceStack
|
ServiceStack.Aws/src/ServiceStack.Aws/DynamoDb/DynamoCodes.cs
|
{
"start": 4130,
"end": 4400
}
|
public class ____ : AttributeBase
{
public int ReadCapacityUnits { get; set; }
public int WriteCapacityUnits { get; set; }
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
|
ProvisionedThroughputAttribute
|
csharp
|
dotnet__efcore
|
test/EFCore.Specification.Tests/TestUtilities/QueryAsserter.cs
|
{
"start": 78987,
"end": 80415
}
|
private class ____(QueryTrackingBehavior queryTrackingBehavior) : ExpressionVisitor
{
private static readonly MethodInfo AsNoTrackingMethodInfo
= typeof(EntityFrameworkQueryableExtensions).GetTypeInfo()
.GetDeclaredMethod(nameof(EntityFrameworkQueryableExtensions.AsNoTracking))!;
private static readonly MethodInfo AsNoTrackingWithIdentityResolutionMethodInfo
= typeof(EntityFrameworkQueryableExtensions).GetTypeInfo()
.GetDeclaredMethod(nameof(EntityFrameworkQueryableExtensions.AsNoTrackingWithIdentityResolution))!;
protected override Expression VisitExtension(Expression expression)
=> expression is EntityQueryRootExpression root
? queryTrackingBehavior switch
{
QueryTrackingBehavior.NoTracking
=> Expression.Call(AsNoTrackingMethodInfo.MakeGenericMethod(root.ElementType), root),
QueryTrackingBehavior.NoTrackingWithIdentityResolution
=> Expression.Call(AsNoTrackingWithIdentityResolutionMethodInfo.MakeGenericMethod(root.ElementType), root),
QueryTrackingBehavior.TrackAll
=> base.VisitExtension(expression),
_ => throw new UnreachableException()
}
: base.VisitExtension(expression);
}
}
|
TrackingRewriter
|
csharp
|
dotnetcore__FreeSql
|
Providers/FreeSql.Provider.KingbaseES/Curd/KingbaseESSelect.cs
|
{
"start": 19414,
"end": 19988
}
|
class ____ T9 : class
{
public KingbaseESSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { }
public override string ToSql(string field = null) => KingbaseESSelect<T1>.ToSqlStatic(_commonUtils, _commonExpression, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, this.GetTableRuleUnions(), _aliasRule, _tosqlAppendContent, _whereGlobalFilter, _orm);
}
|
where
|
csharp
|
microsoft__garnet
|
libs/server/Objects/List/ListObject.cs
|
{
"start": 805,
"end": 1098
}
|
public enum ____ : byte
{
/// <summary>
/// Left or head
/// </summary>
Left,
/// <summary>
/// Right or tail
/// </summary>
Right,
Unknown,
}
/// <summary>
/// List
/// </summary>
|
OperationDirection
|
csharp
|
ServiceStack__ServiceStack
|
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/AttributeFiltersTestAsync.cs
|
{
"start": 12082,
"end": 12663
}
|
public class ____ : RequestFilterAsyncAttribute
{
public ExecutedFirstAsyncAttribute()
{
Priority = int.MinValue;
}
public override Task ExecuteAsync(IRequest req, IResponse res, object requestDto)
{
var dto = (AttributeFilteredAsync)requestDto;
dto.AttrsExecuted.Add(GetType().Name);
return TypeConstants.EmptyTask;
}
}
[ExecutedFirstAsync]
[FilterTestAsync]
[RequiredRole("test")]
[Authenticate]
[RequiredPermission("test")]
|
ExecutedFirstAsyncAttribute
|
csharp
|
dotnet__efcore
|
test/EFCore.Specification.Tests/TestModels/SnapshotMonsterContext.cs
|
{
"start": 6677,
"end": 7021
}
|
public class ____ : IOrderLine
{
public int OrderId { get; set; }
public int ProductId { get; set; }
public int Quantity { get; set; } = 1;
public string ConcurrencyToken { get; set; }
public virtual IAnOrder Order { get; set; }
public virtual IProduct Product { get; set; }
}
|
OrderLine
|
csharp
|
dotnet__orleans
|
src/Orleans.TestingHost/InProcess/InProcessMembershipTable.cs
|
{
"start": 333,
"end": 2421
}
|
internal sealed class ____(string clusterId) : IMembershipTable, IGatewayListProvider
{
private readonly Table _table = new();
private readonly string _clusterId = clusterId;
public TimeSpan MaxStaleness => TimeSpan.Zero;
public bool IsUpdatable => true;
public Task InitializeMembershipTable(bool tryInitTableVersion) => Task.CompletedTask;
public Task DeleteMembershipTableEntries(string clusterId)
{
if (string.Equals(_clusterId, clusterId, StringComparison.Ordinal))
{
_table.Clear();
}
return Task.CompletedTask;
}
public Task<MembershipTableData> ReadRow(SiloAddress key) => Task.FromResult(_table.Read(key));
public Task<MembershipTableData> ReadAll() => Task.FromResult(_table.ReadAll());
public Task<bool> InsertRow(MembershipEntry entry, TableVersion tableVersion) => Task.FromResult(_table.Insert(entry, tableVersion));
public Task<bool> UpdateRow(MembershipEntry entry, string etag, TableVersion tableVersion) => Task.FromResult(_table.Update(entry, etag, tableVersion));
public Task UpdateIAmAlive(MembershipEntry entry)
{
_table.UpdateIAmAlive(entry);
return Task.CompletedTask;
}
public Task CleanupDefunctSiloEntries(DateTimeOffset beforeDate)
{
_table.CleanupDefunctSiloEntries(beforeDate);
return Task.CompletedTask;
}
public Task InitializeGatewayListProvider() => Task.CompletedTask;
public Task<IList<Uri>> GetGateways()
{
var table = _table.ReadAll();
var result = table.Members
.Where(x => x.Item1.Status == SiloStatus.Active && x.Item1.ProxyPort != 0)
.Select(x =>
{
var entry = x.Item1;
return SiloAddress.New(entry.SiloAddress.Endpoint.Address, entry.ProxyPort, entry.SiloAddress.Generation).ToGatewayUri();
}).ToList();
return Task.FromResult<IList<Uri>>(result);
}
public SiloStatus GetSiloStatus(SiloAddress address) => _table.GetSiloStatus(address);
|
InProcessMembershipTable
|
csharp
|
mongodb__mongo-csharp-driver
|
src/MongoDB.Driver/Linq/Linq3Implementation/Ast/AstNode.cs
|
{
"start": 750,
"end": 1142
}
|
internal abstract class ____
{
public abstract AstNodeType NodeType { get; }
public abstract AstNode Accept(AstNodeVisitor visitor);
public abstract BsonValue Render();
public override string ToString()
{
var jsonWriterSettings = new JsonWriterSettings();
return Render().ToJson(jsonWriterSettings);
}
}
}
|
AstNode
|
csharp
|
CommunityToolkit__dotnet
|
tests/CommunityToolkit.Mvvm.Internals.UnitTests/Test_Dictionary2.cs
|
{
"start": 429,
"end": 5164
}
|
public class ____
{
private static void AddItems<T>(T[] keys)
where T : IEquatable<T>
{
object[] values = Enumerable.Range(0, keys.Length).Select(static x => new object()).ToArray();
Dictionary2<T, object> dictionary = new();
// Go through all keys once
for (int i = 0; i < keys.Length; i++)
{
T key = keys[i];
// Verify the key doesn't exist yet
Assert.AreEqual(i, dictionary.Count);
Assert.IsFalse(dictionary.ContainsKey(key));
Assert.IsFalse(dictionary.TryGetValue(key, out object? obj));
Assert.IsNull(obj);
Assert.IsFalse(dictionary.TryRemove(key));
_ = Assert.ThrowsExactly<ArgumentException>(() => _ = dictionary[key]);
// This should create a new entry
ref object? value = ref dictionary.GetOrAddValueRef(key);
Assert.IsNull(value);
value = values[i];
// Verify the key now exists
Assert.IsTrue(dictionary.ContainsKey(key));
Assert.IsTrue(dictionary.TryGetValue(key, out obj));
Assert.AreSame(obj, value);
Assert.AreSame(obj, values[i]);
// Get the key again, should point to the same location
ref object? value2 = ref dictionary.GetOrAddValueRef(key);
Assert.IsTrue(Unsafe.AreSame(ref value, ref value2!));
}
Assert.AreEqual(keys.Length, dictionary.Count);
HashSet<T> keysSet = new();
HashSet<object> valuesSet = new();
Dictionary2<T, object>.Enumerator enumerator = dictionary.GetEnumerator();
// Gather all key/value pairs through the enumerator
while (enumerator.MoveNext())
{
Assert.IsTrue(keysSet.Add(enumerator.GetKey()));
Assert.IsTrue(valuesSet.Add(enumerator.GetValue()));
}
// Verify we have all values we expect
CollectionAssert.AreEquivalent(keys, keysSet.ToArray());
CollectionAssert.AreEquivalent(values, valuesSet.ToArray());
dictionary.Clear();
// Verify the dictionary was cleared properly
Assert.AreEqual(0, dictionary.Count);
enumerator = dictionary.GetEnumerator();
while (enumerator.MoveNext())
{
// Since the dictionary is now empty, we should never get here
Assert.Fail();
}
}
[TestMethod]
[DataRow(1)]
[DataRow(101)]
[DataRow(2467)]
public void AddItems_Int(int count)
{
AddItems(Enumerable.Range(0, count).ToArray());
}
[TestMethod]
[DataRow(1)]
[DataRow(101)]
[DataRow(2467)]
public void AddItems_String(int count)
{
AddItems(Enumerable.Range(0, count).Select(static x => x.ToString()).ToArray());
}
private static void TryRemoveItems<T>(T[] keys)
where T : IEquatable<T>
{
object[] values = Enumerable.Range(0, keys.Length).Select(static x => new object()).ToArray();
Dictionary2<T, object> dictionary = new();
// Populate the dictionary
for (int i = 0; i < keys.Length; i++)
{
T key = keys[i];
dictionary.GetOrAddValueRef(key) = values[i];
}
Random random = new(42);
keys = keys
.Select(x => (Key: x, Index: random.Next()))
.OrderBy(static x => x.Index)
.Select(static x => x.Key)
.ToArray();
values = keys.Select(k => dictionary[k]).ToArray();
for (int i = 0; i < keys.Length; i++)
{
T key = keys[i];
// Verify the state is consistent across removals
Assert.AreEqual(keys.Length - i, dictionary.Count);
Assert.IsTrue(dictionary.ContainsKey(key));
Assert.IsTrue(dictionary.TryGetValue(key, out object? obj));
Assert.AreSame(values[i], obj);
// Remove the item
Assert.IsTrue(dictionary.TryRemove(key));
// Verify the state is consistent after the removal
Assert.IsFalse(dictionary.ContainsKey(key));
Assert.IsFalse(dictionary.TryGetValue(key, out obj));
Assert.IsNull(obj);
}
Assert.AreEqual(0, dictionary.Count);
}
[TestMethod]
[DataRow(1)]
[DataRow(101)]
[DataRow(2467)]
public void TryRemoveItems_Int(int count)
{
TryRemoveItems(Enumerable.Range(0, count).ToArray());
}
[TestMethod]
[DataRow(1)]
[DataRow(101)]
[DataRow(2467)]
public void TryRemoveItems_String(int count)
{
TryRemoveItems(Enumerable.Range(0, count).Select(static x => x.ToString()).ToArray());
}
}
|
Test_Dictionary2
|
csharp
|
MassTransit__MassTransit
|
tests/MassTransit.Azure.Table.Tests/AzureTableInMemoryTestFixture.cs
|
{
"start": 232,
"end": 2126
}
|
public abstract class ____ :
InMemoryTestFixture
{
protected readonly string ConnectionString;
protected readonly TableClient TestCloudTable;
protected readonly string TestTableName;
protected AzureTableInMemoryTestFixture()
{
ConnectionString = Configuration.StorageAccount;
TestTableName = "azuretabletests";
var tableServiceClient = new TableServiceClient(ConnectionString);
TestCloudTable = tableServiceClient.GetTableClient(TestTableName);
}
protected override void ConfigureInMemoryBus(IInMemoryBusFactoryConfigurator configurator)
{
configurator.UseDelayedMessageScheduler();
base.ConfigureInMemoryBus(configurator);
}
public IEnumerable<T> GetRecords<T>()
where T : class, ITableEntity, new()
{
return TestCloudTable.Query<T>().ToList();
}
public IEnumerable<TableEntity> GetTableEntities()
{
return TestCloudTable.Query<TableEntity>();
}
[OneTimeSetUp]
public async Task Bring_it_up()
{
await TestCloudTable.CreateIfNotExistsAsync();
IEnumerable<TableEntity> entities = GetTableEntities();
IEnumerable<IGrouping<string, TableEntity>> groupedEntities = entities.GroupBy(e => e.PartitionKey);
foreach (IGrouping<string, TableEntity> group in groupedEntities)
{
List<TableTransactionAction> batchOperations = group
.Select(entity => new TableTransactionAction(TableTransactionActionType.Delete, entity))
.ToList();
// Execute the batch transaction
await TestCloudTable.SubmitTransactionAsync(batchOperations);
}
}
}
}
|
AzureTableInMemoryTestFixture
|
csharp
|
ServiceStack__ServiceStack
|
ServiceStack/src/ServiceStack.NetFramework/SmartThreadPool/AppSelfHostBase.cs
|
{
"start": 192,
"end": 4525
}
|
public abstract class ____
: AppHostHttpListenerBase
{
private readonly ILog log = LogManager.GetLogger(typeof(AppSelfHostBase));
private readonly AutoResetEvent listenForNextRequest = new(initialState:false);
private readonly Amib.Threading.SmartThreadPool threadPoolManager;
private const int IdleTimeout = 300;
protected AppSelfHostBase(string serviceName, params Assembly[] assembliesWithServices)
: base(serviceName, assembliesWithServices)
{
threadPoolManager = new Amib.Threading.SmartThreadPool(IdleTimeout,
maxWorkerThreads: Math.Max(16, Environment.ProcessorCount * 2));
}
protected AppSelfHostBase(string serviceName, string handlerPath, params Assembly[] assembliesWithServices)
: base(serviceName, handlerPath, assembliesWithServices)
{
threadPoolManager = new Amib.Threading.SmartThreadPool(IdleTimeout,
maxWorkerThreads: Math.Max(16, Environment.ProcessorCount * 2));
}
private bool disposed = false;
protected override void Dispose(bool disposing)
{
if (disposed) return;
lock (this)
{
if (disposed) return;
if (disposing)
threadPoolManager.Dispose();
// new shared cleanup logic
disposed = true;
base.Dispose(disposing);
}
}
private bool IsListening => this.IsStarted && this.Listener != null && this.Listener.IsListening;
// Loop here to begin processing of new requests.
protected override void Listen(object state)
{
while (IsListening)
{
if (Listener == null) return;
try
{
Listener.BeginGetContext(ListenerCallback, Listener);
listenForNextRequest.WaitOne();
}
catch (Exception ex)
{
log.Error("Listen()", ex);
return;
}
if (Listener == null) return;
}
}
// Handle the processing of a request in here.
private void ListenerCallback(IAsyncResult asyncResult)
{
var listener = asyncResult.AsyncState as HttpListener;
HttpListenerContext context;
if (listener == null) return;
var isListening = listener.IsListening;
try
{
if (!isListening)
{
log.DebugFormat("Ignoring ListenerCallback() as HttpListener is no longer listening");
return;
}
// The EndGetContext() method, as with all Begin/End asynchronous methods in the .NET Framework,
// blocks until there is a request to be processed or some type of data is available.
context = listener.EndGetContext(asyncResult);
}
catch (Exception ex)
{
// You will get an exception when httpListener.Stop() is called
// because there will be a thread stopped waiting on the .EndGetContext()
// method, and again, that is just the way most Begin/End asynchronous
// methods of the .NET Framework work.
string errMsg = ex + ": " + isListening;
log.Warn(errMsg);
return;
}
finally
{
// Once we know we have a request (or exception), we signal the other thread
// so that it calls the BeginGetContext() (or possibly exits if we're not
// listening any more) method to start handling the next incoming request
// while we continue to process this request on a different thread.
listenForNextRequest.Set();
}
if (Config.DebugMode && log.IsDebugEnabled)
log.Debug($"{context.Request.UserHostAddress} Request : {context.Request.RawUrl}");
OnBeginRequest(context);
threadPoolManager.QueueWorkItem(ProcessRequestContext, context);
}
}
}
#endif
|
AppSelfHostBase
|
csharp
|
MassTransit__MassTransit
|
tests/MassTransit.Tests/Pipeline/ContentFilter_Specs.cs
|
{
"start": 1511,
"end": 1853
}
|
class ____ :
IConsumer<TestMessage>
{
int _count;
public int Count => _count;
public Task Consume(ConsumeContext<TestMessage> context)
{
Interlocked.Increment(ref _count);
return Task.CompletedTask;
}
}
|
MyConsumer
|
csharp
|
microsoft__PowerToys
|
src/modules/EnvironmentVariables/EnvironmentVariablesUILib/Telemetry/TelemetryInstance.cs
|
{
"start": 278,
"end": 387
}
|
public static class ____
{
public static ITelemetry Telemetry { get; set; }
}
}
|
TelemetryInstance
|
csharp
|
smartstore__Smartstore
|
src/Smartstore.Core/Platform/Search/Facets/FacetGroup.cs
|
{
"start": 74,
"end": 417
}
|
public enum ____
{
Unknown = -1,
Category,
Brand,
Price,
Rating,
DeliveryTime,
Availability,
NewArrivals,
Attribute,
Variant,
Forum,
Customer,
Date
}
[DebuggerDisplay("Key: {Key}, Label: {Label}, Kind: {Kind}")]
|
FacetGroupKind
|
csharp
|
protobuf-net__protobuf-net
|
src/Examples/Issues/Issue41.cs
|
{
"start": 156,
"end": 375
}
|
public class ____
{
[ProtoMember(1, Name = "PropA")]
public string PropA { get; set; }
[ProtoMember(2, Name = "PropB")]
public string PropB { get; set; }
}
[ProtoContract]
|
A
|
csharp
|
protobuf-net__protobuf-net
|
assorted/Net11_Poco/DAL.cs
|
{
"start": 2553,
"end": 3837
}
|
public class ____
#if REMOTING
: ISerializable
#endif
#if PLAT_XMLSERIALIZER
, IXmlSerializable
#endif
{
public const bool MASTER_GROUP = false;
[ProtoMember(1, DataFormat = Database.SubObjectFormat), Tag(1)]
[XmlArray]
public OrderList Orders;
public DatabaseCompatRem()
{
Orders = new OrderList();
}
#region ISerializable Members
#if REMOTING
protected DatabaseCompatRem(SerializationInfo info, StreamingContext context)
: this()
{
Serializer.Merge<DatabaseCompatRem>(info, this);
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
Serializer.Serialize <DatabaseCompatRem>(info, this);
}
#endif
#endregion
#region IXmlSerializable Members
#if PLAT_XMLSERIALIZER
System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
void IXmlSerializable.ReadXml(System.Xml.XmlReader reader)
{
Serializer.Merge(reader, this);
}
void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
{
Serializer.Serialize(writer, this);
}
#endif
#endregion
}
[ProtoContract, Serializable]
|
DatabaseCompatRem
|
csharp
|
ServiceStack__ServiceStack
|
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/ScriptTests/SharpViewsTests.cs
|
{
"start": 578,
"end": 753
}
|
public class ____ : IReturn<TemplateViewPageRequest>
{
public string Name { get; set; }
}
[Route("/view-pages-nested/{Name}")]
|
TemplateViewPageRequest
|
csharp
|
ServiceStack__ServiceStack
|
ServiceStack.Text/tests/ServiceStack.Text.Tests/AutoMappingTests.cs
|
{
"start": 16936,
"end": 18085
}
|
public class ____
{
public int Id { get; set; }
public string ITN { get; set; }
}
[Test]
public void Does_retain_null_properties()
{
var user = new User { FirstName = "Foo" };
var userDto = user.ConvertTo<UserFields>();
Assert.That(userDto.FirstName, Is.EqualTo("Foo"));
Assert.That(userDto.LastName, Is.Null);
Assert.That(userDto.Car, Is.Null);
var customer = new Customer { CompanyInfo = null };
var dto = customer.ConvertTo<CustomerDto>();
Assert.That(dto.CompanyInfo, Is.Null);
}
[Test]
public void Does_ignore_properties_without_attributes()
{
var model = new ModelWithIgnoredFields
{
Id = 1,
Name = "Foo",
Ignored = 2
};
var dto = new ModelWithIgnoredFields { Ignored = 10 }
.PopulateFromPropertiesWithoutAttribute(model, typeof(ReadOnlyAttribute));
Assert.That(dto.Id, Is.EqualTo(model.Id));
Assert.That(dto.Name, Is.EqualTo(model.Name));
Assert.That(dto.Ignored, Is.EqualTo(10));
}
#if !NETCORE
|
CompanyInfoDto
|
csharp
|
dotnetcore__Util
|
src/Util.Ui.NgZorro/Components/Tables/Builders/Contents/ISelectCreateService.cs
|
{
"start": 110,
"end": 757
}
|
public interface ____ {
/// <summary>
/// 创建表格列复选框
/// </summary>
/// <param name="builder">表格单元格标签生成器</param>
/// <param name="content">内容</param>
void CreateCheckbox( TableColumnBuilder builder, IHtmlContent content );
/// <summary>
/// 创建表格列单选框
/// </summary>
/// <param name="builder">表格单元格标签生成器</param>
/// <param name="content">内容</param>
void CreateRadio( TableColumnBuilder builder, IHtmlContent content );
/// <summary>
/// 是否将内容添加到选择框
/// </summary>
/// <param name="builder">表格单元格标签生成器</param>
bool IsAddContentToSelect( TableColumnBuilder builder );
}
|
ISelectCreateService
|
csharp
|
rabbitmq__rabbitmq-dotnet-client
|
projects/RabbitMQ.Client/IBasicProperties.cs
|
{
"start": 6719,
"end": 7127
}
|
class ____,
/// spanning the union of the functionality offered by versions
/// 0-8, 0-8qpid, 0-9 and 0-9-1 of AMQP.
/// </summary>
/// <remarks>
/// <para>
/// Each property is readable, writable and clearable: a cleared
/// property will not be transmitted over the wire. Properties on a
/// fresh instance are clear by default.
/// </para>
/// </remarks>
|
interface
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.