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 | louthy__language-ext | LanguageExt.Core/Monads/Alternative Monads/Fin/Extensions/Fin.Guard.cs | {
"start": 99,
"end": 1265
} | public static class ____
{
/// <summary>
/// Natural transformation to `Fin`
/// </summary>
public static Fin<Unit> ToFin(this Guard<Error, Unit> ma) =>
ma.Flag
? Fin.Succ(unit)
: Fin.Fail<Unit>(ma.OnFalse());
/// <summary>
/// Monadic binding support for `Fin`
/// </summary>
public static Fin<B> Bind<B>(
this Guard<Error, Unit> guard,
Func<Unit, Fin<B>> f) =>
guard.Flag
? f(default).As()
: Fin.Fail<B>(guard.OnFalse());
/// <summary>
/// Monadic binding support for `Fin`
/// </summary>
public static Fin<B> SelectMany<B>(this Guard<Error, Unit> ma, Func<Unit, Fin<B>> f) =>
ma.Flag
? f(default)
: Fin.Fail<B>(ma.OnFalse());
/// <summary>
/// Monadic binding support for `Fin`
/// </summary>
public static Fin<C> SelectMany<B, C>(
this Guard<Error, Unit> ma,
Func<Unit, Fin<B>> bind,
Func<Unit, B, C> project) =>
ma.Flag
? bind(default).Map(b => project(default, b))
: Fin.Fail<C>(ma.OnFalse());
}
| FinGuardExtensions |
csharp | dotnet__reactive | Rx.NET/Source/src/System.Reactive/Concurrency/CatchScheduler.cs | {
"start": 325,
"end": 2291
} | internal sealed class ____<TException> : SchedulerWrapper
where TException : Exception
{
private readonly Func<TException, bool> _handler;
public CatchScheduler(IScheduler scheduler, Func<TException, bool> handler)
: base(scheduler)
{
_handler = handler;
}
protected override Func<IScheduler, TState, IDisposable> Wrap<TState>(Func<IScheduler, TState, IDisposable> action)
{
return (self, state) =>
{
try
{
return action(GetRecursiveWrapper(self), state);
}
catch (TException exception) when (_handler(exception))
{
return Disposable.Empty;
}
};
}
public CatchScheduler(IScheduler scheduler, Func<TException, bool> handler, ConditionalWeakTable<IScheduler, IScheduler> cache)
: base(scheduler, cache)
{
_handler = handler;
}
protected override SchedulerWrapper Clone(IScheduler scheduler, ConditionalWeakTable<IScheduler, IScheduler> cache)
{
return new CatchScheduler<TException>(scheduler, _handler, cache);
}
protected override bool TryGetService(IServiceProvider provider, Type serviceType, out object? service)
{
service = provider.GetService(serviceType);
if (service != null)
{
if (serviceType == typeof(ISchedulerLongRunning))
{
service = new CatchSchedulerLongRunning((ISchedulerLongRunning)service, _handler);
}
else if (serviceType == typeof(ISchedulerPeriodic))
{
service = new CatchSchedulerPeriodic((ISchedulerPeriodic)service, _handler);
}
}
return true;
}
| CatchScheduler |
csharp | icsharpcode__AvalonEdit | ICSharpCode.AvalonEdit/Document/TextDocument.cs | {
"start": 2262,
"end": 25427
} | class ____ not thread-safe. A document instance expects to have a single owner thread
/// and will throw an <see cref="InvalidOperationException"/> when accessed from another thread.
/// It is possible to change the owner thread using the <see cref="SetOwnerThread"/> method.</para>
/// </remarks>
public void VerifyAccess()
{
if (Thread.CurrentThread != owner)
throw new InvalidOperationException("TextDocument can be accessed only from the thread that owns it.");
}
/// <summary>
/// Transfers ownership of the document to another thread. This method can be used to load
/// a file into a TextDocument on a background thread and then transfer ownership to the UI thread
/// for displaying the document.
/// </summary>
/// <remarks>
/// <inheritdoc cref="VerifyAccess"/>
/// <para>
/// The owner can be set to null, which means that no thread can access the document. But, if the document
/// has no owner thread, any thread may take ownership by calling <see cref="SetOwnerThread"/>.
/// </para>
/// </remarks>
public void SetOwnerThread(Thread newOwner)
{
// We need to lock here to ensure that in the null owner case,
// only one thread succeeds in taking ownership.
lock (lockObject) {
if (owner != null) {
VerifyAccess();
}
owner = newOwner;
}
}
#endregion
#region Fields + Constructor
readonly Rope<char> rope;
readonly DocumentLineTree lineTree;
readonly LineManager lineManager;
readonly TextAnchorTree anchorTree;
readonly TextSourceVersionProvider versionProvider = new TextSourceVersionProvider();
/// <summary>
/// Create an empty text document.
/// </summary>
public TextDocument()
: this(string.Empty)
{
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(IEnumerable<char> initialText)
{
if (initialText == null)
throw new ArgumentNullException("initialText");
rope = new Rope<char>(initialText);
lineTree = new DocumentLineTree(this);
lineManager = new LineManager(lineTree, this);
lineTrackers.CollectionChanged += delegate {
lineManager.UpdateListOfLineTrackers();
};
anchorTree = new TextAnchorTree(this);
undoStack = new UndoStack();
FireChangeEvents();
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(ITextSource initialText)
: this(GetTextFromTextSource(initialText))
{
}
// gets the text from a text source, directly retrieving the underlying rope where possible
static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
{
if (textSource == null)
throw new ArgumentNullException("textSource");
RopeTextSource rts = textSource as RopeTextSource;
if (rts != null)
return rts.GetRope();
TextDocument doc = textSource as TextDocument;
if (doc != null)
return doc.rope;
return textSource.Text;
}
#endregion
#region Text
void ThrowIfRangeInvalid(int offset, int length)
{
if (offset < 0 || offset > rope.Length) {
throw new ArgumentOutOfRangeException("offset", offset, "0 <= offset <= " + rope.Length.ToString(CultureInfo.InvariantCulture));
}
if (length < 0 || offset + length > rope.Length) {
throw new ArgumentOutOfRangeException("length", length, "0 <= length, offset(" + offset + ")+length <= " + rope.Length.ToString(CultureInfo.InvariantCulture));
}
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
VerifyAccess();
return rope.ToString(offset, length);
}
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
public string GetText(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException("segment");
return GetText(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return rope.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return rope.LastIndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds
return rope.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return rope.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
DebugVerifyAccess(); // frequently called, so must be fast in release builds
return rope[offset];
}
WeakReference cachedText;
/// <summary>
/// Gets/Sets the text of the whole document.
/// </summary>
public string Text {
get {
VerifyAccess();
string completeText = cachedText != null ? (cachedText.Target as string) : null;
if (completeText == null) {
completeText = rope.ToString();
cachedText = new WeakReference(completeText);
}
return completeText;
}
set {
VerifyAccess();
if (value == null)
throw new ArgumentNullException("value");
Replace(0, rope.Length, value);
}
}
/// <summary>
/// This event is called after a group of changes is completed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextChanged;
event EventHandler IDocument.ChangeCompleted {
add { this.TextChanged += value; }
remove { this.TextChanged -= value; }
}
/// <inheritdoc/>
public int TextLength {
get {
VerifyAccess();
return rope.Length;
}
}
/// <summary>
/// Is raised when one of the properties <see cref="Text"/>, <see cref="TextLength"/>, <see cref="LineCount"/>,
/// <see cref="UndoStack"/> changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Is raised before the document changes.
/// </summary>
/// <remarks>
/// <para>Here is the order in which events are raised during a document update:</para>
/// <list type="bullet">
/// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description>Start of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateStarted"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="Changing"/> event is raised</description></item>
/// <item><description>The document is changed</description></item>
/// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were
/// in the deleted text portion</description></item>
/// <item><description><see cref="Changed"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="TextChanged"/> event is raised</description></item>
/// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item>
/// <item><description>End of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateFinished"/> event is raised</description></item>
/// </list></item>
/// </list>
/// <para>
/// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>,
/// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>.
/// </para><para>
/// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls.
/// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done.
/// </para><para>
/// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step.
/// </para>
/// </remarks>
public event EventHandler<DocumentChangeEventArgs> Changing;
// Unfortunately EventHandler<T> is invariant, so we have to use two separate events
private event EventHandler<TextChangeEventArgs> textChanging;
event EventHandler<TextChangeEventArgs> IDocument.TextChanging {
add { textChanging += value; }
remove { textChanging -= value; }
}
/// <summary>
/// Is raised after the document has changed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler<DocumentChangeEventArgs> Changed;
private event EventHandler<TextChangeEventArgs> textChanged;
event EventHandler<TextChangeEventArgs> IDocument.TextChanged {
add { textChanged += value; }
remove { textChanged -= value; }
}
/// <summary>
/// Creates a snapshot of the current text.
/// </summary>
/// <remarks>
/// <para>This method returns an immutable snapshot of the document, and may be safely called even when
/// the document's owner thread is concurrently modifying the document.
/// </para><para>
/// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other
/// classes implementing ITextSource.CreateSnapshot().
/// </para><para>
/// </para>
/// </remarks>
public ITextSource CreateSnapshot()
{
lock (lockObject) {
return new RopeTextSource(rope, versionProvider.CurrentVersion);
}
}
/// <summary>
/// Creates a snapshot of a part of the current text.
/// </summary>
/// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks>
public ITextSource CreateSnapshot(int offset, int length)
{
lock (lockObject) {
return new RopeTextSource(rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public ITextSourceVersion Version {
get { return versionProvider.CurrentVersion; }
}
/// <inheritdoc/>
public System.IO.TextReader CreateReader()
{
lock (lockObject) {
return new RopeTextReader(rope);
}
}
/// <inheritdoc/>
public System.IO.TextReader CreateReader(int offset, int length)
{
lock (lockObject) {
return new RopeTextReader(rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public void WriteTextTo(System.IO.TextWriter writer)
{
VerifyAccess();
rope.WriteTo(writer, 0, rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(System.IO.TextWriter writer, int offset, int length)
{
VerifyAccess();
rope.WriteTo(writer, offset, length);
}
#endregion
#region BeginUpdate / EndUpdate
int beginUpdateCount;
/// <summary>
/// Gets if an update is running.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public bool IsInUpdate {
get {
VerifyAccess();
return beginUpdateCount > 0;
}
}
/// <summary>
/// Immediately calls <see cref="BeginUpdate()"/>,
/// and returns an IDisposable that calls <see cref="EndUpdate()"/>.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public IDisposable RunUpdate()
{
BeginUpdate();
return new CallbackOnDispose(EndUpdate);
}
/// <summary>
/// <para>Begins a group of document changes.</para>
/// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will
/// group all changes into a single action.</para>
/// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number
/// of EndUpdate calls the events resume their work.</para>
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void BeginUpdate()
{
VerifyAccess();
if (inDocumentChanging)
throw new InvalidOperationException("Cannot change document within another document change.");
beginUpdateCount++;
if (beginUpdateCount == 1) {
undoStack.StartUndoGroup();
if (UpdateStarted != null)
UpdateStarted(this, EventArgs.Empty);
}
}
/// <summary>
/// Ends a group of document changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void EndUpdate()
{
VerifyAccess();
if (inDocumentChanging)
throw new InvalidOperationException("Cannot end update within document change.");
if (beginUpdateCount == 0)
throw new InvalidOperationException("No update is active.");
if (beginUpdateCount == 1) {
// fire change events inside the change group - event handlers might add additional
// document changes to the change group
FireChangeEvents();
undoStack.EndUndoGroup();
beginUpdateCount = 0;
if (UpdateFinished != null)
UpdateFinished(this, EventArgs.Empty);
} else {
beginUpdateCount -= 1;
}
}
/// <summary>
/// Occurs when a document change starts.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateStarted;
/// <summary>
/// Occurs when a document change is finished.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateFinished;
void IDocument.StartUndoableAction()
{
BeginUpdate();
}
void IDocument.EndUndoableAction()
{
EndUpdate();
}
IDisposable IDocument.OpenUndoGroup()
{
return RunUpdate();
}
#endregion
#region Fire events after update
int oldTextLength;
int oldLineCount;
bool fireTextChanged;
/// <summary>
/// Fires TextChanged, TextLengthChanged, LineCountChanged if required.
/// </summary>
internal void FireChangeEvents()
{
// it may be necessary to fire the event multiple times if the document is changed
// from inside the event handlers
while (fireTextChanged) {
fireTextChanged = false;
if (TextChanged != null)
TextChanged(this, EventArgs.Empty);
OnPropertyChanged("Text");
int textLength = rope.Length;
if (textLength != oldTextLength) {
oldTextLength = textLength;
OnPropertyChanged("TextLength");
}
int lineCount = lineTree.LineCount;
if (lineCount != oldLineCount) {
oldLineCount = lineCount;
OnPropertyChanged("LineCount");
}
}
}
void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
#region Insert / Remove / Replace
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, string text)
{
Replace(offset, 0, new StringTextSource(text), null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, ITextSource text)
{
Replace(offset, 0, text, null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) {
Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion);
} else {
Replace(offset, 0, new StringTextSource(text), null);
}
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) {
Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
} else {
Replace(offset, 0, text, null);
}
}
/// <summary>
/// Removes text.
/// </summary>
public void Remove(ISegment segment)
{
Replace(segment, string.Empty);
}
/// <summary>
/// Removes text.
/// </summary>
/// <param name="offset">Starting offset of the text to be removed.</param>
/// <param name="length">Length of the text to be removed.</param>
public void Remove(int offset, int length)
{
Replace(offset, length, StringTextSource.Empty);
}
internal bool inDocumentChanging;
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, string text)
{
if (segment == null)
throw new ArgumentNullException("segment");
Replace(segment.Offset, segment.Length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, ITextSource text)
{
if (segment == null)
throw new ArgumentNullException("segment");
Replace(segment.Offset, segment.Length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, string text)
{
Replace(offset, length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, ITextSource text)
{
Replace(offset, length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMappingType);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType)
{
if (text == null)
throw new ArgumentNullException("text");
// Please see OffsetChangeMappingType XML comments for details on how these modes work.
switch (offsetChangeMappingType) {
case OffsetChangeMappingType.Normal:
Replace(offset, length, text, null);
break;
case OffsetChangeMappingType.KeepAnchorBeforeInsertion:
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(
new OffsetChangeMapEntry(offset, length, text.TextLength, false, true)));
break;
case OffsetChangeMappingType.RemoveAndInsert:
if (length == 0 || text.TextLength == 0) {
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
} else {
OffsetChangeMap map = new OffsetChangeMap(2);
map.Add(new OffsetChangeMapEntry(offset, length, 0));
map.Add(new OffsetChangeMapEntry(offset, 0, text.TextLength));
map.Freeze();
Replace(offset, length, text, map);
}
break;
case OffsetChangeMappingType.CharacterReplace:
if (length == 0 || text.TextLength == 0) {
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
} else if (text.TextLength > length) {
// look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace
// the last character
OffsetChangeMapEntry entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
} else if (text.TextLength < length) {
OffsetChangeMapEntry entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
} else {
Replace(offset, length, text, OffsetChangeMap.Empty);
}
break;
default:
throw new ArgumentOutOfRangeException("offsetChangeMappingType", offsetChangeMappingType, "Invalid | is |
csharp | Tyrrrz__YoutubeExplode | YoutubeExplode/YoutubeHttpHandler.cs | {
"start": 346,
"end": 6622
} | internal class ____ : ClientDelegatingHandler
{
private readonly CookieContainer _cookieContainer = new();
public YoutubeHttpHandler(
HttpClient http,
IReadOnlyList<Cookie> initialCookies,
bool disposeClient = false
)
: base(http, disposeClient)
{
// Consent to the use of cookies on YouTube.
// This is required to access some personalized content, such as mix playlists.
// https://github.com/Tyrrrz/YoutubeExplode/issues/730
// https://github.com/Tyrrrz/YoutubeExplode/issues/732
// https://github.com/Tyrrrz/YoutubeExplode/issues/907
// The cookie is supposed to be invalidated after 13 months, at which point the value
// becomes invalid and needs to be manually replaced in code with a new one.
// https://policies.google.com/technologies/cookies/embedded
_cookieContainer.Add(
new Cookie("SOCS", "CAISEwgDEgk4MTM4MzYzNTIaAmVuIAEaBgiApPzGBg")
{
Domain = "youtube.com",
}
);
// Add user-supplied cookies
foreach (var cookie in initialCookies)
_cookieContainer.Add(cookie);
}
private string? TryGenerateAuthHeaderValue(Uri uri)
{
var cookies = _cookieContainer.GetCookies(uri).Cast<Cookie>().ToArray();
var sessionId =
cookies
.FirstOrDefault(c =>
string.Equals(c.Name, "__Secure-3PAPISID", StringComparison.Ordinal)
)
?.Value
?? cookies
.FirstOrDefault(c => string.Equals(c.Name, "SAPISID", StringComparison.Ordinal))
?.Value;
if (string.IsNullOrWhiteSpace(sessionId))
return null;
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var token = $"{timestamp} {sessionId} {uri.Domain}";
var tokenHash = Hash.Compute(SHA1.Create(), Encoding.UTF8.GetBytes(token)).ToHex();
return $"SAPISIDHASH {timestamp}_{tokenHash}";
}
private HttpRequestMessage HandleRequest(HttpRequestMessage request)
{
// Shouldn't happen?
if (request.RequestUri is null)
return request;
// Set internal API key
if (
request.RequestUri.AbsolutePath.StartsWith("/youtubei/", StringComparison.Ordinal)
&& !UrlEx.ContainsQueryParameter(request.RequestUri.Query, "key")
)
{
request.RequestUri = new Uri(
UrlEx.SetQueryParameter(
request.RequestUri.OriginalString,
"key",
// This key doesn't appear to change
"AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w"
)
);
}
// Set localization language
if (!UrlEx.ContainsQueryParameter(request.RequestUri.Query, "hl"))
{
request.RequestUri = new Uri(
UrlEx.SetQueryParameter(request.RequestUri.OriginalString, "hl", "en")
);
}
// Set origin
if (!request.Headers.Contains("Origin"))
{
request.Headers.Add("Origin", request.RequestUri.Domain);
}
// Set user agent
if (!request.Headers.Contains("User-Agent"))
{
request.Headers.Add(
"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36"
);
}
// Set cookies
if (!request.Headers.Contains("Cookie") && _cookieContainer.Count > 0)
{
var cookieHeaderValue = _cookieContainer.GetCookieHeader(request.RequestUri);
if (!string.IsNullOrWhiteSpace(cookieHeaderValue))
request.Headers.Add("Cookie", cookieHeaderValue);
}
// Set authorization
if (
!request.Headers.Contains("Authorization")
&& TryGenerateAuthHeaderValue(request.RequestUri) is { } authHeaderValue
)
{
request.Headers.Add("Authorization", authHeaderValue);
}
return request;
}
private HttpResponseMessage HandleResponse(HttpResponseMessage response)
{
if (response.RequestMessage?.RequestUri is null)
return response;
// Custom exception for rate limit errors
if ((int)response.StatusCode == 429)
{
throw new RequestLimitExceededException(
"Exceeded request rate limit. "
+ "Please try again in a few hours. "
+ "Alternatively, inject cookies corresponding to a pre-authenticated user when initializing an instance of `YoutubeClient`."
);
}
// Set cookies
if (response.Headers.TryGetValues("Set-Cookie", out var cookieHeaderValues))
{
foreach (var cookieHeaderValue in cookieHeaderValues)
{
try
{
_cookieContainer.SetCookies(
response.RequestMessage.RequestUri,
cookieHeaderValue
);
}
catch (CookieException)
{
// YouTube may send cookies for other domains, ignore them
// https://github.com/Tyrrrz/YoutubeExplode/issues/762
}
}
}
return response;
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken
)
{
for (var retriesRemaining = 5; ; retriesRemaining--)
{
var response = HandleResponse(
await base.SendAsync(
// Request will be cloned by the base handler
HandleRequest(request),
cancellationToken
)
);
// Retry on 5XX errors
if ((int)response.StatusCode >= 500 && retriesRemaining > 0)
{
response.Dispose();
continue;
}
return response;
}
}
}
| YoutubeHttpHandler |
csharp | MassTransit__MassTransit | src/MassTransit/SagaStateMachine/StateMachineRequestExtensions.cs | {
"start": 5851,
"end": 7487
} | class
____ TResponse : class
{
ScheduleTokenId.UseTokenId<RequestTimeoutExpired<TRequest>>(x => x.RequestId);
var activity = new RequestActivity<TInstance, TData, TRequest, TResponse>(request, serviceAddressProvider,
MessageFactory<TRequest>.Create(messageFactory));
return binder.Add(activity);
}
/// <summary>
/// Send a request to the configured service endpoint, and setup the state machine to accept the response.
/// </summary>
/// <typeparam name="TInstance">The state instance type</typeparam>
/// <typeparam name="TData">The event data type</typeparam>
/// <typeparam name="TRequest">The request message type</typeparam>
/// <typeparam name="TResponse">The response message type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="request">The configured request to use</param>
/// <param name="serviceAddressProvider">A provider for the address used for the request</param>
/// <param name="messageFactory">The request message factory</param>
/// <returns></returns>
public static EventActivityBinder<TInstance, TData> Request<TInstance, TData, TRequest, TResponse>(this EventActivityBinder<TInstance, TData> binder,
Request<TInstance, TRequest, TResponse> request, ServiceAddressProvider<TInstance, TData> serviceAddressProvider,
AsyncEventMessageFactory<TInstance, TData, TRequest> messageFactory)
where TInstance : class, SagaStateMachineInstance
where TData : | where |
csharp | microsoft__PowerToys | src/common/AllExperiments/Microsoft.VariantAssignment/Contract/IVariantAssignmentProvider.cs | {
"start": 337,
"end": 949
} | public interface ____ : IDisposable
{
/// <summary>
/// Computes variant assignments based on <paramref name="request"/> data.
/// </summary>
/// <param name="request">Variant assignment parameters.</param>
/// <param name="ct">Propagates notification that operations should be canceled.</param>
/// <returns>An awaitable task that returns a <see cref="IVariantAssignmentResponse"/>.</returns>
Task<IVariantAssignmentResponse> GetVariantAssignmentsAsync(IVariantAssignmentRequest request, CancellationToken ct = default);
}
}
| IVariantAssignmentProvider |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/src/Types/Types/Directives/TagDirectiveExtensions.cs | {
"start": 274,
"end": 1564
} | public static class ____
{
/// <summary>
/// Adds a @tag(name: "your-value") to an <see cref="ObjectType"/>.
/// <code>
/// type Book @tag(name: "your-value") {
/// id: ID!
/// title: String!
/// author: String!
/// }
/// </code>
/// </summary>
/// <param name="descriptor">
/// The <paramref name="descriptor"/> on which this directive shall be applied.
/// </param>
/// <param name="name">
/// The value represents the <paramref name="name"/> of the tag.
/// </param>
/// <returns>
/// Returns the <paramref name="descriptor"/> on which this directive
/// was applied for configuration chaining.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="descriptor"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="name"/> is <c>null</c> or <see cref="string.Empty"/>.
/// </exception>
public static IObjectTypeDescriptor Tag(
this IObjectTypeDescriptor descriptor,
string name)
{
ApplyTag(descriptor, name);
return descriptor;
}
/// <summary>
/// Adds a @tag(name: "your-value") to an <see cref="InterfaceType"/>.
/// <code>
/// | TagDirectiveExtensions |
csharp | smartstore__Smartstore | src/Smartstore.Core/Platform/Stores/SmartDbContext.Stores.cs | {
"start": 69,
"end": 231
} | public partial class ____
{
public DbSet<Store> Stores { get; set; }
public DbSet<StoreMapping> StoreMappings { get; set; }
}
}
| SmartDbContext |
csharp | bitwarden__server | util/SqliteMigrations/Migrations/20231024181657_LimitCollectionCreateDelete.Designer.cs | {
"start": 461,
"end": 81559
} | partial class ____
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "7.0.5");
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.AuthRequest", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<string>("AccessCode")
.HasMaxLength(25)
.HasColumnType("TEXT");
b.Property<bool?>("Approved")
.HasColumnType("INTEGER");
b.Property<DateTime?>("AuthenticationDate")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<string>("MasterPasswordHash")
.HasColumnType("TEXT");
b.Property<Guid?>("OrganizationId")
.HasColumnType("TEXT");
b.Property<string>("PublicKey")
.HasColumnType("TEXT");
b.Property<string>("RequestDeviceIdentifier")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<byte>("RequestDeviceType")
.HasColumnType("INTEGER");
b.Property<string>("RequestIpAddress")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("ResponseDate")
.HasColumnType("TEXT");
b.Property<Guid?>("ResponseDeviceId")
.HasColumnType("TEXT");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("ResponseDeviceId");
b.HasIndex("UserId");
b.ToTable("AuthRequest", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.EmergencyAccess", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<Guid?>("GranteeId")
.HasColumnType("TEXT");
b.Property<Guid>("GrantorId")
.HasColumnType("TEXT");
b.Property<string>("KeyEncrypted")
.HasColumnType("TEXT");
b.Property<DateTime?>("LastNotificationDate")
.HasColumnType("TEXT");
b.Property<DateTime?>("RecoveryInitiatedDate")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<byte>("Status")
.HasColumnType("INTEGER");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.Property<int>("WaitTimeDays")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("GranteeId");
b.HasIndex("GrantorId");
b.ToTable("EmergencyAccess", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.Grant", b =>
{
b.Property<string>("Key")
.HasMaxLength(200)
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.HasMaxLength(200)
.HasColumnType("TEXT");
b.Property<DateTime?>("ConsumedDate")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Data")
.HasColumnType("TEXT");
b.Property<string>("Description")
.HasMaxLength(200)
.HasColumnType("TEXT");
b.Property<DateTime?>("ExpirationDate")
.HasColumnType("TEXT");
b.Property<string>("SessionId")
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("SubjectId")
.HasMaxLength(200)
.HasColumnType("TEXT");
b.Property<string>("Type")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.HasKey("Key");
b.ToTable("Grant", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoConfig", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Data")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("SsoConfig", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoUser", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("ExternalId")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<Guid?>("OrganizationId")
.HasColumnType("TEXT");
b.Property<Guid>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("UserId");
b.ToTable("SsoUser", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("ExternalId")
.HasMaxLength(300)
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("Collection", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionCipher", b =>
{
b.Property<Guid>("CollectionId")
.HasColumnType("TEXT");
b.Property<Guid>("CipherId")
.HasColumnType("TEXT");
b.HasKey("CollectionId", "CipherId");
b.HasIndex("CipherId");
b.ToTable("CollectionCipher", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionGroup", b =>
{
b.Property<Guid>("CollectionId")
.HasColumnType("TEXT");
b.Property<Guid>("GroupId")
.HasColumnType("TEXT");
b.Property<bool>("HidePasswords")
.HasColumnType("INTEGER");
b.Property<bool>("ReadOnly")
.HasColumnType("INTEGER");
b.HasKey("CollectionId", "GroupId");
b.HasIndex("GroupId");
b.ToTable("CollectionGroups");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionUser", b =>
{
b.Property<Guid>("CollectionId")
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationUserId")
.HasColumnType("TEXT");
b.Property<bool>("HidePasswords")
.HasColumnType("INTEGER");
b.Property<bool>("ReadOnly")
.HasColumnType("INTEGER");
b.HasKey("CollectionId", "OrganizationUserId");
b.HasIndex("OrganizationUserId");
b.ToTable("CollectionUsers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Device", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("EncryptedPrivateKey")
.HasColumnType("TEXT");
b.Property<string>("EncryptedPublicKey")
.HasColumnType("TEXT");
b.Property<string>("EncryptedUserKey")
.HasColumnType("TEXT");
b.Property<string>("Identifier")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("PushToken")
.HasMaxLength(255)
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Device", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Event", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<Guid?>("ActingUserId")
.HasColumnType("TEXT");
b.Property<Guid?>("CipherId")
.HasColumnType("TEXT");
b.Property<Guid?>("CollectionId")
.HasColumnType("TEXT");
b.Property<DateTime>("Date")
.HasColumnType("TEXT");
b.Property<byte?>("DeviceType")
.HasColumnType("INTEGER");
b.Property<string>("DomainName")
.HasColumnType("TEXT");
b.Property<Guid?>("GroupId")
.HasColumnType("TEXT");
b.Property<Guid?>("InstallationId")
.HasColumnType("TEXT");
b.Property<string>("IpAddress")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<Guid?>("OrganizationId")
.HasColumnType("TEXT");
b.Property<Guid?>("OrganizationUserId")
.HasColumnType("TEXT");
b.Property<Guid?>("PolicyId")
.HasColumnType("TEXT");
b.Property<Guid?>("ProviderId")
.HasColumnType("TEXT");
b.Property<Guid?>("ProviderOrganizationId")
.HasColumnType("TEXT");
b.Property<Guid?>("ProviderUserId")
.HasColumnType("TEXT");
b.Property<Guid?>("SecretId")
.HasColumnType("TEXT");
b.Property<Guid?>("ServiceAccountId")
.HasColumnType("TEXT");
b.Property<byte?>("SystemUser")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Event", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<bool>("AccessAll")
.HasColumnType("INTEGER");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("ExternalId")
.HasMaxLength(300)
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("Group", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.GroupUser", b =>
{
b.Property<Guid>("GroupId")
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationUserId")
.HasColumnType("TEXT");
b.HasKey("GroupId", "OrganizationUserId");
b.HasIndex("OrganizationUserId");
b.ToTable("GroupUser", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Installation", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<string>("Key")
.HasMaxLength(150)
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Installation", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Organization", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<string>("BillingEmail")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("BusinessAddress1")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("BusinessAddress2")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("BusinessAddress3")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("BusinessCountry")
.HasMaxLength(2)
.HasColumnType("TEXT");
b.Property<string>("BusinessName")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("BusinessTaxNumber")
.HasMaxLength(30)
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<DateTime?>("ExpirationDate")
.HasColumnType("TEXT");
b.Property<byte?>("Gateway")
.HasColumnType("INTEGER");
b.Property<string>("GatewayCustomerId")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("GatewaySubscriptionId")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("Identifier")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("LicenseKey")
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<bool>("LimitCollectionCreationDeletion")
.HasColumnType("INTEGER")
.HasDefaultValue(true);
b.Property<int?>("MaxAutoscaleSeats")
.HasColumnType("INTEGER");
b.Property<int?>("MaxAutoscaleSmSeats")
.HasColumnType("INTEGER");
b.Property<int?>("MaxAutoscaleSmServiceAccounts")
.HasColumnType("INTEGER");
b.Property<short?>("MaxCollections")
.HasColumnType("INTEGER");
b.Property<short?>("MaxStorageGb")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("OwnersNotifiedOfAutoscaling")
.HasColumnType("TEXT");
b.Property<string>("Plan")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<byte>("PlanType")
.HasColumnType("INTEGER");
b.Property<string>("PrivateKey")
.HasColumnType("TEXT");
b.Property<string>("PublicKey")
.HasColumnType("TEXT");
b.Property<string>("ReferenceData")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<int?>("Seats")
.HasColumnType("INTEGER");
b.Property<bool>("SecretsManagerBeta")
.HasColumnType("INTEGER");
b.Property<bool>("SelfHost")
.HasColumnType("INTEGER");
b.Property<int?>("SmSeats")
.HasColumnType("INTEGER");
b.Property<int?>("SmServiceAccounts")
.HasColumnType("INTEGER");
b.Property<byte>("Status")
.HasColumnType("INTEGER");
b.Property<long?>("Storage")
.HasColumnType("INTEGER");
b.Property<string>("TwoFactorProviders")
.HasColumnType("TEXT");
b.Property<bool>("Use2fa")
.HasColumnType("INTEGER");
b.Property<bool>("UseApi")
.HasColumnType("INTEGER");
b.Property<bool>("UseCustomPermissions")
.HasColumnType("INTEGER");
b.Property<bool>("UseDirectory")
.HasColumnType("INTEGER");
b.Property<bool>("UseEvents")
.HasColumnType("INTEGER");
b.Property<bool>("UseGroups")
.HasColumnType("INTEGER");
b.Property<bool>("UseKeyConnector")
.HasColumnType("INTEGER");
b.Property<bool>("UsePasswordManager")
.HasColumnType("INTEGER");
b.Property<bool>("UsePolicies")
.HasColumnType("INTEGER");
b.Property<bool>("UseResetPassword")
.HasColumnType("INTEGER");
b.Property<bool>("UseScim")
.HasColumnType("INTEGER");
b.Property<bool>("UseSecretsManager")
.HasColumnType("INTEGER");
b.Property<bool>("UseSso")
.HasColumnType("INTEGER");
b.Property<bool>("UseTotp")
.HasColumnType("INTEGER");
b.Property<bool>("UsersGetPremium")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("Organization", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationApiKey", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<string>("ApiKey")
.HasMaxLength(30)
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("OrganizationApiKey", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationConnection", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<string>("Config")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("OrganizationConnection", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationDomain", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("DomainName")
.HasMaxLength(255)
.HasColumnType("TEXT");
b.Property<int>("JobRunCount")
.HasColumnType("INTEGER");
b.Property<DateTime?>("LastCheckedDate")
.HasColumnType("TEXT");
b.Property<DateTime>("NextRunDate")
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<string>("Txt")
.HasColumnType("TEXT");
b.Property<DateTime?>("VerifiedDate")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("OrganizationDomain", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationSponsorship", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<string>("FriendlyName")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<DateTime?>("LastSyncDate")
.HasColumnType("TEXT");
b.Property<string>("OfferedToEmail")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<byte?>("PlanSponsorshipType")
.HasColumnType("INTEGER");
b.Property<Guid?>("SponsoredOrganizationId")
.HasColumnType("TEXT");
b.Property<Guid?>("SponsoringOrganizationId")
.HasColumnType("TEXT");
b.Property<Guid>("SponsoringOrganizationUserId")
.HasColumnType("TEXT");
b.Property<bool>("ToDelete")
.HasColumnType("INTEGER");
b.Property<DateTime?>("ValidUntil")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("SponsoredOrganizationId");
b.HasIndex("SponsoringOrganizationId");
b.ToTable("OrganizationSponsorship", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<bool>("AccessAll")
.HasColumnType("INTEGER");
b.Property<bool>("AccessSecretsManager")
.HasColumnType("INTEGER");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("ExternalId")
.HasMaxLength(300)
.HasColumnType("TEXT");
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<string>("Permissions")
.HasColumnType("TEXT");
b.Property<string>("ResetPasswordKey")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<short>("Status")
.HasColumnType("INTEGER");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("UserId");
b.ToTable("OrganizationUser", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Policy", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Data")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.ToTable("Policy", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Provider", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<string>("BillingEmail")
.HasColumnType("TEXT");
b.Property<string>("BillingPhone")
.HasColumnType("TEXT");
b.Property<string>("BusinessAddress1")
.HasColumnType("TEXT");
b.Property<string>("BusinessAddress2")
.HasColumnType("TEXT");
b.Property<string>("BusinessAddress3")
.HasColumnType("TEXT");
b.Property<string>("BusinessCountry")
.HasColumnType("TEXT");
b.Property<string>("BusinessName")
.HasColumnType("TEXT");
b.Property<string>("BusinessTaxNumber")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<byte>("Status")
.HasColumnType("INTEGER");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.Property<bool>("UseEvents")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("Provider", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.ProviderOrganization", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<Guid>("ProviderId")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<string>("Settings")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("ProviderId");
b.ToTable("ProviderOrganization", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.ProviderUser", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<string>("Permissions")
.HasColumnType("TEXT");
b.Property<Guid>("ProviderId")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<byte>("Status")
.HasColumnType("INTEGER");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("ProviderId");
b.HasIndex("UserId");
b.ToTable("ProviderUser", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Send", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<int>("AccessCount")
.HasColumnType("INTEGER");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Data")
.HasColumnType("TEXT");
b.Property<DateTime>("DeletionDate")
.HasColumnType("TEXT");
b.Property<bool>("Disabled")
.HasColumnType("INTEGER");
b.Property<DateTime?>("ExpirationDate")
.HasColumnType("TEXT");
b.Property<bool?>("HideEmail")
.HasColumnType("INTEGER");
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<int?>("MaxAccessCount")
.HasColumnType("INTEGER");
b.Property<Guid?>("OrganizationId")
.HasColumnType("TEXT");
b.Property<string>("Password")
.HasMaxLength(300)
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("UserId");
b.ToTable("Send", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.TaxRate", b =>
{
b.Property<string>("Id")
.HasMaxLength(40)
.HasColumnType("TEXT");
b.Property<bool>("Active")
.HasColumnType("INTEGER");
b.Property<string>("Country")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("PostalCode")
.HasMaxLength(10)
.HasColumnType("TEXT");
b.Property<decimal>("Rate")
.HasColumnType("TEXT");
b.Property<string>("State")
.HasMaxLength(2)
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("TaxRate", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Transaction", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<decimal>("Amount")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Details")
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<byte?>("Gateway")
.HasColumnType("INTEGER");
b.Property<string>("GatewayId")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<Guid?>("OrganizationId")
.HasColumnType("TEXT");
b.Property<byte?>("PaymentMethodType")
.HasColumnType("INTEGER");
b.Property<bool?>("Refunded")
.HasColumnType("INTEGER");
b.Property<decimal?>("RefundedAmount")
.HasColumnType("TEXT");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("UserId");
b.ToTable("Transaction", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.User", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("AccountRevisionDate")
.HasColumnType("TEXT");
b.Property<string>("ApiKey")
.IsRequired()
.HasMaxLength(30)
.HasColumnType("TEXT");
b.Property<string>("AvatarColor")
.HasMaxLength(7)
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Culture")
.HasMaxLength(10)
.HasColumnType("TEXT");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<bool>("EmailVerified")
.HasColumnType("INTEGER");
b.Property<string>("EquivalentDomains")
.HasColumnType("TEXT");
b.Property<string>("ExcludedGlobalEquivalentDomains")
.HasColumnType("TEXT");
b.Property<int>("FailedLoginCount")
.HasColumnType("INTEGER");
b.Property<bool>("ForcePasswordReset")
.HasColumnType("INTEGER");
b.Property<byte?>("Gateway")
.HasColumnType("INTEGER");
b.Property<string>("GatewayCustomerId")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("GatewaySubscriptionId")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<byte>("Kdf")
.HasColumnType("INTEGER");
b.Property<int>("KdfIterations")
.HasColumnType("INTEGER");
b.Property<int?>("KdfMemory")
.HasColumnType("INTEGER");
b.Property<int?>("KdfParallelism")
.HasColumnType("INTEGER");
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<DateTime?>("LastEmailChangeDate")
.HasColumnType("TEXT");
b.Property<DateTime?>("LastFailedLoginDate")
.HasColumnType("TEXT");
b.Property<DateTime?>("LastKdfChangeDate")
.HasColumnType("TEXT");
b.Property<DateTime?>("LastKeyRotationDate")
.HasColumnType("TEXT");
b.Property<DateTime?>("LastPasswordChangeDate")
.HasColumnType("TEXT");
b.Property<string>("LicenseKey")
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("MasterPassword")
.HasMaxLength(300)
.HasColumnType("TEXT");
b.Property<string>("MasterPasswordHint")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<short?>("MaxStorageGb")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<bool>("Premium")
.HasColumnType("INTEGER");
b.Property<DateTime?>("PremiumExpirationDate")
.HasColumnType("TEXT");
b.Property<string>("PrivateKey")
.HasColumnType("TEXT");
b.Property<string>("PublicKey")
.HasColumnType("TEXT");
b.Property<string>("ReferenceData")
.HasColumnType("TEXT");
b.Property<DateTime?>("RenewalReminderDate")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<string>("SecurityStamp")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<long?>("Storage")
.HasColumnType("INTEGER");
b.Property<string>("TwoFactorProviders")
.HasColumnType("TEXT");
b.Property<string>("TwoFactorRecoveryCode")
.HasMaxLength(32)
.HasColumnType("TEXT");
b.Property<bool>("UsesKeyConnector")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("User", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Read")
.HasColumnType("INTEGER");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<bool>("Write")
.HasColumnType("INTEGER");
b.HasKey("Id")
.HasAnnotation("SqlServer:Clustered", true);
b.ToTable("AccessPolicy", (string)null);
b.HasDiscriminator<string>("Discriminator").HasValue("AccessPolicy");
b.UseTphMappingStrategy();
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ApiKey", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<string>("ClientSecretHash")
.HasMaxLength(128)
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("EncryptedPayload")
.HasMaxLength(4000)
.HasColumnType("TEXT");
b.Property<DateTime?>("ExpireAt")
.HasColumnType("TEXT");
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasMaxLength(200)
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<string>("Scope")
.HasMaxLength(4000)
.HasColumnType("TEXT");
b.Property<Guid?>("ServiceAccountId")
.HasColumnType("TEXT");
b.HasKey("Id")
.HasAnnotation("SqlServer:Clustered", true);
b.HasIndex("ServiceAccountId")
.HasAnnotation("SqlServer:Clustered", false);
b.ToTable("ApiKey", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<DateTime?>("DeletedDate")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.HasKey("Id")
.HasAnnotation("SqlServer:Clustered", true);
b.HasIndex("DeletedDate")
.HasAnnotation("SqlServer:Clustered", false);
b.HasIndex("OrganizationId")
.HasAnnotation("SqlServer:Clustered", false);
b.ToTable("Project", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<DateTime?>("DeletedDate")
.HasColumnType("TEXT");
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<string>("Note")
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<string>("Value")
.HasColumnType("TEXT");
b.HasKey("Id")
.HasAnnotation("SqlServer:Clustered", true);
b.HasIndex("DeletedDate")
.HasAnnotation("SqlServer:Clustered", false);
b.HasIndex("OrganizationId")
.HasAnnotation("SqlServer:Clustered", false);
b.ToTable("Secret", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<Guid>("OrganizationId")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.HasKey("Id")
.HasAnnotation("SqlServer:Clustered", true);
b.HasIndex("OrganizationId")
.HasAnnotation("SqlServer:Clustered", false);
b.ToTable("ServiceAccount", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<string>("Attachments")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Data")
.HasColumnType("TEXT");
b.Property<DateTime?>("DeletedDate")
.HasColumnType("TEXT");
b.Property<string>("Favorites")
.HasColumnType("TEXT");
b.Property<string>("Folders")
.HasColumnType("TEXT");
b.Property<Guid?>("OrganizationId")
.HasColumnType("TEXT");
b.Property<byte?>("Reprompt")
.HasColumnType("INTEGER");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<byte>("Type")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("OrganizationId");
b.HasIndex("UserId");
b.ToTable("Cipher", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Folder", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT");
b.Property<Guid>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Folder", (string)null);
});
modelBuilder.Entity("ProjectSecret", b =>
{
b.Property<Guid>("ProjectsId")
.HasColumnType("TEXT");
b.Property<Guid>("SecretsId")
.HasColumnType("TEXT");
b.HasKey("ProjectsId", "SecretsId");
b.HasIndex("SecretsId");
b.ToTable("ProjectSecret");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupProjectAccessPolicy", b =>
{
b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy");
b.Property<Guid?>("GrantedProjectId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("TEXT")
.HasColumnName("GrantedProjectId");
b.Property<Guid?>("GroupId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("TEXT")
.HasColumnName("GroupId");
b.HasIndex("GrantedProjectId");
b.HasIndex("GroupId");
b.HasDiscriminator().HasValue("group_project");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupServiceAccountAccessPolicy", b =>
{
b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy");
b.Property<Guid?>("GrantedServiceAccountId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("TEXT")
.HasColumnName("GrantedServiceAccountId");
b.Property<Guid?>("GroupId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("TEXT")
.HasColumnName("GroupId");
b.HasIndex("GrantedServiceAccountId");
b.HasIndex("GroupId");
b.HasDiscriminator().HasValue("group_service_account");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountProjectAccessPolicy", b =>
{
b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy");
b.Property<Guid?>("GrantedProjectId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("TEXT")
.HasColumnName("GrantedProjectId");
b.Property<Guid?>("ServiceAccountId")
.HasColumnType("TEXT")
.HasColumnName("ServiceAccountId");
b.HasIndex("GrantedProjectId");
b.HasIndex("ServiceAccountId");
b.HasDiscriminator().HasValue("service_account_project");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserProjectAccessPolicy", b =>
{
b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy");
b.Property<Guid?>("GrantedProjectId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("TEXT")
.HasColumnName("GrantedProjectId");
b.Property<Guid?>("OrganizationUserId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("TEXT")
.HasColumnName("OrganizationUserId");
b.HasIndex("GrantedProjectId");
b.HasIndex("OrganizationUserId");
b.HasDiscriminator().HasValue("user_project");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserServiceAccountAccessPolicy", b =>
{
b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy");
b.Property<Guid?>("GrantedServiceAccountId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("TEXT")
.HasColumnName("GrantedServiceAccountId");
b.Property<Guid?>("OrganizationUserId")
.ValueGeneratedOnUpdateSometimes()
.HasColumnType("TEXT")
.HasColumnName("OrganizationUserId");
b.HasIndex("GrantedServiceAccountId");
b.HasIndex("OrganizationUserId");
b.HasDiscriminator().HasValue("user_service_account");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.AuthRequest", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Device", "ResponseDevice")
.WithMany()
.HasForeignKey("ResponseDeviceId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
b.Navigation("ResponseDevice");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.EmergencyAccess", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "Grantee")
.WithMany()
.HasForeignKey("GranteeId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "Grantor")
.WithMany()
.HasForeignKey("GrantorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Grantee");
b.Navigation("Grantor");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoConfig", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("SsoConfigs")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("SsoUsers")
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("SsoUsers")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("Collections")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionCipher", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", "Cipher")
.WithMany("CollectionCiphers")
.HasForeignKey("CipherId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection")
.WithMany("CollectionCiphers")
.HasForeignKey("CollectionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Cipher");
b.Navigation("Collection");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionGroup", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection")
.WithMany("CollectionGroups")
.HasForeignKey("CollectionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group")
.WithMany()
.HasForeignKey("GroupId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Collection");
b.Navigation("Group");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection")
.WithMany("CollectionUsers")
.HasForeignKey("CollectionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser")
.WithMany("CollectionUsers")
.HasForeignKey("OrganizationUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Collection");
b.Navigation("OrganizationUser");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Device", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("Groups")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.GroupUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group")
.WithMany("GroupUsers")
.HasForeignKey("GroupId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser")
.WithMany("GroupUsers")
.HasForeignKey("OrganizationUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Group");
b.Navigation("OrganizationUser");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationApiKey", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("ApiKeys")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationConnection", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("Connections")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationDomain", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("Domains")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationSponsorship", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "SponsoredOrganization")
.WithMany()
.HasForeignKey("SponsoredOrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "SponsoringOrganization")
.WithMany()
.HasForeignKey("SponsoringOrganizationId");
b.Navigation("SponsoredOrganization");
b.Navigation("SponsoringOrganization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("OrganizationUsers")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("OrganizationUsers")
.HasForeignKey("UserId");
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Policy", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("Policies")
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.ProviderOrganization", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Provider", "Provider")
.WithMany()
.HasForeignKey("ProviderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
b.Navigation("Provider");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.ProviderUser", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Provider", "Provider")
.WithMany()
.HasForeignKey("ProviderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany()
.HasForeignKey("UserId");
b.Navigation("Provider");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Send", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany()
.HasForeignKey("UserId");
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Transaction", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("Transactions")
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("Transactions")
.HasForeignKey("UserId");
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ApiKey", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "ServiceAccount")
.WithMany()
.HasForeignKey("ServiceAccountId");
b.Navigation("ServiceAccount");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany()
.HasForeignKey("OrganizationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Organization");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Organization", "Organization")
.WithMany("Ciphers")
.HasForeignKey("OrganizationId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("Ciphers")
.HasForeignKey("UserId");
b.Navigation("Organization");
b.Navigation("User");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Folder", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User")
.WithMany("Folders")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("ProjectSecret", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", null)
.WithMany()
.HasForeignKey("ProjectsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", null)
.WithMany()
.HasForeignKey("SecretsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupProjectAccessPolicy", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", "GrantedProject")
.WithMany("GroupAccessPolicies")
.HasForeignKey("GrantedProjectId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group")
.WithMany()
.HasForeignKey("GroupId");
b.Navigation("GrantedProject");
b.Navigation("Group");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupServiceAccountAccessPolicy", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "GrantedServiceAccount")
.WithMany("GroupAccessPolicies")
.HasForeignKey("GrantedServiceAccountId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group")
.WithMany()
.HasForeignKey("GroupId");
b.Navigation("GrantedServiceAccount");
b.Navigation("Group");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountProjectAccessPolicy", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", "GrantedProject")
.WithMany("ServiceAccountAccessPolicies")
.HasForeignKey("GrantedProjectId");
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "ServiceAccount")
.WithMany()
.HasForeignKey("ServiceAccountId");
b.Navigation("GrantedProject");
b.Navigation("ServiceAccount");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserProjectAccessPolicy", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", "GrantedProject")
.WithMany("UserAccessPolicies")
.HasForeignKey("GrantedProjectId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser")
.WithMany()
.HasForeignKey("OrganizationUserId");
b.Navigation("GrantedProject");
b.Navigation("OrganizationUser");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserServiceAccountAccessPolicy", b =>
{
b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "GrantedServiceAccount")
.WithMany("UserAccessPolicies")
.HasForeignKey("GrantedServiceAccountId");
b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser")
.WithMany()
.HasForeignKey("OrganizationUserId");
b.Navigation("GrantedServiceAccount");
b.Navigation("OrganizationUser");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b =>
{
b.Navigation("CollectionCiphers");
b.Navigation("CollectionGroups");
b.Navigation("CollectionUsers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b =>
{
b.Navigation("GroupUsers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Organization", b =>
{
b.Navigation("ApiKeys");
b.Navigation("Ciphers");
b.Navigation("Collections");
b.Navigation("Connections");
b.Navigation("Domains");
b.Navigation("Groups");
b.Navigation("OrganizationUsers");
b.Navigation("Policies");
b.Navigation("SsoConfigs");
b.Navigation("SsoUsers");
b.Navigation("Transactions");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b =>
{
b.Navigation("CollectionUsers");
b.Navigation("GroupUsers");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.User", b =>
{
b.Navigation("Ciphers");
b.Navigation("Folders");
b.Navigation("OrganizationUsers");
b.Navigation("SsoUsers");
b.Navigation("Transactions");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", b =>
{
b.Navigation("GroupAccessPolicies");
b.Navigation("ServiceAccountAccessPolicies");
b.Navigation("UserAccessPolicies");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", b =>
{
b.Navigation("GroupAccessPolicies");
b.Navigation("UserAccessPolicies");
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", b =>
{
b.Navigation("CollectionCiphers");
});
#pragma warning restore 612, 618
}
}
}
| LimitCollectionCreateDelete |
csharp | scriban__scriban | src/Scriban/Syntax/ScientificFunctionCallRewriter.cs | {
"start": 11119,
"end": 11238
} | private enum ____
{
None,
Regular,
Expression
}
}
} | FunctionCallKind |
csharp | dotnet__maui | src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue21314.cs | {
"start": 145,
"end": 530
} | public class ____ : _IssuesUITest
{
public override string Issue => "Image has wrong orientation on iOS";
public Issue21314(TestDevice device) : base(device)
{
}
[Test]
[Category(UITestCategories.Image)]
public void ImageShouldBePortrait()
{
var image = App.WaitForElement("theImage").GetRect();
ClassicAssert.Greater(image.Height, image.Width);
}
}
} | Issue21314 |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler.Tests/TestCases/Pretty/TypeMemberTests.cs | {
"start": 8022,
"end": 8197
} | public class ____ : T23_G_HideMembers2
{
#if ROSLYN
public int this[int i] => 2;
#else
public int this[int i] {
get {
return 2;
}
}
#endif
}
| T23_G2_HideMembers2 |
csharp | dotnet__maui | src/Controls/tests/CustomAttributes/Test.cs | {
"start": 1374,
"end": 1460
} | public enum ____
{
Command,
Text,
Detail,
TextColor,
DetailColor,
}
| TextCell |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack/ModularStartup.cs | {
"start": 14265,
"end": 15459
} | public class ____
{
public static Type? StartupType { get; set; }
protected IConfiguration Configuration { get; }
protected readonly ModularStartup Instance;
public ModularStartupActivator(IConfiguration configuration)
{
Configuration = configuration;
var ci = StartupType!.GetConstructor(new[] { typeof(IConfiguration) });
if (ci != null)
{
Instance = (ModularStartup) ci.Invoke(new[]{ Configuration });
}
else
{
ci = StartupType.GetConstructor(Type.EmptyTypes);
if (ci != null)
{
Instance = (ModularStartup) ci.Invoke(TypeConstants.EmptyObjectArray);
Instance.Configuration = configuration;
}
else
throw new NotSupportedException($"{StartupType.Name} does not have a {StartupType.Name}(IConfiguration) constructor");
}
}
public virtual void ConfigureServices(IServiceCollection services)
{
Instance.ConfigureServices(services);
}
public virtual void Configure(IApplicationBuilder app)
{
Instance.Configure(app);
}
}
#endif | ModularStartupActivator |
csharp | dotnetcore__Util | src/Util.Ui.NgZorro/Components/Forms/Renders/FormSplitRender.cs | {
"start": 194,
"end": 844
} | public class ____ : RenderBase {
/// <summary>
/// 配置
/// </summary>
private readonly Config _config;
/// <summary>
/// 初始化表单分隔符渲染器
/// </summary>
/// <param name="config">配置</param>
public FormSplitRender( Config config ) {
_config = config;
}
/// <summary>
/// 获取标签生成器
/// </summary>
protected override TagBuilder GetTagBuilder() {
var builder = new FormSplitBuilder( _config );
builder.Config();
return builder;
}
/// <inheritdoc />
public override IHtmlContent Clone() {
return new FormSplitRender( _config.Copy() );
}
} | FormSplitRender |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Driver.Tests/AggregateFluentFacetTests.cs | {
"start": 28370,
"end": 28818
} | private class ____ : IEqualityComparer<CategorizedByYear>
{
public bool Equals(CategorizedByYear x, CategorizedByYear y)
{
return
x.Id == y.Id &&
x.Count == y.Count;
}
public int GetHashCode(CategorizedByYear obj)
{
throw new NotImplementedException();
}
}
| CategorizedByYearComparer |
csharp | CommunityToolkit__dotnet | tests/CommunityToolkit.Mvvm.SourceGenerators.Roslyn4001.UnitTests/Test_FieldReferenceForObservablePropertyFieldCodeFixer.cs | {
"start": 9265,
"end": 10539
} | class ____
{
void M()
{
var c = new C();
_ = c?.I;
}
}
""";
CSharpCodeFixTest test = new()
{
TestCode = original,
FixedCode = @fixed,
ReferenceAssemblies = ReferenceAssemblies.Net.Net80
};
test.TestState.AdditionalReferences.Add(typeof(ObservableObject).Assembly);
test.ExpectedDiagnostics.AddRange(new[]
{
// /0/Test0.cs(14,15): warning MVVMTK0034: The field C.i is annotated with [ObservableProperty] and should not be directly referenced (use the generated property instead)
CSharpCodeFixVerifier.Diagnostic().WithSpan(14, 15, 14, 17).WithArguments("C.i"),
});
test.FixedState.ExpectedDiagnostics.AddRange(new[]
{
// /0/Test0.cs(14,15): error CS1061: 'C' does not contain a definition for 'I' and no accessible extension method 'I' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)
DiagnosticResult.CompilerError("CS1061").WithSpan(14, 15, 14, 17).WithArguments("C", "I"),
});
await test.RunAsync();
}
}
| D |
csharp | fluentassertions__fluentassertions | Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.cs | {
"start": 806,
"end": 845
} | public interface ____;
| IDummyInterface |
csharp | Humanizr__Humanizer | src/Humanizer/Localisation/ResourceKeys.TimeUnitSymbol.cs | {
"start": 23,
"end": 187
} | public partial class ____
{
/// <summary>
/// Encapsulates the logic required to get the resource keys for TimeUnit.ToSymbol
/// </summary>
| ResourceKeys |
csharp | dotnetcore__FreeSql | FreeSql.Tests/FreeSql.Tests/KingbaseES/KingbaseESExpression/DateTimeTest.cs | {
"start": 163,
"end": 309
} | public class ____
{
ISelect<Topic> select => g.kingbaseES.Select<Topic>();
[Table(Name = "tb_topic111333")]
| DateTimeTest |
csharp | icsharpcode__ILSpy | ILSpy/TextView/ReferenceElementGenerator.cs | {
"start": 2964,
"end": 4009
} | sealed class ____ : VisualLineText
{
readonly ReferenceElementGenerator parent;
readonly ReferenceSegment referenceSegment;
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineReferenceText(VisualLine parentVisualLine, int length, ReferenceElementGenerator parent, ReferenceSegment referenceSegment) : base(parentVisualLine, length)
{
this.parent = parent;
this.referenceSegment = referenceSegment;
}
/// <inheritdoc/>
protected override void OnQueryCursor(QueryCursorEventArgs e)
{
e.Handled = true;
e.Cursor = referenceSegment.IsLocal ? Cursors.Arrow : Cursors.Hand;
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineReferenceText(ParentVisualLine, length, parent, referenceSegment);
}
}
}
| VisualLineReferenceText |
csharp | EventStore__EventStore | src/KurrentDB.Core.Tests/Index/IndexV1/when_merging_ptables.cs | {
"start": 612,
"end": 2806
} | public class ____ : SpecificationWithDirectoryPerTestFixture {
private readonly List<string> _files = new List<string>();
private readonly List<PTable> _tables = new List<PTable>();
private PTable _newtable;
private readonly byte _ptableVersion;
private readonly bool _skipIndexVerify;
public when_merging_ptables(byte version, bool skipIndexVerify) {
_ptableVersion = version;
_skipIndexVerify = skipIndexVerify;
}
[OneTimeSetUp]
public override async Task TestFixtureSetUp() {
await base.TestFixtureSetUp();
_files.Add(GetTempFilePath());
var table = new HashListMemTable(_ptableVersion, maxSize: 20);
table.Add(0x0101, 0, 0x0101);
table.Add(0x0102, 0, 0x0102);
table.Add(0x0103, 0, 0x0103);
table.Add(0x0104, 0, 0x0104);
_tables.Add(PTable.FromMemtable(table, GetTempFilePath()));
table = new HashListMemTable(_ptableVersion, maxSize: 20);
table.Add(0x0105, 0, 0x0105);
table.Add(0x0106, 0, 0x0106);
table.Add(0x0107, 0, 0x0107);
table.Add(0x0108, 0, 0x0108);
_tables.Add(PTable.FromMemtable(table, GetTempFilePath()));
_newtable = PTable.MergeTo(
tables: _tables,
outputFile: GetTempFilePath(),
version: PTableVersions.IndexV4,
skipIndexVerify: _skipIndexVerify,
useBloomFilter: true);
}
[OneTimeTearDown]
public override Task TestFixtureTearDown() {
_newtable.Dispose();
foreach (var ssTable in _tables) {
ssTable.Dispose();
}
return base.TestFixtureTearDown();
}
[Test]
public void merged_ptable_is_64bit() {
Assert.AreEqual(PTableVersions.IndexV4, _newtable.Version);
}
[Test]
public void there_are_8_records_in_the_merged_index() {
Assert.AreEqual(8, _newtable.Count);
}
[Test]
public void a_stream_can_be_found() {
Assert.True(_newtable.TryGetLatestEntry(0x0108, out var entry));
Assert.AreEqual(0x0108, entry.Stream);
Assert.AreEqual(0, entry.Version);
Assert.AreEqual(0x0108, entry.Position);
}
[Test]
public void no_entries_should_have_changed() {
foreach (var item in _newtable.IterateAllInOrder()) {
Assert.IsTrue((ulong)item.Position == item.Stream, "Expected the Stream (Hash) {0:X} to be equal to {1:X}",
item.Stream - 1, item.Position);
}
}
}
| when_merging_ptables |
csharp | mysql-net__MySqlConnector | src/MySqlConnector/Protocol/Serialization/CompressedPayloadHandler.cs | {
"start": 11391,
"end": 12794
} | private sealed class ____ : IByteHandler
{
public CompressedByteHandler(CompressedPayloadHandler compressedPayloadHandler, ProtocolErrorBehavior protocolErrorBehavior)
{
m_compressedPayloadHandler = compressedPayloadHandler;
m_protocolErrorBehavior = protocolErrorBehavior;
}
public void Dispose()
{
}
public int RemainingTimeout
{
get => m_compressedPayloadHandler.ByteHandler.RemainingTimeout;
set => m_compressedPayloadHandler.ByteHandler.RemainingTimeout = value;
}
public ValueTask<int> ReadBytesAsync(Memory<byte> buffer, IOBehavior ioBehavior) =>
m_compressedPayloadHandler.ReadBytesAsync(buffer, m_protocolErrorBehavior, ioBehavior);
public ValueTask WriteBytesAsync(ReadOnlyMemory<byte> data, IOBehavior ioBehavior) => throw new NotSupportedException();
private readonly CompressedPayloadHandler m_compressedPayloadHandler;
private readonly ProtocolErrorBehavior m_protocolErrorBehavior;
}
private readonly BufferedByteReader m_bufferedByteReader;
private readonly BufferedByteReader m_compressedBufferedByteReader;
private MemoryStream? m_uncompressedStream;
private IByteHandler? m_uncompressedStreamByteHandler;
private IByteHandler? m_byteHandler;
private byte m_compressedSequenceNumber;
private byte m_uncompressedSequenceNumber;
private ArraySegment<byte> m_remainingData;
private bool m_isContinuationPacket;
}
| CompressedByteHandler |
csharp | microsoft__semantic-kernel | dotnet/samples/Concepts/ChatCompletion/OpenAI_CustomClient.cs | {
"start": 479,
"end": 2604
} | public sealed class ____(ITestOutputHelper output) : BaseTest(output)
{
[Fact]
public async Task UsingCustomHttpClientWithOpenAI()
{
Assert.NotNull(TestConfiguration.OpenAI.ChatModelId);
Assert.NotNull(TestConfiguration.OpenAI.ApiKey);
Console.WriteLine($"======== Open AI - {nameof(UsingCustomHttpClientWithOpenAI)} ========");
// Create an HttpClient and include your custom header(s)
using var myCustomHttpHandler = new MyCustomClientHttpHandler(Output);
using var myCustomClient = new HttpClient(handler: myCustomHttpHandler);
myCustomClient.DefaultRequestHeaders.Add("My-Custom-Header", "My Custom Value");
// Configure AzureOpenAIClient to use the customized HttpClient
var clientOptions = new OpenAIClientOptions
{
Transport = new HttpClientPipelineTransport(myCustomClient),
NetworkTimeout = TimeSpan.FromSeconds(30),
RetryPolicy = new ClientRetryPolicy()
};
var customClient = new OpenAIClient(new ApiKeyCredential(TestConfiguration.OpenAI.ApiKey), clientOptions);
var kernel = Kernel.CreateBuilder()
.AddOpenAIChatCompletion(TestConfiguration.OpenAI.ChatModelId, customClient)
.Build();
// Load semantic plugin defined with prompt templates
string folder = RepoFiles.SamplePluginsPath();
kernel.ImportPluginFromPromptDirectory(Path.Combine(folder, "FunPlugin"));
// Run
var result = await kernel.InvokeAsync(
kernel.Plugins["FunPlugin"]["Excuses"],
new() { ["input"] = "I have no homework" }
);
Console.WriteLine(result.GetValue<string>());
myCustomClient.Dispose();
}
/// <summary>
/// Normally you would use a custom HttpClientHandler to add custom logic to your custom http client
/// This uses the ITestOutputHelper to write the requested URI to the test output
/// </summary>
/// <param name="output">The <see cref="ITestOutputHelper"/> to write the requested URI to the test output </param>
| OpenAI_CustomClient |
csharp | dotnet__machinelearning | src/Microsoft.ML.Core/Data/LinkedRootCursorBase.cs | {
"start": 286,
"end": 427
} | class ____ a cursor has an input cursor, but still needs to do work on <see cref="DataViewRowCursor.MoveNext"/>.
/// </summary>
[BestFriend]
| for |
csharp | microsoft__garnet | libs/storage/Tsavorite/cs/src/core/Index/Tsavorite/Implementation/TryCopyToReadCache.cs | {
"start": 4463,
"end": 6076
} | record ____ the chain, then once we CAS'd it in someone could have spliced into
// it, but then that splice will call ReadCacheCheckTailAfterSplice and invalidate it if it's the same key.
// Consistency Notes:
// - This is only a concern for CTT; an update would take an XLock which means the ReadCache insert could not be done until that XLock was released.
// a. Therefore there is no "momentary inconsistency", because the value inserted at the splice would not be changed.
// b. It is not possible for another thread to update the "at tail" value to introduce inconsistency until we have released the current SLock.
// - If there are two ReadCache inserts for the same key, one will fail the CAS because it will see the other's update which changed hei.entry.
success = EnsureNoNewMainLogRecordWasSpliced(ref key, stackCtx.recSrc, pendingContext.InitialLatestLogicalAddress, ref failStatus);
}
if (success)
{
if (success)
newRecordInfo.UnsealAndValidate();
pendingContext.recordInfo = newRecordInfo;
pendingContext.logicalAddress = upsertInfo.Address;
sessionFunctions.PostSingleWriter(ref key, ref input, ref recordValue, ref readcache.GetValue(newPhysicalAddress), ref output, ref upsertInfo, WriteReason.CopyToReadCache, ref newRecordInfo);
stackCtx.ClearNewRecord();
return true;
}
// CAS failure, or another | in |
csharp | duplicati__duplicati | Duplicati/Library/Main/Operation/ListFilesHandler.cs | {
"start": 1466,
"end": 12346
} | internal class ____
{
/// <summary>
/// The tag used for logging
/// </summary>
private static readonly string LOGTAG = Logging.Log.LogTagFromType<ListFilesHandler>();
private readonly Options m_options;
private readonly ListResults m_result;
public ListFilesHandler(Options options, ListResults result)
{
m_options = options;
m_result = result;
}
public async Task RunAsync(IBackendManager backendManager, IEnumerable<string> filterstrings, IFilter compositefilter)
{
var cancellationToken = m_result.TaskControl.ProgressToken;
var parsedfilter = new FilterExpression(filterstrings);
var filter = JoinedFilterExpression.Join(parsedfilter, compositefilter);
var simpleList = !((filter is FilterExpression expression && expression.Type == FilterType.Simple) || m_options.AllVersions);
//Use a speedy local query
if (!m_options.NoLocalDb && System.IO.File.Exists(m_options.Dbpath))
await using (var db = await Database.LocalListDatabase.CreateAsync(m_options.Dbpath, null, m_result.TaskControl.ProgressToken).ConfigureAwait(false))
{
await using var filesets = await db.SelectFileSets(m_options.Time, m_options.Version, m_result.TaskControl.ProgressToken).ConfigureAwait(false);
if (!filter.Empty)
{
if (simpleList || (m_options.ListFolderContents && !m_options.AllVersions))
{
await filesets
.TakeFirst(m_result.TaskControl.ProgressToken)
.ConfigureAwait(false);
}
}
IAsyncEnumerable<Database.LocalListDatabase.IFileversion> files;
if (m_options.ListFolderContents)
{
files = filesets.SelectFolderContents(filter, m_result.TaskControl.ProgressToken);
}
else if (m_options.ListPrefixOnly)
{
files = filesets.GetLargestPrefix(filter, m_result.TaskControl.ProgressToken);
}
else if (filter.Empty)
{
files = null;
}
else
{
files = filesets.SelectFiles(filter, m_result.TaskControl.ProgressToken);
}
if (m_options.ListSetsOnly)
{
m_result.SetResult(
await filesets
.QuickSets(m_result.TaskControl.ProgressToken)
.Select(x => new ListResultFileset(x.Version, x.IsFullBackup, x.Time, x.FileCount, x.FileSizes))
.ToArrayAsync(cancellationToken: m_result.TaskControl.ProgressToken)
.ConfigureAwait(false),
null
);
}
else
{
m_result.SetResult(
await filesets
.Sets(m_result.TaskControl.ProgressToken)
.Select(x => new ListResultFileset(x.Version, x.IsFullBackup, x.Time, x.FileCount, x.FileSizes))
.ToArrayAsync(cancellationToken: m_result.TaskControl.ProgressToken)
.ConfigureAwait(false),
files == null
? null
:
await files.Select(async n =>
new ListResultFile(
n.Path,
await n
.Sizes(m_result.TaskControl.ProgressToken)
.ToArrayAsync(cancellationToken: m_result.TaskControl.ProgressToken)
.ConfigureAwait(false)
)
)
.Select(x => x.Result)
.Cast<IListResultFile>()
.ToArrayAsync(cancellationToken: m_result.TaskControl.ProgressToken)
.ConfigureAwait(false)
);
}
return;
}
Logging.Log.WriteInformationMessage(LOGTAG, "NoLocalDatabase", "No local database, accessing remote store");
//TODO: Add prefix and foldercontents
if (m_options.ListFolderContents)
throw new UserInformationException("Listing folder contents is not supported without a local database, consider using the \"repair\" option to rebuild the database.", "FolderContentListingRequiresLocalDatabase");
else if (m_options.ListPrefixOnly)
throw new UserInformationException("Listing prefixes is not supported without a local database, consider using the \"repair\" option to rebuild the database.", "PrefixListingRequiresLocalDatabase");
// Otherwise, grab info from remote location
using (var tmpdb = new TempFile())
await using (var db = await LocalDatabase.CreateLocalDatabaseAsync(tmpdb, "List", true, null, m_result.TaskControl.ProgressToken).ConfigureAwait(false))
{
var filteredList = ParseAndFilterFilesets(await backendManager.ListAsync(cancellationToken).ConfigureAwait(false), m_options);
if (filteredList.Count == 0)
throw new UserInformationException("No filesets found on remote target", "EmptyRemoteFolder");
var numberSeq = await CreateResultSequence(filteredList, backendManager, m_options, cancellationToken)
.ConfigureAwait(false);
if (filter.Empty)
{
m_result.SetResult(numberSeq, null);
m_result.EncryptedFiles = filteredList.Any(x => !string.IsNullOrWhiteSpace(x.Value.EncryptionModule));
return;
}
var firstEntry = filteredList[0].Value;
filteredList.RemoveAt(0);
Dictionary<string, List<long>> res;
if (!await m_result.TaskControl.ProgressRendevouz().ConfigureAwait(false))
return;
using (var tmpfile = await backendManager.GetAsync(firstEntry.File.Name, null, firstEntry.File.Size, cancellationToken).ConfigureAwait(false))
using (var rd = new FilesetVolumeReader(RestoreHandler.GetCompressionModule(firstEntry.File.Name), tmpfile, m_options))
if (simpleList)
{
m_result.SetResult(
numberSeq.Take(1),
(from n in rd.Files
where Library.Utility.FilterExpression.Matches(filter, n.Path)
orderby n.Path
select new ListResultFile(n.Path, new long[] { n.Size }))
.ToArray()
);
return;
}
else
{
res = rd.Files
.Where(x => Library.Utility.FilterExpression.Matches(filter, x.Path))
.ToDictionary(
x => x.Path,
y =>
{
var lst = new List<long>();
lst.Add(y.Size);
return lst;
},
Library.Utility.Utility.ClientFilenameStringComparer
);
}
long flindex = 1;
var filteredListMap = filteredList.ToDictionary(x => x.Value.File.Name, x => x.Value);
await foreach (var (tmpfile, hash, size, name) in backendManager.GetFilesOverlappedAsync(filteredList.Select(x => new RemoteVolumeMapper(x.Value)), cancellationToken).ConfigureAwait(false))
{
var flentry = filteredListMap[name];
using (tmpfile)
using (var rd = new FilesetVolumeReader(flentry.CompressionModule, tmpfile, m_options))
{
if (!await m_result.TaskControl.ProgressRendevouz().ConfigureAwait(false))
return;
foreach (var p in from n in rd.Files where Library.Utility.FilterExpression.Matches(filter, n.Path) select n)
{
List<long> lst;
if (!res.TryGetValue(p.Path, out lst))
{
lst = new List<long>();
res[p.Path] = lst;
for (var i = 0; i < flindex; i++)
lst.Add(-1);
}
lst.Add(p.Size);
}
foreach (var n in from i in res where i.Value.Count < flindex + 1 select i)
n.Value.Add(-1);
flindex++;
}
}
m_result.SetResult(
numberSeq,
from n in res
orderby n.Key
select (Duplicati.Library.Interface.IListResultFile)(new ListResultFile(n.Key, n.Value))
);
}
}
public static List<KeyValuePair<long, Volumes.IParsedVolume>> ParseAndFilterFilesets(IEnumerable<Duplicati.Library.Interface.IFileEntry> rawlist, Options options)
{
var parsedlist = (from n in rawlist
let p = Volumes.VolumeBase.ParseFilename(n)
where p != null && p.FileType == RemoteVolumeType.Files
orderby p.Time descending
select p).ToArray();
var filelistFilter = RestoreHandler.FilterNumberedFilelist(options.Time, options.Version);
return filelistFilter(parsedlist).ToList();
}
| ListFilesHandler |
csharp | dotnet__aspnetcore | src/Hosting/Hosting/test/GenericWebHostBuilderTests.cs | {
"start": 6599,
"end": 7064
} | private class ____
{
public void ConfigureServices(IServiceCollection services) { services.AddSingleton<FirstStartup>(); }
public void Configure(IApplicationBuilder app)
{
Assert.NotNull(app.ApplicationServices.GetService<FirstStartup>());
Assert.Null(app.ApplicationServices.GetService<SecondStartup>());
app.Run(context => context.Response.WriteAsync("FirstStartup"));
}
}
| FirstStartup |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Driver.Tests/Core/Bindings/WritableServerBindingTests.cs | {
"start": 933,
"end": 12421
} | public class ____
{
private Mock<IClusterInternal> _mockCluster;
public WritableServerBindingTests()
{
_mockCluster = new Mock<IClusterInternal>();
}
[Fact]
public void Constructor_should_throw_if_cluster_is_null()
{
Action act = () => new WritableServerBinding(null, NoCoreSession.NewHandle());
act.ShouldThrow<ArgumentNullException>();
}
[Fact]
public void Constructor_should_throw_if_session_is_null()
{
var cluster = new Mock<IClusterInternal>().Object;
Action act = () => new WritableServerBinding(cluster, null);
act.ShouldThrow<ArgumentNullException>();
}
[Fact]
public void ReadPreference_should_be_primary()
{
var subject = new WritableServerBinding(_mockCluster.Object, NoCoreSession.NewHandle());
subject.ReadPreference.Should().Be(ReadPreference.Primary);
}
[Fact]
public void Session_should_return_expected_result()
{
var cluster = new Mock<IClusterInternal>().Object;
var session = new Mock<ICoreSessionHandle>().Object;
var subject = new WritableServerBinding(cluster, session);
var result = subject.Session;
result.Should().BeSameAs(session);
}
[Theory]
[ParameterAttributeData]
public async Task GetReadChannelSource_should_throw_if_disposed(
[Values(false, true)]
bool async)
{
var subject = new WritableServerBinding(_mockCluster.Object, NoCoreSession.NewHandle());
subject.Dispose();
var exception = async ?
await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) :
Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout));
exception.Should().BeOfType<ObjectDisposedException>();
}
[Theory]
[ParameterAttributeData]
public async Task GetReadChannelSource_should_use_a_writable_server_selector_to_select_the_server_from_the_cluster(
[Values(false, true)]
bool async)
{
var subject = new WritableServerBinding(_mockCluster.Object, NoCoreSession.NewHandle());
var selectedServer = new Mock<IServer>().Object;
var clusterId = new ClusterId();
var endPoint = new DnsEndPoint("localhost", 27017);
var initialClusterDescription = new ClusterDescription(
clusterId,
false,
null,
ClusterType.Unknown,
[new ServerDescription(new ServerId(clusterId, endPoint), endPoint)]);
var finalClusterDescription = initialClusterDescription.WithType(ClusterType.Standalone);
_mockCluster.SetupSequence(c => c.Description).Returns(initialClusterDescription).Returns(finalClusterDescription);
if (async)
{
_mockCluster.Setup(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny<WritableServerSelector>())).Returns(Task.FromResult(selectedServer));
await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout);
_mockCluster.Verify(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny<WritableServerSelector>()), Times.Once);
}
else
{
_mockCluster.Setup(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny<WritableServerSelector>())).Returns(selectedServer);
subject.GetReadChannelSource(OperationContext.NoTimeout);
_mockCluster.Verify(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny<WritableServerSelector>()), Times.Once);
}
}
[Theory]
[ParameterAttributeData]
public async Task GetWriteChannelSource_should_throw_if_disposed(
[Values(false, true)]
bool async)
{
var subject = new WritableServerBinding(_mockCluster.Object, NoCoreSession.NewHandle());
subject.Dispose();
var exception = async ?
await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout)) :
Record.Exception(() => subject.GetWriteChannelSource(OperationContext.NoTimeout));
exception.Should().BeOfType<ObjectDisposedException>();
}
[Theory]
[ParameterAttributeData]
public async Task GetWriteChannelSourceAsync_should_use_a_writable_server_selector_to_select_the_server_from_the_cluster(
[Values(false, true)]
bool async)
{
var subject = new WritableServerBinding(_mockCluster.Object, NoCoreSession.NewHandle());
var selectedServer = new Mock<IServer>().Object;
var clusterId = new ClusterId();
var endPoint = new DnsEndPoint("localhost", 27017);
var initialClusterDescription = new ClusterDescription(
clusterId,
false,
null,
ClusterType.Unknown,
[new ServerDescription(new ServerId(clusterId, endPoint), endPoint)]);
var finalClusterDescription = initialClusterDescription.WithType(ClusterType.Standalone);
_mockCluster.SetupSequence(c => c.Description).Returns(initialClusterDescription).Returns(finalClusterDescription);
if (async)
{
_mockCluster.Setup(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny<WritableServerSelector>())).Returns(Task.FromResult(selectedServer));
await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout);
_mockCluster.Verify(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny<WritableServerSelector>()), Times.Once);
}
else
{
_mockCluster.Setup(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny<WritableServerSelector>())).Returns(selectedServer);
subject.GetWriteChannelSource(OperationContext.NoTimeout);
_mockCluster.Verify(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny<WritableServerSelector>()), Times.Once);
}
}
[Theory]
[ParameterAttributeData]
public async Task GetWriteChannelSource_should_use_a_composite_server_selector_to_select_the_server_from_the_cluster_when_deprioritized_servers_present(
[Values(false, true)]
bool async)
{
var subject = new WritableServerBinding(_mockCluster.Object, NoCoreSession.NewHandle());
var selectedServer = new Mock<IServer>().Object;
var clusterId = new ClusterId();
var endPoint = new DnsEndPoint("localhost", 27017);
var server = new ServerDescription(new ServerId(clusterId, endPoint), endPoint);
var initialClusterDescription = new ClusterDescription(
clusterId,
false,
null,
ClusterType.Unknown,
new[] { server });
var finalClusterDescription = initialClusterDescription.WithType(ClusterType.Sharded);
_mockCluster.SetupSequence(c => c.Description).Returns(initialClusterDescription).Returns(finalClusterDescription);
var deprioritizedServers = new ServerDescription[] { server };
if (async)
{
_mockCluster.Setup(c => c.SelectServerAsync(OperationContext.NoTimeout, It.Is<CompositeServerSelector>(cp => cp.ToString().Contains("PriorityServerSelector")))).Returns(Task.FromResult(selectedServer));
await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout, deprioritizedServers);
_mockCluster.Verify(c => c.SelectServerAsync(OperationContext.NoTimeout, It.Is<CompositeServerSelector>(cp => cp.ToString().Contains("PriorityServerSelector"))), Times.Once);
}
else
{
_mockCluster.Setup(c => c.SelectServer(OperationContext.NoTimeout, It.Is<CompositeServerSelector>(cp => cp.ToString().Contains("PriorityServerSelector")))).Returns(selectedServer);
subject.GetWriteChannelSource(OperationContext.NoTimeout, deprioritizedServers);
_mockCluster.Verify(c => c.SelectServer(OperationContext.NoTimeout, It.Is<CompositeServerSelector>(c => c.ToString().Contains("PriorityServerSelector"))), Times.Once);
}
}
[Theory]
[ParameterAttributeData]
public async Task GetWriteChannelSource_with_mayUseSecondary_should_pass_mayUseSecondary_to_server_selector(
[Values(false, true)]
bool async)
{
var subject = new WritableServerBinding(_mockCluster.Object, NoCoreSession.NewHandle());
var selectedServer = new Mock<IServer>().Object;
var clusterId = new ClusterId();
var endPoint = new DnsEndPoint("localhost", 27017);
var initialClusterDescription = new ClusterDescription(
clusterId,
false,
null,
ClusterType.Unknown,
[new ServerDescription(new ServerId(clusterId, endPoint), endPoint)]);
var finalClusterDescription = initialClusterDescription.WithType(ClusterType.Standalone);
_mockCluster.SetupSequence(c => c.Description).Returns(initialClusterDescription).Returns(finalClusterDescription);
var mockMayUseSecondary = new Mock<IMayUseSecondaryCriteria>();
mockMayUseSecondary.SetupGet(x => x.ReadPreference).Returns(ReadPreference.SecondaryPreferred);
mockMayUseSecondary.Setup(x => x.CanUseSecondary(It.IsAny<ServerDescription>())).Returns(true);
var mayUseSecondary = mockMayUseSecondary.Object;
if (async)
{
_mockCluster.Setup(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny<WritableServerSelector>())).Returns(Task.FromResult(selectedServer));
await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout, mayUseSecondary);
_mockCluster.Verify(c => c.SelectServerAsync(OperationContext.NoTimeout, It.Is<WritableServerSelector>(s => s.MayUseSecondary == mayUseSecondary)), Times.Once);
}
else
{
_mockCluster.Setup(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny<WritableServerSelector>())).Returns(selectedServer);
subject.GetWriteChannelSource(OperationContext.NoTimeout, mayUseSecondary);
_mockCluster.Verify(c => c.SelectServer(OperationContext.NoTimeout, It.Is<WritableServerSelector>(s => s.MayUseSecondary == mayUseSecondary)), Times.Once);
}
}
[Fact]
public void Dispose_should_call_dispose_on_owned_resources()
{
var mockSession = new Mock<ICoreSessionHandle>();
var subject = new WritableServerBinding(_mockCluster.Object, mockSession.Object);
subject.Dispose();
_mockCluster.Verify(c => c.Dispose(), Times.Never);
mockSession.Verify(m => m.Dispose(), Times.Once);
}
}
| WritableServerBindingTests |
csharp | dotnetcore__Util | src/Util.FileStorage.Abstractions/ILocalFileStore.cs | {
"start": 73,
"end": 2342
} | public interface ____ {
/// <summary>
/// 文件是否存在
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="policy">文件名处理策略</param>
/// <param name="cancellationToken">取消令牌</param>
Task<bool> FileExistsAsync( string fileName, string policy = null, CancellationToken cancellationToken = default );
/// <summary>
/// 获取文件流
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="cancellationToken">取消令牌</param>
Task<Stream> GetFileStreamAsync( string fileName, CancellationToken cancellationToken = default );
/// <summary>
/// 保存文件
/// </summary>
/// <param name="stream">文件流</param>
/// <param name="fileName">文件名,包含扩展名</param>
/// <param name="policy">文件名处理策略</param>
/// <param name="cancellationToken">取消令牌</param>
Task<FileResult> SaveFileAsync( Stream stream, string fileName, string policy = null, CancellationToken cancellationToken = default );
/// <summary>
/// 下载远程文件并保存到文件存储
/// </summary>
/// <param name="url">远程下载地址</param>
/// <param name="fileName">文件名,包含扩展名</param>
/// <param name="policy">文件名处理策略</param>
/// <param name="cancellationToken">取消令牌</param>
Task<FileResult> SaveFileByUrlAsync( string url, string fileName, string policy = null, CancellationToken cancellationToken = default );
/// <summary>
/// 复制文件
/// </summary>
/// <param name="sourceFileName">源文件名</param>
/// <param name="destinationFileName">目标文件名</param>
/// <param name="cancellationToken">取消令牌</param>
Task CopyFileAsync( string sourceFileName, string destinationFileName, CancellationToken cancellationToken = default );
/// <summary>
/// 移动文件
/// </summary>
/// <param name="sourceFileName">源文件名</param>
/// <param name="destinationFileName">目标文件名</param>
/// <param name="cancellationToken">取消令牌</param>
Task MoveFileAsync( string sourceFileName, string destinationFileName, CancellationToken cancellationToken = default );
/// <summary>
/// 删除文件
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="cancellationToken">取消令牌</param>
Task DeleteFileAsync( string fileName, CancellationToken cancellationToken = default );
} | ILocalFileStore |
csharp | dotnet__efcore | test/EFCore.InMemory.FunctionalTests/ConfigPatternsInMemoryTest.cs | {
"start": 14086,
"end": 14912
} | private class ____
{
private readonly InjectDifferentConfigurationsBlogContext _context;
public InjectDifferentConfigurationsBlogController(InjectDifferentConfigurationsBlogContext context)
{
Assert.NotNull(context);
_context = context;
}
public void Test()
{
Assert.IsType<DbContextOptions<InjectDifferentConfigurationsBlogContext>>(
_context.GetService<IDbContextOptions>());
_context.Blogs.Add(
new Blog { Name = "The Waffle Cart" });
_context.SaveChanges();
var blog = _context.Blogs.SingleOrDefault();
Assert.NotEqual(0, blog.Id);
Assert.Equal("The Waffle Cart", blog.Name);
}
}
| InjectDifferentConfigurationsBlogController |
csharp | dotnet__reactive | Rx.NET/Source/src/System.Reactive/Concurrency/ThreadPoolScheduler.cs | {
"start": 7906,
"end": 9331
} | private sealed class ____<TState> : IDisposable
{
private TState _state;
private Func<TState, TState> _action;
private readonly AsyncLock _gate;
private volatile Timer? _timer;
public PeriodicTimer(TState state, TimeSpan period, Func<TState, TState> action)
{
_state = state;
_action = action;
_gate = new AsyncLock();
//
// Rooting of the timer happens through the this.Tick delegate's target object,
// which is the current instance and has a field to store the Timer instance.
//
_timer = new Timer(static @this => ((PeriodicTimer<TState>)@this!).Tick(), this, period, period);
}
private void Tick()
{
_gate.Wait(
this,
@this =>
{
@this._state = @this._action(@this._state);
});
}
public void Dispose()
{
var timer = _timer;
if (timer != null)
{
_action = Stubs<TState>.I;
_timer = null;
timer.Dispose();
_gate.Dispose();
}
}
}
}
}
#endif | PeriodicTimer |
csharp | dotnet__reactive | Rx.NET/Source/src/System.Reactive/Linq/Observable/RetryWhen.cs | {
"start": 387,
"end": 1940
} | internal sealed class ____<T, U> : IObservable<T>
{
private readonly IObservable<T> _source;
private readonly Func<IObservable<Exception>, IObservable<U>> _handler;
internal RetryWhen(IObservable<T> source, Func<IObservable<Exception>, IObservable<U>> handler)
{
_source = source;
_handler = handler;
}
public IDisposable Subscribe(IObserver<T> observer)
{
if (observer == null)
{
throw new ArgumentNullException(nameof(observer));
}
var errorSignals = new Subject<Exception>();
IObservable<U> redo;
try
{
redo = _handler(errorSignals);
if (redo == null)
{
#pragma warning disable CA2201 // (Do not raise reserved exception types.) Backwards compatibility prevents us from complying.
throw new NullReferenceException("The handler returned a null IObservable");
#pragma warning restore CA2201
}
}
catch (Exception ex)
{
observer.OnError(ex);
return Disposable.Empty;
}
var parent = new MainObserver(observer, _source, new RedoSerializedObserver<Exception>(errorSignals));
var d = redo.SubscribeSafe(parent.HandlerConsumer);
parent.HandlerUpstream.Disposable = d;
parent.HandlerNext();
return parent;
}
| RetryWhen |
csharp | microsoft__FASTER | cs/src/core/Async/RMWAsync.cs | {
"start": 2768,
"end": 9483
} | public struct ____<Input, TOutput, Context>
{
internal readonly AsyncOperationInternal<Input, TOutput, Context, RmwAsyncOperation<Input, TOutput, Context>, RmwAsyncResult<Input, TOutput, Context>> updateAsyncInternal;
/// <summary>Current status of the RMW operation</summary>
public Status Status { get; }
/// <summary>Output of the RMW operation if current status is not pending</summary>
public TOutput Output { get; }
/// <summary>Metadata of the updated record</summary>
public RecordMetadata RecordMetadata { get; }
internal RmwAsyncResult(Status status, TOutput output, RecordMetadata recordMetadata)
{
Debug.Assert(!status.IsPending);
this.Status = status;
this.Output = output;
this.RecordMetadata = recordMetadata;
this.updateAsyncInternal = default;
}
internal RmwAsyncResult(FasterKV<Key, Value> fasterKV, IFasterSession<Key, Value, Input, TOutput, Context> fasterSession,
PendingContext<Input, TOutput, Context> pendingContext, ref RMWOptions rmwOptions, AsyncIOContext<Key, Value> diskRequest, ExceptionDispatchInfo exceptionDispatchInfo)
{
Status = new(StatusCode.Pending);
this.Output = default;
this.RecordMetadata = default;
updateAsyncInternal = new AsyncOperationInternal<Input, TOutput, Context, RmwAsyncOperation<Input, TOutput, Context>, RmwAsyncResult<Input, TOutput, Context>>(
fasterKV, fasterSession, pendingContext, exceptionDispatchInfo, new (diskRequest, ref rmwOptions));
}
/// <summary>Complete the RMW operation, issuing additional (rare) I/O asynchronously if needed. It is usually preferable to use Complete() instead of this.</summary>
/// <returns>ValueTask for RMW result. User needs to await again if result status is pending.</returns>
public ValueTask<RmwAsyncResult<Input, TOutput, Context>> CompleteAsync(CancellationToken token = default)
=> this.Status.IsPending
? updateAsyncInternal.CompleteAsync(token)
: new ValueTask<RmwAsyncResult<Input, TOutput, Context>>(new RmwAsyncResult<Input, TOutput, Context>(this.Status, this.Output, this.RecordMetadata));
/// <summary>Complete the RMW operation, issuing additional (rare) I/O synchronously if needed.</summary>
/// <returns>Status of RMW operation</returns>
public (Status status, TOutput output) Complete()
=> Complete(out _);
/// <summary>Complete the RMW operation, issuing additional (rare) I/O synchronously if needed.</summary>
/// <returns>Status of RMW operation</returns>
public (Status status, TOutput output) Complete(out RecordMetadata recordMetadata)
{
if (!this.Status.IsPending)
{
recordMetadata = this.RecordMetadata;
return (this.Status, this.Output);
}
var rmwAsyncResult = updateAsyncInternal.CompleteSync();
recordMetadata = rmwAsyncResult.RecordMetadata;
return (rmwAsyncResult.Status, rmwAsyncResult.Output);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ValueTask<RmwAsyncResult<Input, Output, Context>> RmwAsync<Input, Output, Context, FasterSession>(FasterSession fasterSession,
ref Key key, ref Input input, ref RMWOptions rmwOptions, Context context, long serialNo, CancellationToken token = default)
where FasterSession : IFasterSession<Key, Value, Input, Output, Context>
{
var pcontext = new PendingContext<Input, Output, Context> { IsAsync = true };
var diskRequest = default(AsyncIOContext<Key, Value>);
fasterSession.UnsafeResumeThread();
try
{
Output output = default;
var status = CallInternalRMW(fasterSession, ref pcontext, ref key, ref input, ref output, ref rmwOptions, context, serialNo, out diskRequest);
if (!status.IsPending)
return new ValueTask<RmwAsyncResult<Input, Output, Context>>(new RmwAsyncResult<Input, Output, Context>(status, output, new RecordMetadata(pcontext.recordInfo, pcontext.logicalAddress)));
}
finally
{
Debug.Assert(serialNo >= fasterSession.Ctx.serialNum, "Operation serial numbers must be non-decreasing");
fasterSession.Ctx.serialNum = serialNo;
fasterSession.UnsafeSuspendThread();
}
return SlowRmwAsync(this, fasterSession, pcontext, rmwOptions, diskRequest, token);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Status CallInternalRMW<Input, Output, Context>(IFasterSession<Key, Value, Input, Output, Context> fasterSession, ref PendingContext<Input, Output, Context> pcontext,
ref Key key, ref Input input, ref Output output, ref RMWOptions rmwOptions, Context context, long serialNo, out AsyncIOContext<Key, Value> diskRequest)
{
OperationStatus internalStatus;
var keyHash = rmwOptions.KeyHash ?? comparer.GetHashCode64(ref key);
do
internalStatus = InternalRMW(ref key, keyHash, ref input, ref output, ref context, ref pcontext, fasterSession, serialNo);
while (HandleImmediateRetryStatus(internalStatus, fasterSession, ref pcontext));
return HandleOperationStatus(fasterSession.Ctx, ref pcontext, internalStatus, out diskRequest);
}
private static async ValueTask<RmwAsyncResult<Input, Output, Context>> SlowRmwAsync<Input, Output, Context>(
FasterKV<Key, Value> @this, IFasterSession<Key, Value, Input, Output, Context> fasterSession,
PendingContext<Input, Output, Context> pcontext, RMWOptions rmwOptions, AsyncIOContext<Key, Value> diskRequest, CancellationToken token = default)
{
ExceptionDispatchInfo exceptionDispatchInfo;
(diskRequest, exceptionDispatchInfo) = await WaitForFlushOrIOCompletionAsync(@this, fasterSession.Ctx, pcontext.flushEvent, diskRequest, token);
pcontext.flushEvent = default;
return new RmwAsyncResult<Input, Output, Context>(@this, fasterSession, pcontext, ref rmwOptions, diskRequest, exceptionDispatchInfo);
}
}
}
| RmwAsyncResult |
csharp | dotnetcore__Util | src/Util.Data.EntityFrameworkCore/ValueConverters/ExtraPropertiesValueConverter.cs | {
"start": 159,
"end": 1481
} | public class ____ : ValueConverter<ExtraPropertyDictionary, string> {
/// <summary>
/// 初始化扩展属性值转换器
/// </summary>
public ExtraPropertiesValueConverter()
: base( extraProperties => PropertiesToJson( extraProperties ), json => JsonToProperties( json ) ) {
}
/// <summary>
/// 扩展属性转换为json
/// </summary>
private static string PropertiesToJson( ExtraPropertyDictionary extraProperties ) {
var options = new JsonSerializerOptions {
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Encoder = JavaScriptEncoder.Create( UnicodeRanges.All ),
Converters = {
new UtcDateTimeJsonConverter(),
new UtcNullableDateTimeJsonConverter()
}
};
return Util.Helpers.Json.ToJson( extraProperties, options );
}
/// <summary>
/// json转换为扩展属性
/// </summary>
private static ExtraPropertyDictionary JsonToProperties( string json ) {
if( json.IsEmpty() || json == "{}" )
return new ExtraPropertyDictionary();
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
return Util.Helpers.Json.ToObject<ExtraPropertyDictionary>( json, options ) ?? new ExtraPropertyDictionary();
}
} | ExtraPropertiesValueConverter |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 132304,
"end": 132521
} | public class ____
{
public int Id { get; set; }
public RelatedEntity610 ParentEntity { get; set; }
public IEnumerable<RelatedEntity612> ChildEntities { get; set; }
}
| RelatedEntity611 |
csharp | xunit__xunit | src/xunit.v3.assert.tests/Asserts/EqualityAssertsTests.cs | {
"start": 2970,
"end": 3670
} | class ____<T>(bool result) :
IEqualityComparer<T>
{
readonly bool result = result;
public bool Equals(T? x, T? y) => result;
public int GetHashCode(T obj) => throw new NotImplementedException();
}
[Fact]
public void NonEnumerable_WithThrow_RecordsInnerException()
{
var ex = Record.Exception(() => Assert.Equal(42, 2112, new ThrowingIntComparer()));
Assert.IsType<EqualException>(ex);
Assert.Equal(
"Assert.Equal() Failure: Exception thrown during comparison" + Environment.NewLine +
"Expected: 42" + Environment.NewLine +
"Actual: 2112",
ex.Message
);
Assert.IsType<DivideByZeroException>(ex.InnerException);
}
| Comparer |
csharp | abpframework__abp | framework/src/Volo.Abp.Threading/Volo/Abp/Threading/AmbientDataContextAmbientScopeProvider.cs | {
"start": 232,
"end": 2279
} | public class ____<T> : IAmbientScopeProvider<T>
{
public ILogger<AmbientDataContextAmbientScopeProvider<T>> Logger { get; set; }
private static readonly ConcurrentDictionary<string, ScopeItem> ScopeDictionary = new ConcurrentDictionary<string, ScopeItem>();
private readonly IAmbientDataContext _dataContext;
public AmbientDataContextAmbientScopeProvider([NotNull] IAmbientDataContext dataContext)
{
Check.NotNull(dataContext, nameof(dataContext));
_dataContext = dataContext;
Logger = NullLogger<AmbientDataContextAmbientScopeProvider<T>>.Instance;
}
public T? GetValue(string contextKey)
{
var item = GetCurrentItem(contextKey);
if (item == null)
{
return default;
}
return item.Value;
}
public IDisposable BeginScope(string contextKey, T value)
{
var item = new ScopeItem(value, GetCurrentItem(contextKey));
if (!ScopeDictionary.TryAdd(item.Id, item))
{
throw new AbpException("Can not add item! ScopeDictionary.TryAdd returns false!");
}
_dataContext.SetData(contextKey, item.Id);
return new DisposeAction<ValueTuple<ConcurrentDictionary<string, ScopeItem>, ScopeItem, IAmbientDataContext, string>>(static (state) =>
{
var (scopeDictionary, item, dataContext, contextKey) = state;
scopeDictionary.TryRemove(item.Id, out item);
if (item == null)
{
return;
}
if (item.Outer == null)
{
dataContext.SetData(contextKey, null);
return;
}
dataContext.SetData(contextKey, item.Outer.Id);
}, (ScopeDictionary, item, _dataContext, contextKey));
}
private ScopeItem? GetCurrentItem(string contextKey)
{
return _dataContext.GetData(contextKey) is string objKey ? ScopeDictionary.GetOrDefault(objKey) : null;
}
| AmbientDataContextAmbientScopeProvider |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.Tests/Types/AutoRegisteringInputObjectGraphTypeTests.cs | {
"start": 22820,
"end": 22952
} | private class ____
{
public int Id { get; set; }
public string Name { get; set; } = null!;
}
| TestBasicClass |
csharp | dotnet__BenchmarkDotNet | tests/BenchmarkDotNet.Tests/Exporters/MarkdownExporterVerifyTests.cs | {
"start": 2432,
"end": 2921
} | public class ____
{
[Params(2, 10), UsedImplicitly] public int Param;
[Benchmark] public void Base() { }
[Benchmark] public void Foo() { }
[Benchmark] public void Bar() { }
}
[RankColumn, LogicalGroupColumn, BaselineColumn]
[SimpleJob(id: "Job1"), SimpleJob(id: "Job2")]
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByMethod)]
| NoBaseline_MethodsParamsJobs |
csharp | MassTransit__MassTransit | src/MassTransit/Configuration/DependencyInjection/DependencyInjectionRegistrationExtensions.cs | {
"start": 7626,
"end": 10321
} | class
____ TImplementation : class, TService
{
services.Replace(new ServiceDescriptor(typeof(TService), typeof(TImplementation), ServiceLifetime.Scoped));
}
static void AddInstrumentation(IServiceCollection collection)
{
collection.AddOptions<InstrumentationOptions>();
collection.AddSingleton<IConfigureOptions<InstrumentationOptions>, ConfigureDefaultInstrumentationOptions>();
}
static void AddUsageTracker(IServiceCollection collection)
{
collection.AddOptions<UsageTelemetryOptions>();
collection.TryAddSingleton<IUsageTracker, UsageTracker>();
}
static void AddHostedService(IServiceCollection collection)
{
collection.AddOptions();
collection.AddHealthChecks();
collection.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<HealthCheckServiceOptions>, ConfigureBusHealthCheckServiceOptions>());
collection.AddOptions<MassTransitHostOptions>();
collection.TryAddSingleton<IValidateOptions<MassTransitHostOptions>, ValidateMassTransitHostOptions>();
collection.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, MassTransitHostedService>());
}
internal static void RemoveMassTransit(this IServiceCollection collection)
{
collection.RemoveAll<IClientFactory>();
collection.RemoveAll<Bind<IBus, IBusRegistrationContext>>();
collection.RemoveAll<IBusRegistrationContext>();
collection.RemoveAll(typeof(IReceiveEndpointDispatcher<>));
collection.RemoveAll<IReceiveEndpointDispatcherFactory>();
collection.RemoveAll<IBusDepot>();
collection.RemoveAll<IScopedConsumeContextProvider>();
collection.RemoveAll<Bind<IBus, ISetScopedConsumeContext>>();
collection.RemoveAll<Bind<IBus, IScopedConsumeContextProvider>>();
collection.RemoveAll<IScopedBusContextProvider<IBus>>();
collection.RemoveAll<ConsumeContext>();
collection.RemoveAll<ISendEndpointProvider>();
collection.RemoveAll<IPublishEndpoint>();
collection.RemoveAll(typeof(IRequestClient<>));
collection.RemoveAll<IMessageScheduler>();
collection.RemoveAll<Bind<IBus, IBusInstance>>();
collection.RemoveAll<IBusInstance>();
collection.RemoveAll<IReceiveEndpointConnector>();
collection.RemoveAll<IBusControl>();
collection.RemoveAll<IBus>();
collection.RemoveAll<IScopedClientFactory>();
}
| where |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/src/Types/Types/DirectiveType.cs | {
"start": 626,
"end": 7198
} | public partial class ____
: TypeSystemObject<DirectiveTypeConfiguration>
, IDirectiveDefinition
, IHasRuntimeType
, ITypeIdentityProvider
{
private Action<IDirectiveTypeDescriptor>? _configure;
private Func<object?[], object> _createInstance = null!;
private Action<object, object?[]> _getFieldValues = null!;
private Func<DirectiveNode, object> _parse = null!;
private Func<object, DirectiveNode> _format = null!;
private InputParser _inputParser = null!;
protected DirectiveType()
=> _configure = Configure;
public DirectiveType(Action<IDirectiveTypeDescriptor> configure)
=> _configure = configure ?? throw new ArgumentNullException(nameof(configure));
/// <summary>
/// Create a directive type from a type definition.
/// </summary>
/// <param name="definition">
/// The directive type definition that specifies the properties of the
/// newly created directive type.
/// </param>
/// <returns>
/// Returns the newly created directive type.
/// </returns>
public static DirectiveType CreateUnsafe(DirectiveTypeConfiguration definition)
=> new() { Configuration = definition };
/// <summary>
/// Gets the schema coordinate of the directive type.
/// </summary>
public SchemaCoordinate Coordinate => new(Name, ofDirective: true);
/// <summary>
/// Gets the runtime type.
/// The runtime type defines of which value the type is when it
/// manifests in the execution engine.
/// </summary>
public Type RuntimeType { get; private set; } = null!;
/// <summary>
/// Defines if this directive is repeatable. Repeatable directives are often useful when
/// the same directive should be used with different arguments at a single location,
/// especially in cases where additional information needs to be provided to a type or
/// schema extension via a directive
/// </summary>
public bool IsRepeatable { get; private set; }
/// <summary>
/// Gets the locations where this directive type can be used to annotate
/// a type system member.
/// </summary>
public DirectiveLocation Locations { get; private set; }
/// <summary>
/// Gets the directive arguments.
/// </summary>
public DirectiveArgumentCollection Arguments { get; private set; } = null!;
IReadOnlyFieldDefinitionCollection<IInputValueDefinition> IDirectiveDefinition.Arguments
=> Arguments.AsReadOnlyFieldDefinitionCollection();
/// <summary>
/// Gets the directive field middleware.
/// </summary>
public DirectiveMiddleware? Middleware { get; private set; }
/// <summary>
/// <para>Defines that this directive can be used in executable GraphQL documents.</para>
/// <para>
/// In order to be executable a directive must at least be valid
/// in one of the following locations:
/// QUERY (<see cref="DirectiveLocation.Query"/>)
/// MUTATION (<see cref="DirectiveLocation.Mutation"/>)
/// SUBSCRIPTION (<see cref="DirectiveLocation.Subscription"/>)
/// FIELD (<see cref="DirectiveLocation.Field"/>)
/// FRAGMENT_DEFINITION (<see cref="DirectiveLocation.FragmentDefinition"/>)
/// FRAGMENT_SPREAD (<see cref="DirectiveLocation.FragmentSpread"/>)
/// INLINE_FRAGMENT (<see cref="DirectiveLocation.InlineFragment"/>)
/// VARIABLE_DEFINITION (<see cref="DirectiveLocation.VariableDefinition"/>)
/// </para>
/// </summary>
public bool IsExecutableDirective { get; private set; }
/// <summary>
/// <para>Defines that this directive can be applied to type system members.</para>
/// <para>
/// In order to be a type system directive it must at least be valid
/// in one of the following locations:
/// SCHEMA (<see cref="DirectiveLocation.Schema"/>)
/// SCALAR (<see cref="DirectiveLocation.Scalar"/>)
/// OBJECT (<see cref="DirectiveLocation.Object"/>)
/// FIELD_DEFINITION (<see cref="DirectiveLocation.FieldDefinition"/>)
/// ARGUMENT_DEFINITION (<see cref="DirectiveLocation.ArgumentDefinition"/>)
/// INTERFACE (<see cref="DirectiveLocation.Interface"/>)
/// UNION (<see cref="DirectiveLocation.Union"/>)
/// ENUM (<see cref="DirectiveLocation.Enum"/>)
/// ENUM_VALUE (<see cref="DirectiveLocation.EnumValue"/>)
/// INPUT_OBJECT (<see cref="DirectiveLocation.InputObject"/>)
/// INPUT_FIELD_DEFINITION (<see cref="DirectiveLocation.InputFieldDefinition"/>)
/// </para>
/// </summary>
public bool IsTypeSystemDirective { get; private set; }
/// <summary>
/// Defines if instances of this directive type are publicly visible through introspection.
/// </summary>
internal bool IsPublic { get; private set; }
private Type? TypeIdentity { get; set; }
Type? ITypeIdentityProvider.TypeIdentity => TypeIdentity;
internal object CreateInstance(object?[] fieldValues)
=> _createInstance(fieldValues);
internal void GetFieldValues(object runtimeValue, object?[] fieldValues)
=> _getFieldValues(runtimeValue, fieldValues);
public object Parse(DirectiveNode directiveNode)
=> _parse(directiveNode);
public DirectiveNode Format(object runtimeValue)
=> _format(runtimeValue);
public T ParseArgument<T>(string name, IValueNode? value)
{
name.EnsureGraphQLName();
if (!Arguments.TryGetField(name, out var argument))
{
throw new ArgumentException(
string.Format(
Directive_GetArgumentValue_UnknownArgument,
Name,
name));
}
value ??= argument.DefaultValue ?? NullValueNode.Default;
return (T)_inputParser.ParseLiteral(value, argument, typeof(T))!;
}
/// <summary>
/// Returns the SDL representation of the current <see cref="DirectiveType"/>.
/// </summary>
/// <returns>
/// Returns the SDL representation of the current <see cref="DirectiveType"/>.
/// </returns>
public override string ToString() => SchemaDebugFormatter.Format(this).ToString(true);
/// <summary>
/// Creates a <see cref="DirectiveDefinitionNode"/> from the current <see cref="DirectiveType"/>.
/// </summary>
/// <returns>
/// Returns a <see cref="DirectiveDefinitionNode"/>.
/// </returns>
public DirectiveDefinitionNode ToSyntaxNode() => SchemaDebugFormatter.Format(this);
ISyntaxNode ISyntaxNodeProvider.ToSyntaxNode() => SchemaDebugFormatter.Format(this);
}
| DirectiveType |
csharp | dotnet__efcore | src/EFCore/Metadata/ITypeBase.cs | {
"start": 428,
"end": 12612
} | public interface ____ : IReadOnlyTypeBase, IAnnotatable
{
/// <summary>
/// Gets the model that this type belongs to.
/// </summary>
new IModel Model { get; }
/// <summary>
/// Gets this entity type or the one on which the complex property chain is declared.
/// </summary>
new IEntityType ContainingEntityType
=> (IEntityType)this;
/// <summary>
/// Gets the base type of this type. Returns <see langword="null" /> if this is not a derived type in an inheritance
/// hierarchy.
/// </summary>
new ITypeBase? BaseType { get; }
/// <summary>
/// Gets the <see cref="InstantiationBinding" /> for the preferred constructor.
/// </summary>
InstantiationBinding? ConstructorBinding { get; }
/// <summary>
/// Gets all types in the model that derive from this type.
/// </summary>
/// <returns>The derived types.</returns>
new IEnumerable<ITypeBase> GetDerivedTypes()
=> ((IReadOnlyTypeBase)this).GetDerivedTypes().Cast<ITypeBase>();
/// <summary>
/// Returns all derived types of this type, including the type itself.
/// </summary>
/// <returns>Derived types.</returns>
new IEnumerable<ITypeBase> GetDerivedTypesInclusive()
=> ((IReadOnlyTypeBase)this).GetDerivedTypesInclusive().Cast<ITypeBase>();
/// <summary>
/// Gets all types in the model that directly derive from this type.
/// </summary>
/// <returns>The derived types.</returns>
new IEnumerable<ITypeBase> GetDirectlyDerivedTypes();
/// <summary>
/// Returns the <see cref="IProperty" /> that will be used for storing a discriminator value.
/// </summary>
new IProperty? FindDiscriminatorProperty()
=> (IProperty?)((IReadOnlyTypeBase)this).FindDiscriminatorProperty();
/// <summary>
/// Gets a property on the given type. Returns <see langword="null" /> if no property is found.
/// </summary>
/// <remarks>
/// This API only finds scalar properties and does not find navigation, complex or service properties.
/// </remarks>
/// <param name="memberInfo">The member on the CLR type.</param>
/// <returns>The property, or <see langword="null" /> if none is found.</returns>
new IProperty? FindProperty(MemberInfo memberInfo)
=> (IProperty?)((IReadOnlyTypeBase)this).FindProperty(memberInfo);
/// <summary>
/// Gets the property with a given name. Returns <see langword="null" /> if no property with the given name is defined.
/// </summary>
/// <remarks>
/// This API only finds scalar properties and does not find navigation, complex or service properties.
/// </remarks>
/// <param name="name">The name of the property.</param>
/// <returns>The property, or <see langword="null" /> if none is found.</returns>
new IProperty? FindProperty(string name);
/// <summary>
/// Finds matching properties on the given type. Returns <see langword="null" /> if any property is not found.
/// </summary>
/// <remarks>
/// This API only finds scalar properties and does not find navigation, complex or service properties.
/// </remarks>
/// <param name="propertyNames">The property names.</param>
/// <returns>The properties, or <see langword="null" /> if any property is not found.</returns>
new IReadOnlyList<IProperty>? FindProperties(
IReadOnlyList<string> propertyNames)
=> (IReadOnlyList<IProperty>?)((IReadOnlyTypeBase)this).FindProperties(propertyNames);
/// <summary>
/// Gets a property with the given name.
/// </summary>
/// <remarks>
/// This API only finds scalar properties and does not find navigation, complex or service properties.
/// </remarks>
/// <param name="name">The property name.</param>
/// <returns>The property.</returns>
new IProperty GetProperty(string name)
=> (IProperty)((IReadOnlyTypeBase)this).GetProperty(name);
/// <summary>
/// Finds a property declared on the type with the given name.
/// Does not return properties defined on a base type.
/// </summary>
/// <param name="name">The property name.</param>
/// <returns>The property, or <see langword="null" /> if none is found.</returns>
new IProperty? FindDeclaredProperty(string name)
=> (IProperty?)((IReadOnlyTypeBase)this).FindDeclaredProperty(name);
/// <summary>
/// Gets all non-navigation properties declared on this type.
/// </summary>
/// <remarks>
/// This method does not return properties declared on base types.
/// It is useful when iterating over all types to avoid processing the same property more than once.
/// Use <see cref="GetProperties" /> to also return properties declared on base types.
/// </remarks>
/// <returns>Declared non-navigation properties.</returns>
new IEnumerable<IProperty> GetDeclaredProperties();
/// <summary>
/// Gets all non-navigation properties declared on the types derived from this type.
/// </summary>
/// <remarks>
/// This method does not return properties declared on the given type itself.
/// Use <see cref="GetProperties" /> to return properties declared on this
/// and base typed types.
/// </remarks>
/// <returns>Derived non-navigation properties.</returns>
new IEnumerable<IProperty> GetDerivedProperties()
=> ((IReadOnlyTypeBase)this).GetDerivedProperties().Cast<IProperty>();
/// <summary>
/// Gets the properties defined on this type.
/// </summary>
/// <remarks>
/// This API only returns scalar properties and does not return navigation, complex or service properties.
/// </remarks>
/// <returns>The properties defined on this type.</returns>
new IEnumerable<IProperty> GetProperties();
/// <summary>
/// Returns the properties that need a value to be generated when the entity entry transitions to the
/// <see cref="EntityState.Added" /> state, including properties defined on non-collection complex types.
/// </summary>
/// <returns>The properties that need a value to be generated on add.</returns>
IEnumerable<IProperty> GetFlattenedValueGeneratingProperties();
/// <summary>
/// Gets the complex property with a given name. Returns <see langword="null" /> if no property with the given name is defined.
/// </summary>
/// <remarks>
/// This API only finds complex properties and does not find navigation, scalar or service properties.
/// </remarks>
/// <param name="name">The name of the property.</param>
/// <returns>The property, or <see langword="null" /> if none is found.</returns>
new IComplexProperty? FindComplexProperty(string name);
/// <summary>
/// Gets a complex property with the given member info. Returns <see langword="null" /> if no property is found.
/// </summary>
/// <remarks>
/// This API only finds complex properties and does not find navigation, scalar or service properties.
/// </remarks>
/// <param name="memberInfo">The member on the entity class.</param>
/// <returns>The property, or <see langword="null" /> if none is found.</returns>
new IComplexProperty? FindComplexProperty(MemberInfo memberInfo)
=> (IComplexProperty?)((IReadOnlyTypeBase)this).FindComplexProperty(memberInfo);
/// <summary>
/// Finds a property declared on the type with the given name.
/// Does not return properties defined on a base type.
/// </summary>
/// <remarks>
/// This API only finds complex properties and does not find navigation, scalar or service properties.
/// </remarks>
/// <param name="name">The property name.</param>
/// <returns>The property, or <see langword="null" /> if none is found.</returns>
new IComplexProperty? FindDeclaredComplexProperty(string name)
=> (IComplexProperty?)((IReadOnlyTypeBase)this).FindDeclaredComplexProperty(name);
/// <summary>
/// Gets the complex properties defined on this entity type.
/// </summary>
/// <remarks>
/// This API only returns complex properties and does not find navigation, scalar or service properties.
/// </remarks>
/// <returns>The complex properties defined on this entity type.</returns>
new IEnumerable<IComplexProperty> GetComplexProperties();
/// <summary>
/// Gets the complex properties declared on this entity type.
/// </summary>
/// <returns>Declared complex properties.</returns>
new IEnumerable<IComplexProperty> GetDeclaredComplexProperties();
/// <summary>
/// Gets the complex properties declared on the types derived from this entity type.
/// </summary>
/// <remarks>
/// This method does not return complex properties declared on the given entity type itself.
/// Use <see cref="GetComplexProperties" /> to return complex properties declared on this
/// and base entity typed types.
/// </remarks>
/// <returns>Derived complex properties.</returns>
new IEnumerable<IComplexProperty> GetDerivedComplexProperties()
=> ((IReadOnlyTypeBase)this).GetDerivedComplexProperties().Cast<IComplexProperty>();
/// <summary>
/// Gets the members defined on this type and base types.
/// </summary>
/// <returns>Type members.</returns>
new IEnumerable<IPropertyBase> GetMembers();
/// <summary>
/// Gets the members declared on this type.
/// </summary>
/// <returns>Declared members.</returns>
new IEnumerable<IPropertyBase> GetDeclaredMembers();
/// <summary>
/// Gets the member with the given name. Returns <see langword="null" /> if no member with the given name is defined.
/// </summary>
/// <remarks>
/// This API only finds scalar properties and does not find navigation, complex or service properties.
/// </remarks>
/// <param name="name">The name of the property.</param>
/// <returns>The property, or <see langword="null" /> if none is found.</returns>
new IPropertyBase? FindMember(string name);
/// <summary>
/// Gets the members with the given name on this type, base types or derived types.
/// </summary>
/// <returns>Type members.</returns>
new IEnumerable<IPropertyBase> FindMembersInHierarchy(string name);
/// <summary>
/// Returns all members that may need a snapshot value when change tracking.
/// </summary>
/// <returns>The members.</returns>
IEnumerable<IPropertyBase> GetSnapshottableMembers();
/// <summary>
/// Gets all properties declared on the base types and types derived from this entity type.
/// </summary>
/// <returns>The properties.</returns>
IEnumerable<IProperty> GetPropertiesInHierarchy()
=> throw new NotSupportedException();
/// <summary>
/// Returns all properties that implement <see cref="IProperty" />, including those on non-collection complex types.
/// </summary>
/// <returns>The properties.</returns>
IEnumerable<IProperty> GetFlattenedProperties();
/// <summary>
/// Returns all properties that implement <see cref="IComplexProperty" />, including those on non-collection complex types.
/// </summary>
/// <returns>The properties.</returns>
IEnumerable<IComplexProperty> GetFlattenedComplexProperties();
/// <summary>
/// Returns all declared properties that implement <see cref="IProperty" />, including those on non-collection complex types.
/// </summary>
/// <returns>The properties.</returns>
IEnumerable<IProperty> GetFlattenedDeclaredProperties();
/// <summary>
/// Gets all properties declared on the base types and types derived from this entity type, including those on non-collection complex
/// types.
/// </summary>
/// <returns>The properties.</returns>
IEnumerable<IProperty> GetFlattenedPropertiesInHierarchy()
=> throw new NotSupportedException();
}
| ITypeBase |
csharp | App-vNext__Polly | src/Polly/Caching/ISyncCacheProvider.cs | {
"start": 185,
"end": 1205
} | public interface ____
{
#pragma warning disable SA1414
/// <summary>
/// Gets a value from cache.
/// </summary>
/// <param name="key">The cache key.</param>
/// <returns>
/// A tuple whose first element is a value indicating whether the key was found in the cache,
/// and whose second element is the value from the cache (null if not found).
/// </returns>
(bool, object?) TryGet(string key);
#pragma warning restore SA1414
/// <summary>
/// Puts the specified value in the cache.
/// </summary>
/// <param name="key">The cache key.</param>
/// <param name="value">The value to put into the cache.</param>
/// <param name="ttl">The time-to-live for the cache entry.</param>
void Put(string key, object? value, Ttl ttl);
}
/// <summary>
/// Defines methods for classes providing synchronous cache functionality for Polly <see cref="CachePolicy{TResult}"/>s.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
| ISyncCacheProvider |
csharp | xunit__xunit | src/xunit.v1.tests/xunit/NotNullTests.cs | {
"start": 51,
"end": 280
} | public class ____
{
[Fact]
public void NotNull()
{
Assert.NotNull(new object());
}
[Fact]
public void NotNullThrowsException()
{
Assert.Throws<NotNullException>(() => Assert.NotNull(null));
}
}
}
| NotNullTests |
csharp | MassTransit__MassTransit | tests/MassTransit.EventHubIntegration.Tests/Configuration.cs | {
"start": 55,
"end": 421
} | static class ____
{
public static string ConsumerGroup = "cg1";
public static string EventHubNamespace =>
"Endpoint=sb://localhost;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;";
public static string StorageAccount => "UseDevelopmentStorage=true";
}
}
| Configuration |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs | {
"start": 3956,
"end": 11195
} | class ____ the original parameters.</summary>
/// <remarks>Set in MatchEnumeratorCreationPattern() and ResolveIEnumerableIEnumeratorFieldMapping()</remarks>
readonly Dictionary<IField, ILVariable> fieldToParameterMap = new Dictionary<IField, ILVariable>();
/// <summary>This dictionary stores the information extracted from the Dispose() method:
/// for each "Finally Method", it stores the set of states for which the method is being called.</summary>
/// <remarks>Set in ConstructExceptionTable()</remarks>
Dictionary<IMethod, LongSet> finallyMethodToStateRange;
/// <summary>
/// For each finally method, stores the target state when entering the finally block,
/// and the decompiled code of the finally method body.
/// </summary>
readonly Dictionary<IMethod, (int? outerState, ILFunction function)> decompiledFinallyMethods = new Dictionary<IMethod, (int? outerState, ILFunction body)>();
/// <summary>
/// Temporary stores for 'yield break'.
/// </summary>
readonly List<StLoc> returnStores = new List<StLoc>();
/// <summary>
/// Local bool variable in MoveNext() that signifies whether to skip finally bodies.
/// </summary>
ILVariable skipFinallyBodies;
/// <summary>
/// Local bool variable in MoveNext() that signifies whether to execute finally bodies.
/// </summary>
ILVariable doFinallyBodies;
/// <summary>
/// Set of variables might hold copies of the generated state field.
/// </summary>
HashSet<ILVariable> cachedStateVars;
#region Run() method
public void Run(ILFunction function, ILTransformContext context)
{
if (!context.Settings.YieldReturn)
return; // abort if enumerator decompilation is disabled
this.context = context;
this.metadata = context.PEFile.Metadata;
this.currentType = metadata.GetMethodDefinition((MethodDefinitionHandle)context.Function.Method.MetadataToken).GetDeclaringType();
this.enumeratorType = default;
this.enumeratorCtor = default;
this.isCompiledWithMono = false;
this.isCompiledWithVisualBasic = false;
this.isCompiledWithLegacyVisualBasic = false;
this.stateField = null;
this.currentField = null;
this.disposingField = null;
this.fieldToParameterMap.Clear();
this.finallyMethodToStateRange = null;
this.decompiledFinallyMethods.Clear();
this.returnStores.Clear();
this.skipFinallyBodies = null;
this.doFinallyBodies = null;
this.cachedStateVars = null;
if (!MatchEnumeratorCreationPattern(function))
return;
BlockContainer newBody;
try
{
AnalyzeCtor();
AnalyzeCurrentProperty();
ResolveIEnumerableIEnumeratorFieldMapping();
ConstructExceptionTable();
newBody = AnalyzeMoveNext(function);
}
catch (SymbolicAnalysisFailedException ex)
{
function.Warnings.Add($"yield-return decompiler failed: {ex.Message}");
return;
}
context.Step("Replacing body with MoveNext() body", function);
function.IsIterator = true;
function.StateMachineCompiledWithMono = isCompiledWithMono;
function.StateMachineCompiledWithLegacyVisualBasic = isCompiledWithLegacyVisualBasic;
var oldBody = function.Body;
function.Body = newBody;
// register any locals used in newBody
function.Variables.AddRange(newBody.Descendants.OfType<IInstructionWithVariableOperand>().Select(inst => inst.Variable).Distinct());
PrintFinallyMethodStateRanges(newBody);
// Add state machine field meta-data to parameter ILVariables.
foreach (var (f, p) in fieldToParameterMap)
{
p.StateMachineField = f;
}
context.Step("Delete unreachable blocks", function);
if (isCompiledWithMono || isCompiledWithVisualBasic)
{
// mono has try-finally inline (like async on MS); we also need to sort nested blocks:
foreach (var nestedContainer in newBody.Blocks.SelectMany(c => c.Descendants).OfType<BlockContainer>())
{
nestedContainer.SortBlocks(deleteUnreachableBlocks: true);
}
// We need to clean up nested blocks before the main block, so that edges from unreachable code
// in nested containers into the main container are removed before we clean up the main container.
}
// Note: because this only deletes blocks outright, the 'stateChanges' entries remain valid
// (though some may point to now-deleted blocks)
newBody.SortBlocks(deleteUnreachableBlocks: true);
function.CheckInvariant(ILPhase.Normal);
try
{
if (isCompiledWithMono)
{
CleanSkipFinallyBodies(function);
}
else if (isCompiledWithLegacyVisualBasic)
{
CleanDoFinallyBodies(function);
}
else if (isCompiledWithVisualBasic)
{
CleanFinallyStateChecks(function);
}
else
{
DecompileFinallyBlocks();
ReconstructTryFinallyBlocks(function);
}
}
catch (SymbolicAnalysisFailedException ex)
{
// Revert the yield-return transformation
context.Step("Transform failed, roll it back", function);
function.IsIterator = false;
function.StateMachineCompiledWithMono = false;
function.StateMachineCompiledWithLegacyVisualBasic = false;
function.Body = oldBody;
function.Variables.RemoveDead();
function.Warnings.Add($"yield-return decompiler failed: {ex.Message}");
return;
}
context.Step("Translate fields to local accesses", function);
TranslateFieldsToLocalAccess(function, function, fieldToParameterMap, isCompiledWithMono);
// On mono, we still need to remove traces of the state variable(s):
if (isCompiledWithMono || isCompiledWithVisualBasic)
{
if (fieldToParameterMap.TryGetValue(stateField, out var stateVar))
{
returnStores.AddRange(stateVar.StoreInstructions.OfType<StLoc>());
}
foreach (var cachedStateVar in cachedStateVars)
{
returnStores.AddRange(cachedStateVar.StoreInstructions.OfType<StLoc>());
}
}
if (returnStores.Count > 0)
{
context.Step("Remove temporaries", function);
foreach (var store in returnStores)
{
if (store.Variable.LoadCount == 0 && store.Variable.AddressCount == 0 && store.Parent is Block block)
{
Debug.Assert(SemanticHelper.IsPure(store.Value.Flags));
block.Instructions.Remove(store);
}
}
}
// Re-run control flow simplification over the newly constructed set of gotos,
// and inlining because TranslateFieldsToLocalAccess() might have opened up new inlining opportunities.
function.RunTransforms(CSharpDecompiler.EarlyILTransforms(), context);
}
#endregion
#region Match the enumerator creation pattern
bool MatchEnumeratorCreationPattern(ILFunction function)
{
Block body = SingleBlock(function.Body);
if (body == null || body.Instructions.Count == 0)
{
return false;
}
ILInstruction newObj;
if (body.Instructions.Count == 1)
{
// No parameters passed to enumerator (not even 'this'):
// ret(newobj(...))
if (!body.Instructions[0].MatchReturn(out newObj))
return false;
if (MatchEnumeratorCreationNewObj(newObj))
{
return true;
}
else if (MatchMonoEnumeratorCreationNewObj(newObj))
{
isCompiledWithMono = true;
return true;
}
else
{
return false;
}
}
// If there's parameters passed to the helper class, the | to |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 3107173,
"end": 3107544
} | public partial interface ____ : IOnFusionConfigurationPublishingTaskChanged_OnFusionConfigurationPublishingTaskChanged_Changes_Changes_6, IUnionMemberAdded
{
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| IOnFusionConfigurationPublishingTaskChanged_OnFusionConfigurationPublishingTaskChanged_Changes_Changes_UnionMemberAdded |
csharp | icsharpcode__ILSpy | ICSharpCode.ILSpyX/Analyzers/Builtin/FindTypeInAttributeDecoder.cs | {
"start": 2140,
"end": 5697
} | class ____ : ICustomAttributeTypeProvider<TokenSearchResult>
{
readonly MetadataFile declaringModule;
readonly MetadataModule currentModule;
readonly TypeDefinitionHandle handle;
readonly PrimitiveTypeCode primitiveType;
/// <summary>
/// Constructs a FindTypeInAttributeDecoder that can be used to find <paramref name="type"/> in signatures from <paramref name="currentModule"/>.
/// </summary>
public FindTypeInAttributeDecoder(MetadataModule currentModule, ITypeDefinition type)
{
this.currentModule = currentModule;
this.declaringModule = type.ParentModule?.MetadataFile ?? throw new InvalidOperationException("Cannot use MetadataModule without PEFile as context.");
this.handle = (TypeDefinitionHandle)type.MetadataToken;
this.primitiveType = type.KnownTypeCode == KnownTypeCode.None ? 0 : type.KnownTypeCode.ToPrimitiveTypeCode();
}
public TokenSearchResult GetPrimitiveType(PrimitiveTypeCode typeCode)
{
return typeCode == primitiveType ? TokenSearchResult.Found : 0;
}
public TokenSearchResult GetSystemType() => TokenSearchResult.SystemType;
public TokenSearchResult GetSZArrayType(TokenSearchResult elementType) => elementType & TokenSearchResult.Found;
public TokenSearchResult GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind)
{
TokenSearchResult result = TokenSearchResult.NoResult;
if (handle.IsEnum(reader, out PrimitiveTypeCode underlyingType))
{
result = (TokenSearchResult)underlyingType;
}
else if (((EntityHandle)handle).IsKnownType(reader, KnownTypeCode.Type))
{
result = TokenSearchResult.SystemType;
}
if (this.handle == handle && reader == declaringModule.Metadata)
{
result |= TokenSearchResult.Found;
}
return result;
}
public TokenSearchResult GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind)
{
var t = currentModule.ResolveType(handle, default);
return GetResultFromResolvedType(t);
}
public TokenSearchResult GetTypeFromSerializedName(string name)
{
if (name == null)
{
return TokenSearchResult.NoResult;
}
try
{
IType type = ReflectionHelper.ParseReflectionName(name, new SimpleTypeResolveContext(currentModule));
return GetResultFromResolvedType(type);
}
catch (ReflectionNameParseException)
{
return TokenSearchResult.NoResult;
}
}
private TokenSearchResult GetResultFromResolvedType(IType type)
{
var td = type.GetDefinition();
if (td == null)
return TokenSearchResult.NoResult;
TokenSearchResult result = TokenSearchResult.NoResult;
var underlyingType = td.EnumUnderlyingType?.GetDefinition();
if (underlyingType != null)
{
result = (TokenSearchResult)underlyingType.KnownTypeCode.ToPrimitiveTypeCode();
}
else if (td.KnownTypeCode == KnownTypeCode.Type)
{
result = TokenSearchResult.SystemType;
}
if (td.MetadataToken == this.handle && td.ParentModule?.MetadataFile == declaringModule)
{
result |= TokenSearchResult.Found;
}
return result;
}
public PrimitiveTypeCode GetUnderlyingEnumType(TokenSearchResult type)
{
TokenSearchResult typeCode = type & TokenSearchResult.TypeCodeMask;
if (typeCode == 0 || typeCode == TokenSearchResult.SystemType)
throw new EnumUnderlyingTypeResolveException();
return (PrimitiveTypeCode)typeCode;
}
public bool IsSystemType(TokenSearchResult type) => (type & TokenSearchResult.TypeCodeMask) == TokenSearchResult.SystemType;
}
}
| FindTypeInAttributeDecoder |
csharp | exceptionless__Exceptionless | tests/Exceptionless.Tests/SerializerTests.cs | {
"start": 332,
"end": 6712
} | public class ____ : TestWithServices
{
public SerializerTests(ITestOutputHelper output) : base(output) { }
[Fact]
public void CanDeserializeEventWithUnknownNamesAndProperties()
{
const string json = @"{""tags"":[""One"",""Two""],""reference_id"":""12"",""Message"":""Hello"",""SomeString"":""Hi"",""SomeBool"":false,""SomeNum"":1,""UnknownProp"":{""Blah"":""SomeVal""},""Some"":{""Blah"":""SomeVal""},""@error"":{""Message"":""SomeVal"",""SomeProp"":""SomeVal""},""Some2"":""{\""Blah\"":\""SomeVal\""}"",""UnknownSerializedProp"":""{\""Blah\"":\""SomeVal\""}""}";
var settings = new JsonSerializerSettings();
var knownDataTypes = new Dictionary<string, Type> {
{ "Some", typeof(SomeModel) },
{ "Some2", typeof(SomeModel) },
{ Event.KnownDataKeys.Error, typeof(Error) }
};
settings.Converters.Add(new DataObjectConverter<Event>(_logger, knownDataTypes));
settings.Converters.Add(new DataObjectConverter<Error>(_logger));
var ev = json.FromJson<Event>(settings);
Assert.NotNull(ev?.Data);
Assert.Equal(8, ev.Data.Count);
Assert.Equal("Hi", ev.Data.GetString("SomeString"));
Assert.False(ev.Data.GetBoolean("SomeBool"));
Assert.Equal(1L, ev.Data["SomeNum"]);
Assert.Equal(typeof(JObject), ev.Data["UnknownProp"]?.GetType());
Assert.Equal(typeof(JObject), ev.Data["UnknownSerializedProp"]?.GetType());
Assert.Equal("SomeVal", (string)((dynamic)ev.Data["UnknownProp"]!)?.Blah!);
Assert.Equal(typeof(SomeModel), ev.Data["Some"]?.GetType());
Assert.Equal(typeof(SomeModel), ev.Data["Some2"]?.GetType());
Assert.Equal("SomeVal", (ev.Data["Some"] as SomeModel)?.Blah);
Assert.Equal(typeof(Error), ev.Data[Event.KnownDataKeys.Error]?.GetType());
Assert.Equal("SomeVal", ((Error)ev.Data[Event.KnownDataKeys.Error]!)?.Message);
Assert.Single(((Error)ev.Data[Event.KnownDataKeys.Error]!)?.Data!);
Assert.Equal("SomeVal", ((Error)ev.Data[Event.KnownDataKeys.Error]!)?.Data?["SomeProp"]);
Assert.Equal("Hello", ev.Message);
Assert.NotNull(ev.Tags);
Assert.Equal(2, ev.Tags.Count);
Assert.Contains("One", ev.Tags);
Assert.Contains("Two", ev.Tags);
Assert.Equal("12", ev.ReferenceId);
const string expectedjson = @"{""Tags"":[""One"",""Two""],""Message"":""Hello"",""Data"":{""SomeString"":""Hi"",""SomeBool"":false,""SomeNum"":1,""UnknownProp"":{""Blah"":""SomeVal""},""Some"":{""Blah"":""SomeVal""},""@error"":{""Modules"":[],""Message"":""SomeVal"",""Data"":{""SomeProp"":""SomeVal""},""StackTrace"":[]},""Some2"":{""Blah"":""SomeVal""},""UnknownSerializedProp"":{""Blah"":""SomeVal""}},""ReferenceId"":""12""}";
string newjson = ev.ToJson(Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore });
Assert.Equal(expectedjson, newjson);
}
[Fact]
public void CanDeserializeEventWithInvalidKnownDataTypes()
{
const string json = @"{""Message"":""Hello"",""Some"":""{\""Blah\"":\""SomeVal\""}"",""@Some"":""{\""Blah\"":\""SomeVal\""}""}";
const string jsonWithInvalidDataType = @"{""Message"":""Hello"",""@Some"":""Testing"",""@string"":""Testing""}";
var settings = new JsonSerializerSettings();
var knownDataTypes = new Dictionary<string, Type> {
{ "Some", typeof(SomeModel) },
{ "@Some", typeof(SomeModel) },
{ "_@Some", typeof(SomeModel) },
{ "@string", typeof(string) }
};
settings.Converters.Add(new DataObjectConverter<Event>(_logger, knownDataTypes));
var ev = json.FromJson<Event>(settings);
Assert.NotNull(ev?.Data);
Assert.Equal(2, ev.Data.Count);
Assert.True(ev.Data.ContainsKey("Some"));
Assert.Equal("SomeVal", (ev.Data["Some"] as SomeModel)?.Blah);
Assert.True(ev.Data.ContainsKey("@Some"));
Assert.Equal("SomeVal", (ev.Data["@Some"] as SomeModel)?.Blah);
ev = jsonWithInvalidDataType.FromJson<Event>(settings);
Assert.NotNull(ev?.Data);
Assert.Equal(2, ev.Data.Count);
Assert.True(ev.Data.ContainsKey("_@Some1"));
Assert.Equal("Testing", ev.Data["_@Some1"] as string);
Assert.True(ev.Data.ContainsKey("@string"));
Assert.Equal("Testing", ev.Data["@string"] as string);
}
[Fact]
public void CanDeserializeEventWithData()
{
const string json = @"{""Message"":""Hello"",""Data"":{""Blah"":""SomeVal""}}";
var settings = new JsonSerializerSettings();
settings.Converters.Add(new DataObjectConverter<Event>(_logger));
var ev = json.FromJson<Event>(settings);
Assert.NotNull(ev?.Data);
Assert.Single(ev.Data);
Assert.Equal("Hello", ev.Message);
Assert.Equal("SomeVal", ev.Data["Blah"]);
}
[Fact]
public void CanDeserializeWebHook()
{
var hook = new WebHook
{
Id = "test",
EventTypes = ["NewError"],
Version = WebHook.KnownVersions.Version2
};
var serializer = GetService<ITextSerializer>();
string json = serializer.SerializeToString(hook);
Assert.Equal("{\"id\":\"test\",\"event_types\":[\"NewError\"],\"is_enabled\":true,\"version\":\"v2\",\"created_utc\":\"0001-01-01T00:00:00\"}", json);
var model = serializer.Deserialize<WebHook>(json);
Assert.Equal(hook.Id, model.Id);
Assert.Equal(hook.EventTypes, model.EventTypes);
Assert.Equal(hook.Version, model.Version);
}
[Fact]
public void CanDeserializeProject()
{
string json = "{\"last_event_date_utc\":\"2020-10-18T20:54:04.3457274+01:00\", \"created_utc\":\"0001-01-01T00:00:00\",\"updated_utc\":\"2020-09-21T04:41:32.7458321Z\"}";
var serializer = GetService<ITextSerializer>();
var model = serializer.Deserialize<Project>(json);
Assert.NotNull(model);
Assert.NotNull(model.LastEventDateUtc);
Assert.NotEqual(DateTime.MinValue, model.LastEventDateUtc);
Assert.Equal(DateTime.MinValue, model.CreatedUtc);
Assert.NotEqual(DateTime.MinValue, model.UpdatedUtc);
}
}
| SerializerTests |
csharp | jbogard__MediatR | src/MediatR/MicrosoftExtensionsDI/MediatrServiceConfiguration.cs | {
"start": 5729,
"end": 8131
} | interface ____</typeparam>
/// <typeparam name="TImplementationType">Closed behavior implementation type</typeparam>
/// <param name="serviceLifetime">Optional service lifetime, defaults to <see cref="ServiceLifetime.Transient"/>.</param>
/// <returns>This</returns>
public MediatRServiceConfiguration AddBehavior<TServiceType, TImplementationType>(ServiceLifetime serviceLifetime = ServiceLifetime.Transient)
=> AddBehavior(typeof(TServiceType), typeof(TImplementationType), serviceLifetime);
/// <summary>
/// Register a closed behavior type against all <see cref="IPipelineBehavior{TRequest,TResponse}"/> implementations
/// </summary>
/// <typeparam name="TImplementationType">Closed behavior implementation type</typeparam>
/// <param name="serviceLifetime">Optional service lifetime, defaults to <see cref="ServiceLifetime.Transient"/>.</param>
/// <returns>This</returns>
public MediatRServiceConfiguration AddBehavior<TImplementationType>(ServiceLifetime serviceLifetime = ServiceLifetime.Transient)
{
return AddBehavior(typeof(TImplementationType), serviceLifetime);
}
/// <summary>
/// Register a closed behavior type against all <see cref="IPipelineBehavior{TRequest,TResponse}"/> implementations
/// </summary>
/// <param name="implementationType">Closed behavior implementation type</param>
/// <param name="serviceLifetime">Optional service lifetime, defaults to <see cref="ServiceLifetime.Transient"/>.</param>
/// <returns>This</returns>
public MediatRServiceConfiguration AddBehavior(Type implementationType, ServiceLifetime serviceLifetime = ServiceLifetime.Transient)
{
var implementedGenericInterfaces = implementationType.FindInterfacesThatClose(typeof(IPipelineBehavior<,>)).ToList();
if (implementedGenericInterfaces.Count == 0)
{
throw new InvalidOperationException($"{implementationType.Name} must implement {typeof(IPipelineBehavior<,>).FullName}");
}
foreach (var implementedBehaviorType in implementedGenericInterfaces)
{
BehaviorsToRegister.Add(new ServiceDescriptor(implementedBehaviorType, implementationType, serviceLifetime));
}
return this;
}
/// <summary>
/// Register a closed behavior type
/// </summary>
/// <param name="serviceType">Closed behavior | type |
csharp | nuke-build__nuke | source/Nuke.Common/Tools/Kubernetes/Kubernetes.Generated.cs | {
"start": 875159,
"end": 876339
} | public partial class ____ : Enumeration
{
public static KubernetesRunOutput json = (KubernetesRunOutput) "json";
public static KubernetesRunOutput yaml = (KubernetesRunOutput) "yaml";
public static KubernetesRunOutput name = (KubernetesRunOutput) "name";
public static KubernetesRunOutput templatefile = (KubernetesRunOutput) "templatefile";
public static KubernetesRunOutput template = (KubernetesRunOutput) "template";
public static KubernetesRunOutput go_template = (KubernetesRunOutput) "go-template";
public static KubernetesRunOutput go_template_file = (KubernetesRunOutput) "go-template-file";
public static KubernetesRunOutput jsonpath = (KubernetesRunOutput) "jsonpath";
public static KubernetesRunOutput jsonpath_file = (KubernetesRunOutput) "jsonpath-file";
public static implicit operator KubernetesRunOutput(string value)
{
return new KubernetesRunOutput { Value = value };
}
}
#endregion
#region KubernetesGetOutput
/// <summary>Used within <see cref="KubernetesTasks"/>.</summary>
[PublicAPI]
[Serializable]
[ExcludeFromCodeCoverage]
[TypeConverter(typeof(TypeConverter<KubernetesGetOutput>))]
| KubernetesRunOutput |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Web.Http.Headers/HttpContentDispositionHeaderValue.cs | {
"start": 299,
"end": 8870
} | public partial class ____ : global::Windows.Foundation.IStringable
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public ulong? Size
{
get
{
throw new global::System.NotImplementedException("The member ulong? HttpContentDispositionHeaderValue.Size is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=ulong%3F%20HttpContentDispositionHeaderValue.Size");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Http.Headers.HttpContentDispositionHeaderValue", "ulong? HttpContentDispositionHeaderValue.Size");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public string Name
{
get
{
throw new global::System.NotImplementedException("The member string HttpContentDispositionHeaderValue.Name is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20HttpContentDispositionHeaderValue.Name");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Http.Headers.HttpContentDispositionHeaderValue", "string HttpContentDispositionHeaderValue.Name");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public string FileNameStar
{
get
{
throw new global::System.NotImplementedException("The member string HttpContentDispositionHeaderValue.FileNameStar is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20HttpContentDispositionHeaderValue.FileNameStar");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Http.Headers.HttpContentDispositionHeaderValue", "string HttpContentDispositionHeaderValue.FileNameStar");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public string FileName
{
get
{
throw new global::System.NotImplementedException("The member string HttpContentDispositionHeaderValue.FileName is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20HttpContentDispositionHeaderValue.FileName");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Http.Headers.HttpContentDispositionHeaderValue", "string HttpContentDispositionHeaderValue.FileName");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public string DispositionType
{
get
{
throw new global::System.NotImplementedException("The member string HttpContentDispositionHeaderValue.DispositionType is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20HttpContentDispositionHeaderValue.DispositionType");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Http.Headers.HttpContentDispositionHeaderValue", "string HttpContentDispositionHeaderValue.DispositionType");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Collections.Generic.IList<global::Windows.Web.Http.Headers.HttpNameValueHeaderValue> Parameters
{
get
{
throw new global::System.NotImplementedException("The member IList<HttpNameValueHeaderValue> HttpContentDispositionHeaderValue.Parameters is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IList%3CHttpNameValueHeaderValue%3E%20HttpContentDispositionHeaderValue.Parameters");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public HttpContentDispositionHeaderValue(string dispositionType)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Http.Headers.HttpContentDispositionHeaderValue", "HttpContentDispositionHeaderValue.HttpContentDispositionHeaderValue(string dispositionType)");
}
#endif
// Forced skipping of method Windows.Web.Http.Headers.HttpContentDispositionHeaderValue.HttpContentDispositionHeaderValue(string)
// Forced skipping of method Windows.Web.Http.Headers.HttpContentDispositionHeaderValue.DispositionType.get
// Forced skipping of method Windows.Web.Http.Headers.HttpContentDispositionHeaderValue.DispositionType.set
// Forced skipping of method Windows.Web.Http.Headers.HttpContentDispositionHeaderValue.FileName.get
// Forced skipping of method Windows.Web.Http.Headers.HttpContentDispositionHeaderValue.FileName.set
// Forced skipping of method Windows.Web.Http.Headers.HttpContentDispositionHeaderValue.FileNameStar.get
// Forced skipping of method Windows.Web.Http.Headers.HttpContentDispositionHeaderValue.FileNameStar.set
// Forced skipping of method Windows.Web.Http.Headers.HttpContentDispositionHeaderValue.Name.get
// Forced skipping of method Windows.Web.Http.Headers.HttpContentDispositionHeaderValue.Name.set
// Forced skipping of method Windows.Web.Http.Headers.HttpContentDispositionHeaderValue.Parameters.get
// Forced skipping of method Windows.Web.Http.Headers.HttpContentDispositionHeaderValue.Size.get
// Forced skipping of method Windows.Web.Http.Headers.HttpContentDispositionHeaderValue.Size.set
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public override string ToString()
{
throw new global::System.NotImplementedException("The member string HttpContentDispositionHeaderValue.ToString() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20HttpContentDispositionHeaderValue.ToString%28%29");
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public static global::Windows.Web.Http.Headers.HttpContentDispositionHeaderValue Parse(string input)
{
throw new global::System.NotImplementedException("The member HttpContentDispositionHeaderValue HttpContentDispositionHeaderValue.Parse(string input) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=HttpContentDispositionHeaderValue%20HttpContentDispositionHeaderValue.Parse%28string%20input%29");
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public static bool TryParse(string input, out global::Windows.Web.Http.Headers.HttpContentDispositionHeaderValue contentDispositionHeaderValue)
{
throw new global::System.NotImplementedException("The member bool HttpContentDispositionHeaderValue.TryParse(string input, out HttpContentDispositionHeaderValue contentDispositionHeaderValue) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20HttpContentDispositionHeaderValue.TryParse%28string%20input%2C%20out%20HttpContentDispositionHeaderValue%20contentDispositionHeaderValue%29");
}
#endif
}
}
| HttpContentDispositionHeaderValue |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.Tests/Bugs/Issue4060.cs | {
"start": 258,
"end": 3746
} | public class ____
{
[Fact]
public async Task VariableModification_ShouldReflectInSecondField()
{
var query = new ObjectGraphType();
query.Field<StringGraphType>("modifyVar")
.Resolve(context =>
{
context.Variables.Find("inputVar")!.Value = "modifiedValue";
return "Variable modified";
});
query.Field<StringGraphType>("retrieveVar")
.Argument<StringGraphType>("varArg")
.Resolve(context => context.GetArgument<string>("varArg"));
var schema = new Schema { Query = query };
var options = new ExecutionOptions
{
Schema = schema,
Query = """
query ($inputVar: String = "originalValue") {
modifyVar
retrieveVar(varArg: $inputVar)
}
""",
Variables = new Inputs(new Dictionary<string, object?>
{
{ "inputVar", "originalValue" }
}),
ValidationRules = DocumentValidator.CoreRules.Append(new FieldMappingValidationRule()),
};
options.Listeners.Add(new DynamicVariableExecutionListener());
var result = await new DocumentExecuter().ExecuteAsync(options);
var resultJson = new GraphQLSerializer().Serialize(result);
resultJson.ShouldBeCrossPlatJson("""
{
"data": {
"modifyVar": "Variable modified",
"retrieveVar": "modifiedValue"
}
}
""");
}
[Fact]
public async Task SampleCodeWorksWhenMergingSelectionSets()
{
var heroType = new ObjectGraphType() { Name = "Hero" };
heroType.Field<IntGraphType>("id");
heroType.Field<StringGraphType>("name");
var query = new ObjectGraphType() { Name = "Query" };
query.Field("hero", heroType)
.Argument<IntGraphType>("id")
.Resolve(context => new { id = context.GetArgument<int>("id"), name = "John Doe" });
var schema = new Schema { Query = query };
schema.Initialize();
var options = new ExecutionOptions
{
Schema = schema,
Query = """
query heroQuery($id: Int!) {
...fragment1
...fragment2
}
fragment fragment1 on Query {
hero(id: $id) {
id
}
}
fragment fragment2 on Query {
hero(id: $id) {
name
}
}
""",
Variables = new Inputs(new Dictionary<string, object?>
{
{ "id", 123 }
}),
ValidationRules = DocumentValidator.CoreRules.Append(new FieldMappingValidationRule()),
};
options.Listeners.Add(new DynamicVariableExecutionListener());
var result = await new DocumentExecuter().ExecuteAsync(options);
var resultJson = new GraphQLSerializer().Serialize(result);
resultJson.ShouldBeCrossPlatJson("""
{
"data": {
"hero": {
"id": 123,
"name": "John Doe"
}
}
}
""");
}
| Issue4060 |
csharp | dotnet__aspnetcore | src/Components/Web/src/WebEventData/FocusEventArgsReader.cs | {
"start": 229,
"end": 866
} | internal static class ____
{
private static readonly JsonEncodedText Type = JsonEncodedText.Encode("type");
internal static FocusEventArgs Read(JsonElement jsonElement)
{
var eventArgs = new FocusEventArgs();
foreach (var property in jsonElement.EnumerateObject())
{
if (property.NameEquals(Type.EncodedUtf8Bytes))
{
eventArgs.Type = property.Value.GetString()!;
}
else
{
throw new JsonException($"Unknown property {property.Name}");
}
}
return eventArgs;
}
}
| FocusEventArgsReader |
csharp | dotnet__aspnetcore | src/Servers/IIS/IIS/test/Common.FunctionalTests/Infrastructure/PublishedSitesFixture.cs | {
"start": 459,
"end": 657
} | public class ____ : ICollectionFixture<PublishedSitesFixture>, ICollectionFixture<ClientCertificateFixture>
{
public const string Name = nameof(PublishedSitesCollection);
}
| PublishedSitesCollection |
csharp | dotnet__BenchmarkDotNet | tests/BenchmarkDotNet.Tests/Builders/HostEnvironmentInfoBuilder.cs | {
"start": 2552,
"end": 3931
} | internal class ____ : HostEnvironmentInfo
{
public MockHostEnvironmentInfo(
string architecture, string benchmarkDotNetVersion, Frequency chronometerFrequency, string configuration, string dotNetSdkVersion,
HardwareTimerKind hardwareTimerKind, bool hasAttachedDebugger, bool hasRyuJit, bool isConcurrentGC, bool isServerGC,
string jitInfo, string jitModules, OsInfo os, CpuInfo cpu,
string runtimeVersion, VirtualMachineHypervisor virtualMachineHypervisor)
{
Architecture = architecture;
BenchmarkDotNetVersion = benchmarkDotNetVersion;
ChronometerFrequency = chronometerFrequency;
Configuration = configuration;
DotNetSdkVersion = new Lazy<string>(() => dotNetSdkVersion);
HardwareTimerKind = hardwareTimerKind;
HasAttachedDebugger = hasAttachedDebugger;
HasRyuJit = hasRyuJit;
IsConcurrentGC = isConcurrentGC;
IsServerGC = isServerGC;
JitInfo = jitInfo;
HardwareIntrinsicsShort = "";
Os = new Lazy<OsInfo>(() => os);
Cpu = new Lazy<CpuInfo>(() => cpu);
RuntimeVersion = runtimeVersion;
VirtualMachineHypervisor = new Lazy<VirtualMachineHypervisor>(() => virtualMachineHypervisor);
}
}
} | MockHostEnvironmentInfo |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs | {
"start": 19034,
"end": 19622
} | internal class ____ : XObjectWrapper
{
private XProcessingInstruction ProcessingInstruction => (XProcessingInstruction)WrappedNode!;
public XProcessingInstructionWrapper(XProcessingInstruction processingInstruction)
: base(processingInstruction)
{
}
public override string? LocalName => ProcessingInstruction.Target;
public override string? Value
{
get => ProcessingInstruction.Data;
set => ProcessingInstruction.Data = value ?? string.Empty;
}
}
| XProcessingInstructionWrapper |
csharp | MonoGame__MonoGame | MonoGame.Framework/GamePlatform.cs | {
"start": 367,
"end": 9295
} | partial class ____ : IDisposable
{
#region Fields
protected TimeSpan _inactiveSleepTime = TimeSpan.FromMilliseconds(20.0);
protected bool _needsToResetElapsedTime = false;
bool disposed;
protected bool InFullScreenMode = false;
protected bool IsDisposed { get { return disposed; } }
#endregion
#region Construction/Destruction
protected GamePlatform(Game game)
{
if (game == null)
throw new ArgumentNullException("game");
Game = game;
}
~GamePlatform()
{
Dispose(false);
}
#endregion Construction/Destruction
#region Public Properties
/// <summary>
/// When implemented in a derived class, reports the default
/// GameRunBehavior for this platform.
/// </summary>
public abstract GameRunBehavior DefaultRunBehavior { get; }
/// <summary>
/// Gets the Game instance that owns this GamePlatform instance.
/// </summary>
public Game Game
{
get; private set;
}
private bool _isActive;
public bool IsActive
{
get { return _isActive; }
internal set
{
if (_isActive != value)
{
_isActive = value;
EventHelpers.Raise(this, _isActive ? Activated : Deactivated, EventArgs.Empty);
}
}
}
private bool _isMouseVisible;
public bool IsMouseVisible
{
get { return _isMouseVisible; }
set
{
if (_isMouseVisible != value)
{
_isMouseVisible = value;
OnIsMouseVisibleChanged();
}
}
}
private GameWindow _window;
public GameWindow Window
{
get { return _window; }
protected set
{
if (_window == null)
{
Mouse.PrimaryWindow = value;
TouchPanel.PrimaryWindow = value;
}
_window = value;
}
}
#endregion
#region Events
public event EventHandler<EventArgs> AsyncRunLoopEnded;
public event EventHandler<EventArgs> Activated;
public event EventHandler<EventArgs> Deactivated;
/// <summary>
/// Raises the AsyncRunLoopEnded event. This method must be called by
/// derived classes when the asynchronous run loop they start has
/// stopped running.
/// </summary>
protected void RaiseAsyncRunLoopEnded()
{
EventHelpers.Raise(this, AsyncRunLoopEnded, EventArgs.Empty);
}
#endregion Events
#region Methods
/// <summary>
/// Gives derived classes an opportunity to do work before any
/// components are initialized. Note that the base implementation sets
/// IsActive to true, so derived classes should either call the base
/// implementation or set IsActive to true by their own means.
/// </summary>
public virtual void BeforeInitialize()
{
IsActive = true;
}
/// <summary>
/// Gives derived classes an opportunity to do work just before the
/// run loop is begun. Implementations may also return false to prevent
/// the run loop from starting.
/// </summary>
/// <returns></returns>
public virtual bool BeforeRun()
{
return true;
}
/// <summary>
/// When implemented in a derived, ends the active run loop.
/// </summary>
public abstract void Exit();
/// <summary>
/// When implemented in a derived, starts the run loop and blocks
/// until it has ended.
/// </summary>
public abstract void RunLoop();
/// <summary>
/// When implemented in a derived, starts the run loop and returns
/// immediately.
/// </summary>
public abstract void StartRunLoop();
/// <summary>
/// Gives derived classes an opportunity to do work just before Update
/// is called for all IUpdatable components. Returning false from this
/// method will result in this round of Update calls being skipped.
/// </summary>
/// <param name="gameTime"></param>
/// <returns></returns>
public abstract bool BeforeUpdate(GameTime gameTime);
/// <summary>
/// Gives derived classes an opportunity to do work just before Draw
/// is called for all IDrawable components. Returning false from this
/// method will result in this round of Draw calls being skipped.
/// </summary>
/// <param name="gameTime"></param>
/// <returns></returns>
public abstract bool BeforeDraw(GameTime gameTime);
/// <summary>
/// When implemented in a derived class, causes the game to enter
/// full-screen mode.
/// </summary>
public abstract void EnterFullScreen();
/// <summary>
/// When implemented in a derived class, causes the game to exit
/// full-screen mode.
/// </summary>
public abstract void ExitFullScreen();
/// <summary>
/// Gives derived classes an opportunity to modify
/// Game.TargetElapsedTime before it is set.
/// </summary>
/// <param name="value">The proposed new value of TargetElapsedTime.</param>
/// <returns>The new value of TargetElapsedTime that will be set.</returns>
public virtual TimeSpan TargetElapsedTimeChanging(TimeSpan value)
{
return value;
}
/// <summary>
/// Starts a device transition (windowed to full screen or vice versa).
/// </summary>
/// <param name='willBeFullScreen'>
/// Specifies whether the device will be in full-screen mode upon completion of the change.
/// </param>
public abstract void BeginScreenDeviceChange (
bool willBeFullScreen
);
/// <summary>
/// Completes a device transition.
/// </summary>
/// <param name='screenDeviceName'>
/// Screen device name.
/// </param>
/// <param name='clientWidth'>
/// The new width of the game's client window.
/// </param>
/// <param name='clientHeight'>
/// The new height of the game's client window.
/// </param>
public abstract void EndScreenDeviceChange (
string screenDeviceName,
int clientWidth,
int clientHeight
);
/// <summary>
/// Gives derived classes an opportunity to take action after
/// Game.TargetElapsedTime has been set.
/// </summary>
public virtual void TargetElapsedTimeChanged() {}
/// <summary>
/// MSDN: Use this method if your game is recovering from a slow-running state, and ElapsedGameTime is too large to be useful.
/// Frame timing is generally handled by the Game class, but some platforms still handle it elsewhere. Once all platforms
/// rely on the Game class's functionality, this method and any overrides should be removed.
/// </summary>
public virtual void ResetElapsedTime() {}
public virtual void Present() { }
protected virtual void OnIsMouseVisibleChanged() {}
/// <summary>
/// Called by the GraphicsDeviceManager to notify the platform
/// that the presentation parameters have changed.
/// </summary>
/// <param name="pp">The new presentation parameters.</param>
internal virtual void OnPresentationChanged(PresentationParameters pp)
{
}
#endregion Methods
#region IDisposable implementation
/// <summary>
/// Performs application-defined tasks associated with freeing,
/// releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
Mouse.PrimaryWindow = null;
TouchPanel.PrimaryWindow = null;
disposed = true;
}
}
/// <summary>
/// Log the specified Message.
/// </summary>
/// <param name='Message'>
///
/// </param>
[System.Diagnostics.Conditional("DEBUG")]
public virtual void Log(string Message) {}
#endregion
}
}
| GamePlatform |
csharp | microsoft__PowerToys | src/modules/cmdpal/extensionsdk/Microsoft.CommandPalette.Extensions.Toolkit/ExtensionInstanceManager`1.cs | {
"start": 4188,
"end": 4437
} | internal partial interface ____
{
void CreateInstance(
[MarshalAs(UnmanagedType.Interface)] object pUnkOuter,
Guid riid,
out IntPtr ppvObject);
void LockServer([MarshalAs(UnmanagedType.Bool)] bool fLock);
}
| IClassFactory |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.Abstractions/Caching/Distributed/IMessageBus.cs | {
"start": 44,
"end": 205
} | public interface ____
{
Task SubscribeAsync(string channel, Action<string, string> handler);
Task PublishAsync(string channel, string message);
}
| IMessageBus |
csharp | dotnet__aspnetcore | src/Mvc/test/WebSites/BasicWebSite/Controllers/ContentNegotiation/ContentNegotiationController.cs | {
"start": 254,
"end": 879
} | public class ____ : Controller
{
public IActionResult Index()
{
return new JsonResult("Index Method");
}
public User UserInfo()
{
return CreateUser();
}
[Produces<User>]
public IActionResult UserInfo_ProducesWithTypeOnly()
{
return new ObjectResult(CreateUser());
}
[Produces<User>]
public IActionResult UserInfo_ProducesWithTypeAndContentType()
{
return new ObjectResult(CreateUser());
}
private User CreateUser()
{
return new User() { Name = "John", Address = "One Microsoft Way" };
}
}
| ContentNegotiationController |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Data/src/Data/Sorting/Convention/SortOperationConventionConfiguration.cs | {
"start": 38,
"end": 209
} | public class ____
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Description { get; set; }
}
| SortOperationConventionConfiguration |
csharp | MassTransit__MassTransit | src/MassTransit/Configuration/ITransactionConfigurator.cs | {
"start": 80,
"end": 405
} | public interface ____
{
/// <summary>
/// Sets the transaction timeout
/// </summary>
TimeSpan Timeout { set; }
/// <summary>
/// Sets the isolation level of the transaction
/// </summary>
IsolationLevel IsolationLevel { set; }
}
}
| ITransactionConfigurator |
csharp | CommunityToolkit__WindowsCommunityToolkit | Microsoft.Toolkit.Uwp.UI.Controls.Layout/BladeView/BladeItem.cs | {
"start": 668,
"end": 3945
} | public partial class ____ : Expander
{
private Button _closeButton;
private Button _enlargeButton;
private double _normalModeWidth;
private bool _loaded = false;
/// <summary>
/// Initializes a new instance of the <see cref="BladeItem"/> class.
/// </summary>
public BladeItem()
{
DefaultStyleKey = typeof(BladeItem);
SizeChanged += OnSizeChanged;
}
/// <summary>
/// Override default OnApplyTemplate to capture child controls
/// </summary>
protected override void OnApplyTemplate()
{
_loaded = true;
base.OnApplyTemplate();
_closeButton = GetTemplateChild("CloseButton") as Button;
_enlargeButton = GetTemplateChild("EnlargeButton") as Button;
if (_closeButton == null)
{
return;
}
_closeButton.Click -= CloseButton_Click;
_closeButton.Click += CloseButton_Click;
if (_enlargeButton == null)
{
return;
}
_enlargeButton.Click -= EnlargeButton_Click;
_enlargeButton.Click += EnlargeButton_Click;
}
/// <inheritdoc/>
protected override void OnExpanded(EventArgs args)
{
base.OnExpanded(args);
if (_loaded)
{
Width = _normalModeWidth;
VisualStateManager.GoToState(this, "Expanded", true);
var name = "WCT_BladeView_ExpandButton_Collapsed".GetLocalized("Microsoft.Toolkit.Uwp.UI.Controls.Layout/Resources");
if (_enlargeButton != null)
{
AutomationProperties.SetName(_enlargeButton, name);
}
}
}
/// <inheritdoc/>
protected override void OnCollapsed(EventArgs args)
{
base.OnCollapsed(args);
if (_loaded)
{
Width = double.NaN;
VisualStateManager.GoToState(this, "Collapsed", true);
var name = "WCT_BladeView_ExpandButton_Expanded".GetLocalized("Microsoft.Toolkit.Uwp.UI.Controls.Layout/Resources");
if (_enlargeButton != null)
{
AutomationProperties.SetName(_enlargeButton, name);
}
}
}
/// <summary>
/// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>)
/// </summary>
/// <returns>An automation peer for this <see cref="BladeItem"/>.</returns>
protected override AutomationPeer OnCreateAutomationPeer()
{
return new BladeItemAutomationPeer(this);
}
private void OnSizeChanged(object sender, SizeChangedEventArgs sizeChangedEventArgs)
{
if (IsExpanded)
{
_normalModeWidth = Width;
}
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
IsOpen = false;
}
private void EnlargeButton_Click(object sender, RoutedEventArgs e)
{
IsExpanded = !IsExpanded;
}
}
} | BladeItem |
csharp | AutoMapper__AutoMapper | src/UnitTests/MappingInheritance/PropertyOnMappingShouldResolveMostSpecificType.cs | {
"start": 239,
"end": 282
} | public class ____ :ItemBase{}
| SpecificItem |
csharp | moq__moq4 | src/Moq.Tests/Regressions/IssueReportsFixture.cs | {
"start": 154630,
"end": 154804
} | public class ____
{
[Fact]
public void Test()
{
new Mock<IFoo>().SetupAllProperties();
}
| _205 |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 4575643,
"end": 4576634
} | public partial class ____ : global::StrawberryShake.IOperationResultDataInfo
{
public ShowWorkspaceCommandQueryResultInfo(global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.INodeData? node)
{
Node = node;
}
/// <summary>
/// Fetches an object given its ID.
/// </summary>
public global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.INodeData? Node { get; }
public global::System.Collections.Generic.IReadOnlyCollection<global::StrawberryShake.EntityId> EntityIds => global::System.Array.Empty<global::StrawberryShake.EntityId>();
public global::System.UInt64 Version => 0;
public global::StrawberryShake.IOperationResultDataInfo WithVersion(global::System.UInt64 version)
{
return new ShowWorkspaceCommandQueryResultInfo(Node);
}
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| ShowWorkspaceCommandQueryResultInfo |
csharp | dotnet__aspnetcore | src/Components/Web/src/Forms/ValidationMessage.cs | {
"start": 408,
"end": 3675
} | public class ____<TValue> : ComponentBase, IDisposable
{
private EditContext? _previousEditContext;
private Expression<Func<TValue>>? _previousFieldAccessor;
private readonly EventHandler<ValidationStateChangedEventArgs>? _validationStateChangedHandler;
private FieldIdentifier _fieldIdentifier;
/// <summary>
/// Gets or sets a collection of additional attributes that will be applied to the created <c>div</c> element.
/// </summary>
[Parameter(CaptureUnmatchedValues = true)] public IReadOnlyDictionary<string, object>? AdditionalAttributes { get; set; }
[CascadingParameter] EditContext CurrentEditContext { get; set; } = default!;
/// <summary>
/// Specifies the field for which validation messages should be displayed.
/// </summary>
[Parameter] public Expression<Func<TValue>>? For { get; set; }
/// <summary>`
/// Constructs an instance of <see cref="ValidationMessage{TValue}"/>.
/// </summary>
public ValidationMessage()
{
_validationStateChangedHandler = (sender, eventArgs) => StateHasChanged();
}
/// <inheritdoc />
protected override void OnParametersSet()
{
if (CurrentEditContext == null)
{
throw new InvalidOperationException($"{GetType()} requires a cascading parameter " +
$"of type {nameof(EditContext)}. For example, you can use {GetType()} inside " +
$"an {nameof(EditForm)}.");
}
if (For == null) // Not possible except if you manually specify T
{
throw new InvalidOperationException($"{GetType()} requires a value for the " +
$"{nameof(For)} parameter.");
}
else if (For != _previousFieldAccessor)
{
_fieldIdentifier = FieldIdentifier.Create(For);
_previousFieldAccessor = For;
}
if (CurrentEditContext != _previousEditContext)
{
DetachValidationStateChangedListener();
CurrentEditContext.OnValidationStateChanged += _validationStateChangedHandler;
_previousEditContext = CurrentEditContext;
}
}
/// <inheritdoc />
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
foreach (var message in CurrentEditContext.GetValidationMessages(_fieldIdentifier))
{
builder.OpenElement(0, "div");
builder.AddAttribute(1, "class", "validation-message");
builder.AddMultipleAttributes(2, AdditionalAttributes);
builder.AddContent(3, message);
builder.CloseElement();
}
}
/// <summary>
/// Called to dispose this instance.
/// </summary>
/// <param name="disposing"><see langword="true"/> if called within <see cref="IDisposable.Dispose"/>.</param>
protected virtual void Dispose(bool disposing)
{
}
void IDisposable.Dispose()
{
DetachValidationStateChangedListener();
Dispose(disposing: true);
}
private void DetachValidationStateChangedListener()
{
if (_previousEditContext != null)
{
_previousEditContext.OnValidationStateChanged -= _validationStateChangedHandler;
}
}
}
| ValidationMessage |
csharp | unoplatform__uno | src/SourceGenerators/System.Xaml.Tests/Test/System.Xaml/TestedTypes.cs | {
"start": 11086,
"end": 11417
} | public class ____
{
public NamedItem2 ()
{
References = new List<NamedItem2> ();
}
public NamedItem2 (string name)
: this ()
{
ItemName = name;
}
public string ItemName { get; set; }
public IList<NamedItem2> References { get; private set; }
}
[TypeConverter (typeof (TestValueConverter))]
| NamedItem2 |
csharp | LibreHardwareMonitor__LibreHardwareMonitor | LibreHardwareMonitorLib/Hardware/Psu/Msi/MsiPsu.cs | {
"start": 2711,
"end": 3254
} | private class ____ : Sensor
{
private readonly UsbApi.IndexInfo _indexInfo;
public PsuSensor(string name, int index, SensorType type, MsiPsu hardware, ISettings settings, UsbApi.IndexInfo indexInfo, bool noHistory = false)
: base(name, index, false, type, hardware, null, settings, noHistory)
{
_indexInfo = indexInfo;
hardware.ActivateSensor(this);
}
public void Update(float[] info)
{
Value = info[(int)_indexInfo];
}
}
}
| PsuSensor |
csharp | dotnet__aspnetcore | src/Components/Analyzers/test/SupplyParameterFromFormAnalyzerTest.cs | {
"start": 867,
"end": 1135
} | public class ____ : System.Attribute
{{
public string Name {{ get; set; }}
public string FormName {{ get; set; }}
}}
public interface {typeof(IComponent).Name}
{{
}}
| SupplyParameterFromFormAttribute |
csharp | dotnet__aspnetcore | src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/Internal/KeyManagementOptionsSetupTest.cs | {
"start": 584,
"end": 4583
} | public class ____
{
[Fact]
public void Configure_SetsExpectedValues()
{
// Arrange
var setup = new KeyManagementOptionsSetup(NullLoggerFactory.Instance);
var options = new KeyManagementOptions()
{
AuthenticatedEncryptorConfiguration = null
};
// Act
setup.Configure(options);
// Assert
Assert.Empty(options.KeyEscrowSinks);
Assert.NotNull(options.AuthenticatedEncryptorConfiguration);
Assert.IsType<AuthenticatedEncryptorConfiguration>(options.AuthenticatedEncryptorConfiguration);
Assert.Collection(
options.AuthenticatedEncryptorFactories,
f => Assert.IsType<CngGcmAuthenticatedEncryptorFactory>(f),
f => Assert.IsType<CngCbcAuthenticatedEncryptorFactory>(f),
f => Assert.IsType<ManagedAuthenticatedEncryptorFactory>(f),
f => Assert.IsType<AuthenticatedEncryptorFactory>(f));
}
[ConditionalFact]
[ConditionalRunTestOnlyIfHkcuRegistryAvailable]
public void Configure_WithRegistryPolicyResolver_SetsValuesFromResolver()
{
// Arrange
var registryEntries = new Dictionary<string, object>()
{
["KeyEscrowSinks"] = String.Join(" ;; ; ", new Type[] { typeof(MyKeyEscrowSink1), typeof(MyKeyEscrowSink2) }.Select(t => t.AssemblyQualifiedName)),
["EncryptionType"] = "managed",
["DefaultKeyLifetime"] = 1024 // days
};
var options = new KeyManagementOptions()
{
AuthenticatedEncryptorConfiguration = null
};
// Act
RunTest(registryEntries, options);
// Assert
Assert.Collection(
options.KeyEscrowSinks,
k => Assert.IsType<MyKeyEscrowSink1>(k),
k => Assert.IsType<MyKeyEscrowSink2>(k));
Assert.Equal(TimeSpan.FromDays(1024), options.NewKeyLifetime);
Assert.NotNull(options.AuthenticatedEncryptorConfiguration);
Assert.IsType<ManagedAuthenticatedEncryptorConfiguration>(options.AuthenticatedEncryptorConfiguration);
Assert.Collection(
options.AuthenticatedEncryptorFactories,
f => Assert.IsType<CngGcmAuthenticatedEncryptorFactory>(f),
f => Assert.IsType<CngCbcAuthenticatedEncryptorFactory>(f),
f => Assert.IsType<ManagedAuthenticatedEncryptorFactory>(f),
f => Assert.IsType<AuthenticatedEncryptorFactory>(f));
}
private static void RunTest(Dictionary<string, object> regValues, KeyManagementOptions options)
{
WithUniqueTempRegKey(registryKey =>
{
foreach (var entry in regValues)
{
registryKey.SetValue(entry.Key, entry.Value);
}
var policyResolver = new RegistryPolicyResolver(
registryKey,
activator: SimpleActivator.DefaultWithoutServices);
var setup = new KeyManagementOptionsSetup(NullLoggerFactory.Instance, policyResolver);
setup.Configure(options);
});
}
/// <summary>
/// Runs a test and cleans up the registry key afterward.
/// </summary>
private static void WithUniqueTempRegKey(Action<RegistryKey> testCode)
{
string uniqueName = Guid.NewGuid().ToString();
var uniqueSubkey = LazyHkcuTempKey.Value.CreateSubKey(uniqueName);
try
{
testCode(uniqueSubkey);
}
finally
{
// clean up when test is done
LazyHkcuTempKey.Value.DeleteSubKeyTree(uniqueName, throwOnMissingSubKey: false);
}
}
private static readonly Lazy<RegistryKey> LazyHkcuTempKey = new Lazy<RegistryKey>(() =>
{
try
{
return Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\ASP.NET\temp");
}
catch
{
// swallow all failures
return null;
}
});
| KeyManagementOptionsSetupTest |
csharp | dotnet__extensions | src/Libraries/Microsoft.Extensions.AI.Evaluation.Quality/RelevanceTruthAndCompletenessEvaluator.cs | {
"start": 8587,
"end": 8852
} | record ____ value of "relevanceReasoning" as "100% of the response is 100% related to the request". If the score is not 5, write your Reasoning as fewer than 100 words and prioritizing the most important contributing reasons to the score.
Step 1c. Now, | the |
csharp | EventStore__EventStore | src/KurrentDB.Core/Messages/TcpMessage.cs | {
"start": 413,
"end": 803
} | public partial class ____ : Message {
public override TcpConnectionManager Affinity => ConnectionManager;
public readonly TcpConnectionManager ConnectionManager;
public readonly Message Message;
public TcpSend(TcpConnectionManager connectionManager, Message message) {
ConnectionManager = connectionManager;
Message = message;
}
}
[DerivedMessage(CoreMessage.Tcp)]
| TcpSend |
csharp | EventStore__EventStore | src/KurrentDB.Core/ClusterVNode.cs | {
"start": 3807,
"end": 6117
} | public abstract class ____ {
protected static readonly ILogger Log = Serilog.Log.ForContext<ClusterVNode>();
public static readonly TimeSpan ShutdownTimeout =
ClusterVNodeController.ShutdownTimeout + TimeSpan.FromSeconds(1);
public static ClusterVNode<TStreamId> Create<TStreamId>(
ClusterVNodeOptions options,
ILogFormatAbstractorFactory<TStreamId> logFormatAbstractorFactory,
AuthenticationProviderFactory authenticationProviderFactory = null,
AuthorizationProviderFactory authorizationProviderFactory = null,
VirtualStreamReader virtualStreamReader = null,
SecondaryIndexReaders secondaryIndexReaders = null,
IReadOnlyList<IPersistentSubscriptionConsumerStrategyFactory> factories = null,
CertificateProvider certificateProvider = null,
IConfiguration configuration = null,
Guid? instanceId = null,
int debugIndex = 0) {
return new ClusterVNode<TStreamId>(
options,
logFormatAbstractorFactory,
authenticationProviderFactory,
authorizationProviderFactory,
virtualStreamReader,
secondaryIndexReaders,
factories,
certificateProvider,
configuration,
instanceId: instanceId,
debugIndex: debugIndex);
}
abstract public TFChunkDb Db { get; }
abstract public GossipAdvertiseInfo GossipAdvertiseInfo { get; }
abstract public IPublisher MainQueue { get; }
abstract public ISubscriber MainBus { get; }
abstract public QueueStatsManager QueueStatsManager { get; }
abstract public IInternalStartup Startup { get; }
abstract public IAuthenticationProvider AuthenticationProvider { get; }
abstract public IHttpService HttpService { get; }
abstract public VNodeInfo NodeInfo { get; }
abstract public IReadIndex ReadIndex { get; }
abstract public CertificateDelegates.ClientCertificateValidator InternalClientCertificateValidator { get; }
abstract public Func<X509Certificate2> CertificateSelector { get; }
abstract public Func<X509Certificate2Collection> IntermediateCertificatesSelector { get; }
abstract public bool DisableHttps { get; }
abstract public bool EnableUnixSocket { get; }
abstract public bool IsShutdown { get; }
abstract public Task<ClusterVNode> StartAsync(bool waitUntilReady, CancellationToken token);
abstract public Task StopAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default);
}
| ClusterVNode |
csharp | xunit__xunit | src/xunit.v3.core.tests/Acceptance/Xunit3AcceptanceTests.cs | {
"start": 27465,
"end": 27730
} | class ____
{
[Fact]
public void Test1() { }
[Fact]
public void Test2() { }
}
[CollectionDefinition("Non-Parallel Collection", DisableParallelization = true)]
[TestCaseOrderer(typeof(TestOrdering.AlphabeticalOrderer))]
| TestClassParallelCollection |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.Analyzers.Tests/FieldNameAnalyzerTests.cs | {
"start": 19602,
"end": 20006
} | public class ____ : ObjectGraphType
{
public MyGraphType()
{
Field<string>(name: "Text1", nullable: true).{|#0:Name("Text2")|}.Resolve(context => "Test");
}
}
""";
const string fix0 =
"""
using GraphQL.Types;
namespace Sample.Server;
| MyGraphType |
csharp | nopSolutions__nopCommerce | src/Tests/Nop.Tests/Nop.Services.Tests/ScheduleTasks/ScheduleTaskTests.cs | {
"start": 170,
"end": 908
} | public class ____ : BaseNopTest
{
private IStaticCacheManager _staticCacheManager;
[OneTimeSetUp]
public void SetUp()
{
_staticCacheManager = GetService<IStaticCacheManager>();
}
[Test]
public async Task TestClearCacheTask()
{
var test = new ClearCacheTask(_staticCacheManager);
var key = new CacheKey("test_key_1") { CacheTime = 30 };
await _staticCacheManager.SetAsync(key, "test data");
var data = await _staticCacheManager.GetAsync(key, () => string.Empty);
data.Should().NotBeEmpty();
await test.ExecuteAsync();
data = await _staticCacheManager.GetAsync(key, () => string.Empty);
data.Should().BeEmpty();
}
} | ScheduleTaskTests |
csharp | dotnet__machinelearning | src/Microsoft.ML.FastTree/Training/EarlyStoppingCriteria.cs | {
"start": 3637,
"end": 3846
} | internal interface ____ : IComponentFactory<bool, EarlyStoppingRuleBase>
{
new EarlyStoppingRuleBase CreateComponent(IHostEnvironment env, bool lowerIsBetter);
}
| IEarlyStoppingCriterionFactory |
csharp | moq__moq4 | src/Moq/Language/Flow/ISetup.cs | {
"start": 638,
"end": 934
} | public interface ____<TMock, TResult> : ICallback<TMock, TResult>, IReturnsThrows<TMock, TResult>, IVerifies, IFluentInterface
where TMock : class
{
}
/// <summary>
/// Implements the fluent API.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
| ISetup |
csharp | kgrzybek__modular-monolith-with-ddd | src/Modules/Meetings/Domain/Meetings/Rules/AttendeeCanBeAddedOnlyInRsvpTermRule.cs | {
"start": 199,
"end": 593
} | public class ____ : IBusinessRule
{
private readonly Term _rsvpTerm;
internal AttendeeCanBeAddedOnlyInRsvpTermRule(Term rsvpTerm)
{
_rsvpTerm = rsvpTerm;
}
public bool IsBroken() => !_rsvpTerm.IsInTerm(SystemClock.Now);
public string Message => "Attendee can be added only in RSVP term";
}
} | AttendeeCanBeAddedOnlyInRsvpTermRule |
csharp | microsoft__semantic-kernel | dotnet/test/VectorData/Weaviate.ConformanceTests/ModelTests/WeaviateBasicModelTests.cs | {
"start": 835,
"end": 984
} | class ____ : BasicModelTests<Guid>.Fixture
{
public override TestStore TestStore => WeaviateTestStore.UnnamedVectorInstance;
}
}
| Fixture |
csharp | jellyfin__jellyfin | src/Jellyfin.Networking/Manager/NetworkManager.cs | {
"start": 35487,
"end": 35668
} | interface ____ matching subnet, using it as bind address: {Result}", source, result);
return result;
}
}
// Fallback to first available | with |
csharp | unoplatform__uno | src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/ImageTests/Image_Stretch_Full_Taller.xaml.cs | {
"start": 627,
"end": 766
} | partial class ____ : UserControl
{
public Image_Stretch_Full_Taller()
{
this.InitializeComponent();
}
}
}
| Image_Stretch_Full_Taller |
csharp | simplcommerce__SimplCommerce | src/SimplCommerce.Infrastructure/Data/ICustomModelBuilder.cs | {
"start": 89,
"end": 187
} | public interface ____
{
void Build(ModelBuilder modelBuilder);
}
}
| ICustomModelBuilder |
csharp | MassTransit__MassTransit | src/Persistence/MassTransit.MongoDbIntegration/MongoDbIntegration/Courier/Consumers/RoutingSlipActivityFaultedConsumer.cs | {
"start": 161,
"end": 735
} | public class ____ :
IConsumer<RoutingSlipActivityFaulted>
{
readonly IRoutingSlipEventPersister _persister;
public RoutingSlipActivityFaultedConsumer(IRoutingSlipEventPersister persister)
{
_persister = persister;
}
public Task Consume(ConsumeContext<RoutingSlipActivityFaulted> context)
{
var @event = new RoutingSlipActivityFaultedDocument(context.Message);
return _persister.Persist(context.Message.TrackingNumber, @event);
}
}
}
| RoutingSlipActivityFaultedConsumer |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/Serialization/JsonSerialization_Specs.cs | {
"start": 10718,
"end": 11158
} | class ____
{
public Envelope()
{
Headers = new Dictionary<string, string>();
MessageType = new List<string>();
}
public IDictionary<string, string> Headers { get; set; }
public object Message { get; set; }
public IList<string> MessageType { get; set; }
public BusHostInfo Host { get; set; }
}
| Envelope |
csharp | serilog__serilog-sinks-file | src/Serilog.Sinks.File/Sinks/File/SharedFileSink.AtomicAppend.cs | {
"start": 993,
"end": 7488
} | public sealed class ____ : IFileSink, IDisposable, ISetLoggingFailureListener
{
readonly MemoryStream _writeBuffer;
readonly string _path;
readonly TextWriter _output;
readonly ITextFormatter _textFormatter;
readonly long? _fileSizeLimitBytes;
readonly object _syncRoot = new();
ILoggingFailureListener _failureListener = SelfLog.FailureListener;
// The stream is reopened with a larger buffer if atomic writes beyond the current buffer size are needed.
FileStream _fileOutput;
int _fileStreamBufferLength = DefaultFileStreamBufferLength;
const int DefaultFileStreamBufferLength = 4096;
/// <summary>Construct a <see cref="FileSink"/>.</summary>
/// <param name="path">Path to the file.</param>
/// <param name="textFormatter">Formatter used to convert log events to text.</param>
/// <param name="fileSizeLimitBytes">The approximate maximum size, in bytes, to which a log file will be allowed to grow.
/// For unrestricted growth, pass null. The default is 1 GB. To avoid writing partial events, the last event within the limit
/// will be written in full even if it exceeds the limit.</param>
/// <param name="encoding">Character encoding used to write the text file. The default is UTF-8 without BOM.</param>
/// <returns>Configuration object allowing method chaining.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="path"/> is <code>null</code></exception>
/// <exception cref="ArgumentNullException">When <paramref name="textFormatter"/> is <code>null</code></exception>
/// <exception cref="IOException"></exception>
/// <exception cref="InvalidOperationException"></exception>
/// <exception cref="NotSupportedException"></exception>
/// <exception cref="PathTooLongException">When <paramref name="path"/> is too long</exception>
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission to access the <paramref name="path"/></exception>
/// <exception cref="ArgumentException">Invalid <paramref name="path"/></exception>
public SharedFileSink(string path, ITextFormatter textFormatter, long? fileSizeLimitBytes, Encoding? encoding = null)
{
if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 1)
throw new ArgumentException("Invalid value provided; file size limit must be at least 1 byte, or null.");
_path = path ?? throw new ArgumentNullException(nameof(path));
_textFormatter = textFormatter ?? throw new ArgumentNullException(nameof(textFormatter));
_fileSizeLimitBytes = fileSizeLimitBytes;
var directory = Path.GetDirectoryName(path);
if (!string.IsNullOrWhiteSpace(directory) && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
// FileSystemRights.AppendData sets the Win32 FILE_APPEND_DATA flag. On Linux this is O_APPEND, but that API is not yet
// exposed by .NET Core.
_fileOutput = new FileStream(
path,
FileMode.Append,
FileSystemRights.AppendData,
FileShare.ReadWrite,
_fileStreamBufferLength,
FileOptions.None);
_writeBuffer = new MemoryStream();
_output = new StreamWriter(_writeBuffer,
encoding ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
}
bool IFileSink.EmitOrOverflow(LogEvent logEvent)
{
if (logEvent == null) throw new ArgumentNullException(nameof(logEvent));
lock (_syncRoot)
{
try
{
_textFormatter.Format(logEvent, _output);
_output.Flush();
var bytes = _writeBuffer.GetBuffer();
var length = (int) _writeBuffer.Length;
if (length > _fileStreamBufferLength)
{
var oldOutput = _fileOutput;
_fileOutput = new FileStream(
_path,
FileMode.Append,
FileSystemRights.AppendData,
FileShare.ReadWrite,
length,
FileOptions.None);
_fileStreamBufferLength = length;
oldOutput.Dispose();
}
if (_fileSizeLimitBytes != null)
{
try
{
if (_fileOutput.Length >= _fileSizeLimitBytes.Value)
return false;
}
catch (FileNotFoundException) { } // Cheaper and more reliable than checking existence
}
_fileOutput.Write(bytes, 0, length);
_fileOutput.Flush();
return true;
}
catch
{
// Make sure there's no leftover cruft in there.
_output.Flush();
throw;
}
finally
{
_writeBuffer.Position = 0;
_writeBuffer.SetLength(0);
}
}
}
/// <summary>
/// Emit the provided log event to the sink.
/// </summary>
/// <param name="logEvent">The log event to write.</param>
/// <exception cref="ArgumentNullException">When <paramref name="logEvent"/> is <code>null</code></exception>
public void Emit(LogEvent logEvent)
{
if (!((IFileSink)this).EmitOrOverflow(logEvent))
{
// Support fallback chains without the overhead of throwing an exception.
_failureListener.OnLoggingFailed(
this,
LoggingFailureKind.Permanent,
"the log file size limit has been reached and no rolling behavior was specified",
[logEvent],
exception: null);
}
}
/// <inheritdoc />
public void Dispose()
{
lock (_syncRoot)
{
_fileOutput.Dispose();
}
}
/// <inheritdoc />
public void FlushToDisk()
{
lock (_syncRoot)
{
_output.Flush();
_fileOutput.Flush(true);
}
}
void ISetLoggingFailureListener.SetFailureListener(ILoggingFailureListener failureListener)
{
_failureListener = failureListener ?? throw new ArgumentNullException(nameof(failureListener));
}
}
#endif
| SharedFileSink |
csharp | AvaloniaUI__Avalonia | tests/Avalonia.Markup.Xaml.UnitTests/MarkupExtensions/OptionsMarkupExtensionTests.cs | {
"start": 21460,
"end": 21618
} | public class ____
{
public string Name { get; set; }
public ChildObject()
{
OptionsMarkupExtensionTests.ObjectsCreated++;
}
}
| ChildObject |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/src/Types.Queries/QueryConventionTypeInterceptor.cs | {
"start": 135,
"end": 10354
} | internal sealed class ____ : TypeInterceptor
{
private readonly ErrorTypeHelper _errorTypeHelper = new();
private readonly StringBuilder _sb = new();
private readonly List<ObjectTypeConfiguration> _typeDefs = [];
private TypeInitializer _typeInitializer = null!;
private TypeRegistry _typeRegistry = null!;
private IDescriptorContext _context = null!;
private ObjectTypeConfiguration _mutationDef = null!;
internal override void InitializeContext(
IDescriptorContext context,
TypeInitializer typeInitializer,
TypeRegistry typeRegistry,
TypeLookup typeLookup,
TypeReferenceResolver typeReferenceResolver)
{
_context = context;
_typeInitializer = typeInitializer;
_typeRegistry = typeRegistry;
_errorTypeHelper.InitializerErrorTypeInterface(_context);
}
public override void OnAfterResolveRootType(
ITypeCompletionContext completionContext,
ObjectTypeConfiguration configuration,
OperationType operationType)
{
if (operationType is OperationType.Mutation)
{
_mutationDef = configuration;
}
}
public override void OnAfterCompleteName(
ITypeCompletionContext completionContext,
TypeSystemConfiguration configuration)
{
if (completionContext.Type is ObjectType && configuration is ObjectTypeConfiguration typeDef)
{
_typeDefs.Add(typeDef);
}
base.OnAfterCompleteName(completionContext, configuration);
}
public override void OnBeforeCompleteTypes()
{
var errorInterfaceTypeRef = _errorTypeHelper.ErrorTypeInterfaceRef;
var errorInterfaceIsRegistered = false;
List<TypeReference>? typeSet = null;
foreach (var typeDef in _typeDefs.ToArray())
{
if (_mutationDef == typeDef)
{
continue;
}
foreach (var field in typeDef.Fields)
{
if (field.IsIntrospectionField)
{
continue;
}
typeSet?.Clear();
if (field.ResultType != null
&& typeof(IFieldResult).IsAssignableFrom(field.ResultType)
&& _context.TryInferSchemaType(
_context.TypeInspector.GetOutputTypeRef(field.ResultType),
out var schemaTypeRefs))
{
foreach (var errorTypeRef in schemaTypeRefs.Skip(1))
{
(typeSet ??= []).Add(errorTypeRef);
if (_typeRegistry.TryGetType(errorTypeRef, out var errorType))
{
((ObjectType)errorType.Type).Configuration!.Interfaces.Add(errorInterfaceTypeRef);
}
}
}
// collect error definitions from query field.
var errorDefinitions = _errorTypeHelper.GetErrorConfigurations(field);
// collect error factories for middleware
var errorFactories = errorDefinitions.Count != 0
? errorDefinitions.Select(t => t.Factory).ToArray()
: [];
if (errorDefinitions.Count > 0)
{
foreach (var errorDef in errorDefinitions)
{
var obj = TryRegisterType(errorDef.SchemaType);
if (obj is not null)
{
_typeRegistry.Register(obj);
var errorTypeRef = TypeReference.Create(obj.Type);
RegisterErrorType(errorTypeRef, errorDef.SchemaType);
RegisterErrorType(errorTypeRef, errorDef.RuntimeType);
((ObjectType)obj.Type).Configuration!.Interfaces.Add(errorInterfaceTypeRef);
}
var errorSchemaTypeRef = _context.TypeInspector.GetOutputTypeRef(errorDef.SchemaType);
if (obj is null && _typeRegistry.TryGetType(errorSchemaTypeRef, out obj))
{
((ObjectType)obj.Type).Configuration!.Interfaces.Add(errorInterfaceTypeRef);
}
(typeSet ??= []).Add(errorSchemaTypeRef);
}
}
if (!errorInterfaceIsRegistered && !_typeRegistry.TryGetTypeRef(errorInterfaceTypeRef, out _))
{
var err = TryRegisterType(errorInterfaceTypeRef.Type.Type);
if (err is not null)
{
err.References.Add(errorInterfaceTypeRef);
_typeRegistry.Register(err);
_typeRegistry.TryRegister(errorInterfaceTypeRef, TypeReference.Create(err.Type));
}
errorInterfaceIsRegistered = true;
}
if (typeSet?.Count > 0)
{
typeSet.Insert(0, GetFieldType(field.Type!));
field.Type = CreateFieldResultType(field.Name, typeSet);
typeDef.Dependencies.Add(new TypeDependency(field.Type, Completed));
// create middleware
var errorMiddleware =
new FieldMiddlewareConfiguration(
FieldClassMiddlewareFactory.Create<QueryResultMiddleware>(
(typeof(IReadOnlyList<CreateError>), errorFactories)),
isRepeatable: false,
key: "Query Results");
// last but not least we insert the result middleware to the query field.
field.MiddlewareConfigurations.Insert(0, errorMiddleware);
}
}
}
}
private static TypeReference GetFieldType(TypeReference typeRef)
{
if (typeRef is ExtendedTypeReference { Type.IsGeneric: true } extendedTypeRef
&& typeof(IFieldResult).IsAssignableFrom(extendedTypeRef.Type.Type))
{
return TypeReference.Create(extendedTypeRef.Type.TypeArguments[0], TypeContext.Output);
}
return typeRef;
}
private TypeReference CreateFieldResultType(string fieldName, IReadOnlyList<TypeReference> typeSet)
{
var resultType = new UnionType(
d =>
{
d.Name(CreateResultTypeName(fieldName));
var typeDef = d.Extend().Configuration;
foreach (var schemaTypeRef in typeSet)
{
typeDef.Types.Add(schemaTypeRef);
}
});
var registeredType = _typeInitializer.InitializeType(resultType);
var resultTypeRef = new SchemaTypeReference(new NonNullType(resultType));
registeredType.References.Add(resultTypeRef);
_typeRegistry.Register(registeredType);
_typeInitializer.CompleteTypeName(registeredType);
_typeInitializer.CompileResolvers(registeredType);
_typeInitializer.CompleteType(registeredType);
return resultTypeRef;
}
private RegisteredType? TryRegisterType(Type type)
{
if (_typeRegistry.IsRegistered(_context.TypeInspector.GetOutputTypeRef(type)))
{
return null;
}
var registeredType = _typeInitializer.InitializeType(type);
_typeInitializer.CompleteTypeName(registeredType);
_typeInitializer.CompileResolvers(registeredType);
if (registeredType.Type is ObjectType errorObject && errorObject.RuntimeType != typeof(object))
{
foreach (var possibleInterface in _typeRegistry.Types)
{
if (possibleInterface.Type is InterfaceType interfaceType
&& interfaceType.RuntimeType != typeof(object)
&& interfaceType.RuntimeType.IsAssignableFrom(errorObject.RuntimeType))
{
var typeRef = possibleInterface.TypeReference;
errorObject.Configuration!.Interfaces.Add(typeRef);
registeredType.Dependencies.Add(new TypeDependency(typeRef, Completed));
}
else if (possibleInterface.Type is UnionType unionType
&& unionType.RuntimeType != typeof(object)
&& unionType.RuntimeType.IsAssignableFrom(errorObject.RuntimeType))
{
var typeRef = registeredType.TypeReference;
unionType.Configuration!.Types.Add(typeRef);
possibleInterface.Dependencies.Add(new TypeDependency(typeRef, Completed));
}
}
}
else if (registeredType.Type is ObjectType errorInterface && errorInterface.RuntimeType != typeof(object))
{
foreach (var possibleInterface in _typeRegistry.Types)
{
if (possibleInterface.Type is InterfaceType interfaceType
&& interfaceType.RuntimeType != typeof(object)
&& interfaceType.RuntimeType.IsAssignableFrom(errorInterface.RuntimeType))
{
var typeRef = possibleInterface.TypeReference;
errorInterface.Configuration!.Interfaces.Add(typeRef);
registeredType.Dependencies.Add(new(typeRef, Completed));
}
}
}
return registeredType;
}
private void RegisterErrorType(TypeReference errorTypeRef, Type lookupType)
=> _typeRegistry.TryRegister(_context.TypeInspector.GetOutputTypeRef(lookupType), errorTypeRef);
private string CreateResultTypeName(string fieldName)
{
_sb.Clear();
_sb.Append(char.ToUpper(fieldName[0]));
if (fieldName.Length > 1)
{
_sb.Append(fieldName.AsSpan()[1..]);
}
_sb.Append("Result");
return _sb.ToString();
}
}
| QueryConventionTypeInterceptor |
csharp | dotnet__orleans | test/Benchmarks/Serialization/Models/Vector3.cs | {
"start": 399,
"end": 532
} | public struct ____
{
[Id(0)]
public float X;
[Id(1)]
public float Y;
[Id(2)]
public float Z;
}
| ImmutableVector3 |
csharp | npgsql__npgsql | src/Npgsql/PostgresDatabaseInfo.cs | {
"start": 22019,
"end": 22944
} | enum ____
Expect<RowDescriptionMessage>(await conn.ReadMessage(async).ConfigureAwait(false), conn);
currentOID = uint.MaxValue;
PostgresEnumType? currentEnum = null;
skipCurrent = false;
while (true)
{
msg = await conn.ReadMessage(async).ConfigureAwait(false);
if (msg is not DataRowMessage)
break;
conn.ReadBuffer.Skip(2); // Column count
var oid = uint.Parse(ReadNonNullableString(conn.ReadBuffer), NumberFormatInfo.InvariantInfo);
var enumlabel = ReadNonNullableString(conn.ReadBuffer);
if (oid != currentOID)
{
currentOID = oid;
if (!byOID.TryGetValue(oid, out var type)) // See #2020
{
_connectionLogger.LogWarning("Skipping | fields |
csharp | SixLabors__ImageSharp | src/ImageSharp/PixelAccessor{TPixel}.cs | {
"start": 1798,
"end": 2823
} | struct ____<TPixel>
where TPixel : unmanaged, IPixel<TPixel>
{
private Buffer2D<TPixel> buffer;
internal PixelAccessor(Buffer2D<TPixel> buffer) => this.buffer = buffer;
/// <summary>
/// Gets the width of the backing <see cref="Image{TPixel}"/>.
/// </summary>
public int Width => this.buffer.Width;
/// <summary>
/// Gets the height of the backing <see cref="Image{TPixel}"/>.
/// </summary>
public int Height => this.buffer.Height;
/// <summary>
/// Gets the representation of the pixels as a <see cref="Span{T}"/> of contiguous memory
/// at row <paramref name="rowIndex"/> beginning from the first pixel on that row.
/// </summary>
/// <param name="rowIndex">The row index.</param>
/// <returns>The <see cref="Span{TPixel}"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown when row index is out of range.</exception>
public Span<TPixel> GetRowSpan(int rowIndex) => this.buffer.DangerousGetRowSpan(rowIndex);
}
| PixelAccessor |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Caching/src/Caching/Types/CacheControlDirectiveType.cs | {
"start": 236,
"end": 322
} | interface ____ union types to provide caching hints to
/// the executor.
/// </summary>
| or |
csharp | dotnet__efcore | test/EFCore.SqlServer.FunctionalTests/SqlServerConfigPatternsTest.cs | {
"start": 8720,
"end": 9453
} | public class ____
{
[ConditionalFact]
public async Task Can_register_context_with_DI_container_and_have_it_injected()
{
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkSqlServer()
.AddTransient<NorthwindContext>()
.AddTransient<MyController>()
.AddSingleton(p => new DbContextOptionsBuilder().UseInternalServiceProvider(p).Options)
.BuildServiceProvider(validateScopes: true);
await using (await SqlServerTestStore.GetNorthwindStoreAsync())
{
await serviceProvider.GetRequiredService<MyController>().TestAsync();
}
}
| InjectContext |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Placements/Deployment/PlacementsDeploymentSource.cs | {
"start": 230,
"end": 1323
} | public sealed class ____
: DeploymentSourceBase<PlacementsDeploymentStep>
{
private readonly PlacementsManager _placementsManager;
private readonly JsonSerializerOptions _jsonSerializerOptions;
public PlacementsDeploymentSource(
PlacementsManager placementsManager,
IOptions<DocumentJsonSerializerOptions> jsonSerializerOptions)
{
_placementsManager = placementsManager;
_jsonSerializerOptions = jsonSerializerOptions.Value.SerializerOptions;
}
protected override async Task ProcessAsync(PlacementsDeploymentStep step, DeploymentPlanResult result)
{
var placementObjects = new JsonObject();
var placements = await _placementsManager.ListShapePlacementsAsync();
foreach (var placement in placements)
{
placementObjects[placement.Key] = JArray.FromObject(placement.Value, _jsonSerializerOptions);
}
result.Steps.Add(new JsonObject
{
["name"] = "Placements",
["Placements"] = placementObjects,
});
}
}
| PlacementsDeploymentSource |
csharp | dotnet__efcore | test/EFCore.Tests/ChangeTracking/ComplexPropertyEntryTest.cs | {
"start": 24622,
"end": 24793
} | private class ____
{
public string? Name;
public int Rating;
public FieldTag Tag = null!;
public FieldTog Tog;
}
| FieldManufacturer |
csharp | ServiceStack__ServiceStack | ServiceStack.Text/tests/ServiceStack.Text.Benchmarks/MiniProfiler/ClientTimings.cs | {
"start": 260,
"end": 6685
} | public class ____
{
private const string TimingPrefix = "clientPerformance[timing][";
private const string ProbesPrefix = "clientProbes[";
/// <summary>
/// Gets or sets the list of client side timings
/// </summary>
[DataMember(Order = 2)]
public List<ClientTiming> Timings { get; set; }
/// <summary>
/// Gets or sets the redirect count.
/// </summary>
[DataMember(Order = 1)]
public int RedirectCount { get; set; }
/// <summary>
/// Returns null if there is not client timing stuff
/// </summary>
/// <param name="form">The form to transform to a <see cref="ClientTiming"/>.</param>
public static ClientTimings FromForm(IDictionary<string, string> form)
{
ClientTimings timing = null;
// AJAX requests won't have client timings
if (!form.ContainsKey(TimingPrefix + "navigationStart]")) return timing;
long.TryParse(form[TimingPrefix + "navigationStart]"], out long navigationStart);
if (navigationStart > 0)
{
var timings = new List<ClientTiming>();
timing = new ClientTimings();
int.TryParse(form["clientPerformance[navigation][redirectCount]"], out int redirectCount);
timing.RedirectCount = redirectCount;
var clientPerf = new Dictionary<string, ClientTiming>();
var clientProbes = new Dictionary<int, ClientTiming>();
foreach (string key in
form.Keys.OrderBy(i => i.IndexOf("Start]", StringComparison.Ordinal) > 0 ? "_" + i : i))
{
if (key.StartsWith(TimingPrefix, StringComparison.Ordinal))
{
long.TryParse(form[key], out long val);
val -= navigationStart;
string parsedName = key.Substring(
TimingPrefix.Length, (key.Length - 1) - TimingPrefix.Length);
// just ignore stuff that is negative ... not relevant
if (val > 0)
{
if (parsedName.EndsWith("Start", StringComparison.Ordinal))
{
var shortName = parsedName.Substring(0, parsedName.Length - 5);
clientPerf[shortName] = new ClientTiming
{
Duration = -1,
Name = parsedName,
Start = val
};
}
else if (parsedName.EndsWith("End", StringComparison.Ordinal))
{
var shortName = parsedName.Substring(0, parsedName.Length - 3);
if (clientPerf.TryGetValue(shortName, out var t))
{
t.Duration = val - t.Start;
t.Name = shortName;
}
}
else
{
clientPerf[parsedName] = new ClientTiming { Name = parsedName, Start = val, Duration = -1 };
}
}
}
if (key.StartsWith(ProbesPrefix, StringComparison.Ordinal))
{
int endBracketIndex = key.IndexOf(']');
if (endBracketIndex > 0 && int.TryParse(key.Substring(ProbesPrefix.Length, endBracketIndex - ProbesPrefix.Length), out int probeId))
{
if (!clientProbes.TryGetValue(probeId, out var t))
{
t = new ClientTiming();
clientProbes.Add(probeId, t);
}
if (key.EndsWith("[n]", StringComparison.Ordinal))
{
t.Name = form[key];
}
if (key.EndsWith("[d]", StringComparison.Ordinal))
{
long.TryParse(form[key], out long val);
if (val > 0)
{
t.Start = val - navigationStart;
}
}
}
}
}
foreach (var group in clientProbes
.Values.OrderBy(p => p.Name)
.GroupBy(p => p.Name))
{
ClientTiming current = null;
foreach (var item in group)
{
if (current == null)
{
current = item;
}
else
{
current.Duration = item.Start - current.Start;
timings.Add(current);
current = null;
}
}
}
foreach (var item in clientPerf.Values)
{
item.Name = SentenceCase(item.Name);
}
timings.AddRange(clientPerf.Values);
timing.Timings = timings.OrderBy(t => t.Start).ToList();
}
return timing;
}
private static string SentenceCase(string value)
{
var sb = new StringBuilder();
for (int i = 0; i < value.Length; i++)
{
if (i == 0)
{
sb.Append(char.ToUpper(value[0]));
continue;
}
if (value[i] == char.ToUpper(value[i]))
{
sb.Append(' ');
}
sb.Append(value[i]);
}
return sb.ToString();
}
}
}
| ClientTimings |
csharp | dotnet__orleans | test/Tester/MinimalReminderTests.cs | {
"start": 287,
"end": 424
} | public class ____ : IClassFixture<MinimalReminderTests.Fixture>
{
private readonly Fixture fixture;
| MinimalReminderTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.