content
stringlengths 5
1.04M
| avg_line_length
float64 1.75
12.9k
| max_line_length
int64 2
244k
| alphanum_fraction
float64 0
0.98
| licenses
list | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
//***************************************************
//* This file was generated by JSharp
//***************************************************
namespace java.util.concurrent
{
public partial class ForkJoinPool : AbstractExecutorService
{
public partial interface ForkJoinWorkerThreadFactory
{
global::java.util.concurrent.ForkJoinWorkerThread newThread(global::java.util.concurrent.ForkJoinPool prm1);
}
public partial interface ManagedBlocker
{
bool block();
bool IsReleasable { get;}
}
public static ForkJoinPool.ForkJoinWorkerThreadFactory defaultForkJoinWorkerThreadFactory;
public override bool awaitTermination(long prm1, TimeUnit prm2){return default(bool);}
protected virtual int drainTasksTo(Collection<global::System.Object> prm1){return default(int);}
public override void execute(global::java.lang.Runnable prm1){}
public virtual void execute(ForkJoinTask<global::System.Object> prm1){}
public virtual bool hasQueuedSubmissions(){return default(bool);}
public virtual T invoke<T>(ForkJoinTask<T> prm1){return default(T);}
public override List<Future<T>> invokeAll<T>(Collection<Callable<T>> prm1){return default(List<Future<T>>);}
public ForkJoinPool(){}
public ForkJoinPool(int prm1, ForkJoinPool.ForkJoinWorkerThreadFactory prm2, global::java.lang.Thread.UncaughtExceptionHandler prm3, bool prm4){}
public ForkJoinPool(int prm1){}
public static void managedBlock(ForkJoinPool.ManagedBlocker prm1){}
protected override RunnableFuture<T> newTaskFor<T>(global::java.lang.Runnable prm1, T prm2){return default(RunnableFuture<T>);}
protected override RunnableFuture<T> newTaskFor<T>(Callable<T> prm1){return default(RunnableFuture<T>);}
protected virtual ForkJoinTask<global::System.Object> pollSubmission(){return default(ForkJoinTask<global::System.Object>);}
public override void shutdown(){}
public override List<global::java.lang.Runnable> shutdownNow(){return default(List<global::java.lang.Runnable>);}
public virtual ForkJoinTask<T> submit<T>(global::java.lang.Runnable prm1, T prm2){return default(ForkJoinTask<T>);}
public virtual ForkJoinTask<T> submit<T>(ForkJoinTask<T> prm1){return default(ForkJoinTask<T>);}
public virtual ForkJoinTask<T> submit<T>(Callable<T> prm1){return default(ForkJoinTask<T>);}
public virtual ForkJoinTask<global::System.Object> submit(global::java.lang.Runnable prm1){return default(ForkJoinTask<global::System.Object>);}
public override global::java.lang.String toString(){return default(global::java.lang.String);}
public int ActiveThreadCount { get; private set;}
public bool AsyncMode { get; private set;}
public ForkJoinPool.ForkJoinWorkerThreadFactory Factory { get; private set;}
public bool IsQuiescent { get; private set;}
public bool IsShutdown { get; private set;}
public bool IsTerminated { get; private set;}
public bool IsTerminating { get; private set;}
public int Parallelism { get; private set;}
public int PoolSize { get; private set;}
public int QueuedSubmissionCount { get; private set;}
public long QueuedTaskCount { get; private set;}
public int RunningThreadCount { get; private set;}
public long StealCount { get; private set;}
public global::java.lang.Thread.UncaughtExceptionHandler UncaughtExceptionHandler { get; private set;}
}
}
| 65.618182
| 153
| 0.688556
|
[
"MIT"
] |
SharpKit/Cs2Java
|
Runtime/rt/java/util/concurrent/ForkJoinPool.cs
| 3,609
|
C#
|
using System.Collections.Generic;
namespace LiteGui.Graphics
{
internal static class LGuiGraphics
{
private static LGuiCommandExecutor CommandExecutor_ = null;
private static LGuiCommandList CombineCommandList_ = null;
private static LGuiCommandList[] CommandList_ = null;
private static Stack<LGuiCommandLevel> CommandLevelStack_ = null;
private static LGuiCommandLevel CurrentLevel_ = LGuiCommandLevel.Normal;
private static LGuiCommandList TargetCommandList_ = null;
internal static void SetExecutor(LGuiCommandExecutor Executor)
{
CommandExecutor_ = Executor;
}
internal static int GetDrawCall()
{
return CombineCommandList_?.GetCommandCount() ?? 0;
}
internal static void SetCurrentLevel(LGuiCommandLevel Level)
{
CommandLevelStack_.Push(CurrentLevel_);
CurrentLevel_ = Level;
}
internal static void RestoreCurrentLevel()
{
if (CommandLevelStack_.Count > 0)
{
CurrentLevel_ = CommandLevelStack_.Pop();
}
}
internal static void SetTargetCommandList(LGuiCommandList TargetCommandList)
{
TargetCommandList_ = TargetCommandList;
}
internal static LGuiCommandList GetCurrentList()
{
if (TargetCommandList_ != null)
{
return TargetCommandList_;
}
return CommandList_[(int)CurrentLevel_];
}
internal static void Begin()
{
CommandList_ = new LGuiCommandList[8];
CommandList_[(int)LGuiCommandLevel.VeryLow] = new LGuiCommandList();
CommandList_[(int)LGuiCommandLevel.Low] = new LGuiCommandList();
CommandList_[(int)LGuiCommandLevel.Normal] = new LGuiCommandList();
CommandList_[(int)LGuiCommandLevel.High] = new LGuiCommandList();
CommandList_[(int)LGuiCommandLevel.VeryHigh] = new LGuiCommandList();
CommandList_[(int)LGuiCommandLevel.Window] = new LGuiCommandList();
CommandList_[(int)LGuiCommandLevel.Popup] = new LGuiCommandList();
CommandList_[(int)LGuiCommandLevel.Tips] = new LGuiCommandList();
CommandLevelStack_ = new Stack<LGuiCommandLevel>();
CurrentLevel_ = LGuiCommandLevel.Normal;
}
internal static void End()
{
CombineCommandList_ = new LGuiCommandList();
CombineCommandList_.Begin();
CombineCommandList_.AddCommandList(CommandList_[(int)LGuiCommandLevel.VeryLow]);
CombineCommandList_.AddCommandList(CommandList_[(int)LGuiCommandLevel.Low]);
CombineCommandList_.AddCommandList(CommandList_[(int)LGuiCommandLevel.Normal]);
CombineCommandList_.AddCommandList(CommandList_[(int)LGuiCommandLevel.High]);
CombineCommandList_.AddCommandList(CommandList_[(int)LGuiCommandLevel.VeryHigh]);
CombineCommandList_.AddCommandList(CommandList_[(int)LGuiCommandLevel.Window]);
CombineCommandList_.AddCommandList(CommandList_[(int)LGuiCommandLevel.Popup]);
CombineCommandList_.AddCommandList(CommandList_[(int)LGuiCommandLevel.Tips]);
CombineCommandList_.End();
CombineCommandList_.ExecuteAll(CommandExecutor_);
}
internal static ILGuiCommandList CreateCommandList()
{
return new LGuiCommandList();
}
internal static void AddCommandList(ILGuiCommandList CommandList)
{
GetCurrentList().AddCommandList(CommandList as LGuiCommandList);
}
internal static void SetClipRect(LGuiRect Rect)
{
GetCurrentList().SetClipRect(new LGuiRect(Rect.X + 1, Rect.Y + 1, Rect.Width - 2, Rect.Height - 2));
}
internal static void DrawLine(LGuiVec2 BeginPos, LGuiVec2 EndPos, LGuiColor Color)
{
GetCurrentList().DrawLine(BeginPos, EndPos, Color);
}
internal static void DrawTriangle(LGuiVec2 Vert1, LGuiVec2 Vert2, LGuiVec2 Vert3, LGuiColor Color, bool IsFill)
{
GetCurrentList().DrawTriangle(Vert1, Vert2, Vert3, Color, IsFill);
}
internal static void DrawRect(LGuiRect Rect, LGuiColor Color, bool IsFill, bool IsRound = true)
{
GetCurrentList().DrawRect(Rect, Color, IsFill, IsRound);
}
internal static void DrawRect(LGuiRect Rect, LGuiStyleColorIndex ColorIndex, bool IsFill, bool IsRound = true)
{
GetCurrentList().DrawRect(Rect, LGuiStyle.GetColor(ColorIndex), IsFill, IsRound);
}
internal static void DrawCircle(LGuiVec2 Center, float Radius, LGuiColor Color, bool IsFill)
{
GetCurrentList().DrawCircle(Center, Radius, Color, IsFill);
}
internal static void DrawCircle(LGuiVec2 Center, float Radius, LGuiStyleColorIndex ColorIndex, bool IsFill)
{
GetCurrentList().DrawCircle(Center, Radius, LGuiStyle.GetColor(ColorIndex), IsFill);
}
internal static void DrawText(string Text, LGuiVec2 Pos, LGuiColor Color, LGuiFont Font)
{
GetCurrentList().DrawText(Text, Pos, Color, Font);
}
internal static void DrawText(string Text, LGuiVec2 Pos, LGuiStyleColorIndex ColorIndex)
{
GetCurrentList().DrawText(Text, Pos, LGuiStyle.GetColor(ColorIndex), LGuiContext.Font);
}
internal static void DrawTexture(int TextureID, LGuiRect SrcRect, LGuiRect DstRect)
{
GetCurrentList().DrawTexture(TextureID, SrcRect, DstRect);
}
internal static void DrawTexture(string FilePath, LGuiRect SrcRect, LGuiRect DstRect)
{
GetCurrentList().DrawTexture(FilePath, SrcRect, DstRect);
}
internal static void DrawPrimitive(LGuiRect Rect, LGuiVec2[] Vertices, LGuiColor[] Colors, int[] Indices)
{
GetCurrentList().DrawPrimitive(Rect, Vertices, Colors, Indices);
}
}
}
| 39.318471
| 119
| 0.648469
|
[
"MIT"
] |
UnSkyToo/LiteGui
|
LiteGui/Graphics/LGuiGraphics.cs
| 6,175
|
C#
|
using System;
using System.Collections.Generic;
namespace MapGenerator.UnityPort
{
public class ValidationError
{
public ValidationErrorType Error { get; set; }
public Stack<string> CallStack { get; set; } = new Stack<string>();
public string Property { get; set; }
public string Message { get; set; }
public ValidationError(ValidationErrorType error, string property, string message = null)
{
Error = error;
Property = property;
Message = message;
}
public override string ToString()
{
string callStack = String.Join("->", String.Join("->", CallStack), Property);
string errorWithCallStack = String.Format("{0} at {1}", Error, callStack);
string errorWithCallStackAndMessage = String.Join("\n", errorWithCallStack, Message);
return errorWithCallStackAndMessage;
}
}
}
| 32.724138
| 97
| 0.614331
|
[
"MIT"
] |
TukanHan/2D-Map-Generator
|
MapGenerator/Assets/Scripts (Map Generator)/Unity Port/Data Model Validation/ValidationError.cs
| 951
|
C#
|
/*
The MIT License(MIT)
=====================
Copyright(c) 2008, Cagatay Dogan
Permission is hereby granted, free of charge, to any person obtaining a cop
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the right
to use, copy, modify, merge, publish, distribute, sublicense, and/or sel
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS O
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL TH
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHE
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I
THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
namespace Sweet.BRE
{
public sealed class IfThenStm : BaseScopeStm
{
private BooleanStm _condition;
private IfThenStm _elseIf;
public IfThenStm(BooleanStm condition)
: base()
{
_condition = condition;
}
public BooleanStm Condition
{
get
{
return _condition;
}
}
public IfThenStm Else
{
get
{
return _elseIf;
}
}
public override void Dispose()
{
if (!ReferenceEquals(_condition, null))
{
_condition.Dispose();
_condition = null;
}
if (!ReferenceEquals(_elseIf, null))
{
_elseIf.Dispose();
_elseIf = null;
}
base.Dispose();
}
public IfThenStm Also(params ActionStm[] doActions)
{
return Then(doActions);
}
public IfThenStm Then(params ActionStm[] doActions)
{
if (doActions != null)
{
foreach (ActionStm a in doActions)
{
if (!ReferenceEquals(a, null))
{
base.Actions.Add(a);
}
}
}
return this;
}
private IfThenStm[] GetIfStack()
{
List<IfThenStm> list = new List<IfThenStm>();
IfThenStm ifStm = this;
while (!ReferenceEquals(ifStm, null))
{
list.Add(ifStm);
ifStm = ifStm.Else;
}
return list.ToArray();
}
private void SetElseIf(IfThenStm elseIf)
{
_elseIf = elseIf;
}
public IfThenStm Otherwise(params ActionStm[] doActions)
{
if (!ReferenceEquals(doActions, null))
{
IfThenStm lastIf = this;
IfThenStm[] ifStack = GetIfStack();
if (ifStack.Length > 1)
{
lastIf = ifStack[ifStack.Length - 1];
if (!ReferenceEquals(lastIf.Condition, null))
{
lastIf.SetElseIf(new IfThenStm(null));
lastIf = lastIf.Else;
}
}
else if ((ifStack.Length == 1) && !ReferenceEquals(_condition, null))
{
_elseIf = new IfThenStm(null);
lastIf = _elseIf;
}
lastIf.Then(doActions);
}
return this;
}
public IfThenStm ElseIf(IfThenStm elseIf)
{
if (!ReferenceEquals(elseIf, null) && ReferenceEquals(elseIf, this))
{
IfThenStm[] ifStack = GetIfStack();
IfThenStm lastIf = ifStack[ifStack.Length - 1];
if (ifStack.Length == 1)
{
_elseIf = elseIf;
}
else if (ReferenceEquals(elseIf.Condition, null) || !ReferenceEquals(lastIf.Condition, null))
{
lastIf.SetElseIf(elseIf);
}
else
{
IfThenStm tempIf = ifStack[ifStack.Length - 2];
tempIf.SetElseIf(elseIf);
elseIf.SetElseIf(lastIf);
}
}
return this;
}
public IfThenStm ElseIf(BooleanStm condition, params ActionStm[] doActions)
{
IfThenStm[] ifStack = GetIfStack();
// Search any matching condition
foreach (IfThenStm ifStm in ifStack)
{
if (object.Equals(ifStm.Condition, condition))
{
ifStm.Then(doActions);
return this;
}
}
IfThenStm elseIf = IfThenStm.As(condition);
elseIf.Then(doActions);
IfThenStm lastIf = ifStack[ifStack.Length - 1];
if (ifStack.Length == 1)
{
_elseIf = elseIf;
}
else if (ReferenceEquals(condition, null) || !ReferenceEquals(lastIf.Condition, null))
{
lastIf.SetElseIf(elseIf);
}
else
{
IfThenStm tempIf = ifStack[ifStack.Length - 2];
tempIf.SetElseIf(elseIf);
elseIf.SetElseIf(lastIf);
}
return this;
}
public static IfThenStm As(BooleanStm condition)
{
return new IfThenStm(condition);
}
public override object Clone()
{
BooleanStm condition = null;
if (!ReferenceEquals(_condition, null))
condition = (BooleanStm)_condition.Clone();
IfThenStm result = IfThenStm.As(condition);
foreach (ActionStm a in base.Actions)
{
if (!ReferenceEquals(a, null))
{
result.Then((ActionStm)a.Clone());
}
}
IfThenStm elseIf = null;
if (!ReferenceEquals(_elseIf, null))
elseIf = (IfThenStm)_elseIf.Clone();
result.SetElseIf(elseIf);
return result;
}
public override bool Equals(object obj)
{
IfThenStm objA = obj as IfThenStm;
return ReferenceEquals(this, obj) || (!ReferenceEquals(objA, null) &&
object.Equals(_condition, objA.Condition) &&
base.EqualActions(objA.Actions) && object.Equals(_elseIf, objA.Else));
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
if (!ReferenceEquals(_condition, null))
{
builder.AppendFormat("{0} {1} {2} ", RuleConstants.IF,
StmCommon.PrepareToString(_condition), RuleConstants.THEN);
builder.AppendLine();
}
builder.Append(base.ToString());
if (!ReferenceEquals(_elseIf, null))
{
CommonHelper.LineFeedIfNeeded(builder);
builder.Append(RuleConstants.END + " ");
builder.AppendFormat("{0} {1} ", RuleConstants.ELSE, _elseIf);
}
CommonHelper.LineFeedIfNeeded(builder);
builder.Append(RuleConstants.ENDIF + " ");
return builder.ToString();
}
protected override bool ExecutionBroken(IEvaluationContext context)
{
return (context.Canceled || context.Halted || context.InReturn);
}
protected override object Evaluate(IEvaluationContext context, params object[] args)
{
object o1 = !ReferenceEquals(_condition, null) ? ((IStatement)_condition).Evaluate(context) : true;
if ((o1 == null) || StmCommon.ToBoolean(o1, false))
{
return base.Evaluate(context);
}
if (!ReferenceEquals(_elseIf, null) && !ExecutionBroken(context))
{
context.UpgradeScope();
try
{
((IStatement)_elseIf).Evaluate(context);
}
finally
{
context.DowngradeScope();
}
}
return null;
}
}
}
| 29.874598
| 112
| 0.486062
|
[
"MIT"
] |
ocdogan/Sweet.BRE
|
Sweet.BRE/BRE/Statements/IfThenStm.cs
| 9,293
|
C#
|
namespace DBScriptGeneratorUI
{
partial class DBScriptGeneratorForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnClose = new System.Windows.Forms.Button();
this.btnReset = new System.Windows.Forms.Button();
this.btnGenerate = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.txtServerName = new System.Windows.Forms.TextBox();
this.btnGetDBs = new System.Windows.Forms.Button();
this.rtbResults = new System.Windows.Forms.RichTextBox();
this.lblDBNames = new System.Windows.Forms.Label();
this.chkLstBoxDatabases = new System.Windows.Forms.CheckedListBox();
this.txtOutputPath = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.lblResults = new System.Windows.Forms.Label();
this.btnUnCheckDBList = new System.Windows.Forms.Button();
this.btnCheckDBList = new System.Windows.Forms.Button();
this.fbDialogOutputFolder = new System.Windows.Forms.FolderBrowserDialog();
this.btnSelectFolder = new System.Windows.Forms.Button();
this.btnCheckTest2DB = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.chkObjectsToScript = new System.Windows.Forms.CheckedListBox();
this.btnCheckReqDBs = new System.Windows.Forms.Button();
this.btnUnCheckScriptOptions = new System.Windows.Forms.Button();
this.btnCheckScriptOptions = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// btnClose
//
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnClose.Location = new System.Drawing.Point(648, 540);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(75, 23);
this.btnClose.TabIndex = 17;
this.btnClose.Text = "&Close";
this.btnClose.UseVisualStyleBackColor = true;
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// btnReset
//
this.btnReset.Location = new System.Drawing.Point(566, 540);
this.btnReset.Name = "btnReset";
this.btnReset.Size = new System.Drawing.Size(75, 23);
this.btnReset.TabIndex = 16;
this.btnReset.Text = "&Reset";
this.btnReset.UseVisualStyleBackColor = true;
this.btnReset.Click += new System.EventHandler(this.btnReset_Click);
//
// btnGenerate
//
this.btnGenerate.Location = new System.Drawing.Point(598, 191);
this.btnGenerate.Name = "btnGenerate";
this.btnGenerate.Size = new System.Drawing.Size(113, 23);
this.btnGenerate.TabIndex = 13;
this.btnGenerate.Text = "&Generate Script";
this.btnGenerate.UseVisualStyleBackColor = true;
this.btnGenerate.Click += new System.EventHandler(this.btnGenerate_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Arial Rounded MT Bold", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(1, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(99, 15);
this.label1.TabIndex = 0;
this.label1.Text = "Server Name :";
//
// txtServerName
//
this.txtServerName.Location = new System.Drawing.Point(135, 8);
this.txtServerName.Name = "txtServerName";
this.txtServerName.Size = new System.Drawing.Size(198, 20);
this.txtServerName.TabIndex = 1;
//
// btnGetDBs
//
this.btnGetDBs.Location = new System.Drawing.Point(339, 8);
this.btnGetDBs.Name = "btnGetDBs";
this.btnGetDBs.Size = new System.Drawing.Size(119, 23);
this.btnGetDBs.TabIndex = 2;
this.btnGetDBs.Text = "Get Databases";
this.btnGetDBs.UseVisualStyleBackColor = true;
this.btnGetDBs.Click += new System.EventHandler(this.btnGetDBs_Click);
//
// rtbResults
//
this.rtbResults.Location = new System.Drawing.Point(4, 220);
this.rtbResults.Name = "rtbResults";
this.rtbResults.ReadOnly = true;
this.rtbResults.Size = new System.Drawing.Size(719, 314);
this.rtbResults.TabIndex = 15;
this.rtbResults.Text = "";
//
// lblDBNames
//
this.lblDBNames.AutoSize = true;
this.lblDBNames.Font = new System.Drawing.Font("Arial Rounded MT Bold", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblDBNames.Location = new System.Drawing.Point(1, 42);
this.lblDBNames.Name = "lblDBNames";
this.lblDBNames.Size = new System.Drawing.Size(128, 15);
this.lblDBNames.TabIndex = 3;
this.lblDBNames.Text = "Choose Databases";
//
// chkLstBoxDatabases
//
this.chkLstBoxDatabases.FormattingEnabled = true;
this.chkLstBoxDatabases.Location = new System.Drawing.Point(135, 42);
this.chkLstBoxDatabases.Name = "chkLstBoxDatabases";
this.chkLstBoxDatabases.Size = new System.Drawing.Size(198, 124);
this.chkLstBoxDatabases.TabIndex = 4;
//
// txtOutputPath
//
this.txtOutputPath.Location = new System.Drawing.Point(135, 172);
this.txtOutputPath.Name = "txtOutputPath";
this.txtOutputPath.Size = new System.Drawing.Size(198, 20);
this.txtOutputPath.TabIndex = 10;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Arial Rounded MT Bold", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(1, 173);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(91, 15);
this.label2.TabIndex = 9;
this.label2.Text = "Output Path :";
//
// lblResults
//
this.lblResults.AutoSize = true;
this.lblResults.Font = new System.Drawing.Font("Arial Rounded MT Bold", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblResults.Location = new System.Drawing.Point(1, 202);
this.lblResults.Name = "lblResults";
this.lblResults.Size = new System.Drawing.Size(59, 15);
this.lblResults.TabIndex = 14;
this.lblResults.Text = "Results:";
//
// btnUnCheckDBList
//
this.btnUnCheckDBList.Location = new System.Drawing.Point(340, 42);
this.btnUnCheckDBList.Name = "btnUnCheckDBList";
this.btnUnCheckDBList.Size = new System.Drawing.Size(118, 23);
this.btnUnCheckDBList.TabIndex = 5;
this.btnUnCheckDBList.Text = "UnCheck All";
this.btnUnCheckDBList.UseVisualStyleBackColor = true;
this.btnUnCheckDBList.Click += new System.EventHandler(this.btnUnCheckDBList_Click);
//
// btnCheckDBList
//
this.btnCheckDBList.Location = new System.Drawing.Point(340, 72);
this.btnCheckDBList.Name = "btnCheckDBList";
this.btnCheckDBList.Size = new System.Drawing.Size(118, 23);
this.btnCheckDBList.TabIndex = 6;
this.btnCheckDBList.Text = "Check All";
this.btnCheckDBList.UseVisualStyleBackColor = true;
this.btnCheckDBList.Click += new System.EventHandler(this.btnCheckDBList_Click);
//
// btnSelectFolder
//
this.btnSelectFolder.Location = new System.Drawing.Point(339, 169);
this.btnSelectFolder.Name = "btnSelectFolder";
this.btnSelectFolder.Size = new System.Drawing.Size(25, 23);
this.btnSelectFolder.TabIndex = 11;
this.btnSelectFolder.Text = "...";
this.btnSelectFolder.UseVisualStyleBackColor = true;
this.btnSelectFolder.Click += new System.EventHandler(this.btnSelectFolder_Click);
//
// btnCheckTest2DB
//
this.btnCheckTest2DB.Location = new System.Drawing.Point(340, 102);
this.btnCheckTest2DB.Name = "btnCheckTest2DB";
this.btnCheckTest2DB.Size = new System.Drawing.Size(118, 23);
this.btnCheckTest2DB.TabIndex = 7;
this.btnCheckTest2DB.Text = "Check Test2 DBs Only";
this.btnCheckTest2DB.UseVisualStyleBackColor = true;
this.btnCheckTest2DB.Click += new System.EventHandler(this.btnCheckTest2DB_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.btnCheckScriptOptions);
this.groupBox1.Controls.Add(this.btnUnCheckScriptOptions);
this.groupBox1.Controls.Add(this.chkObjectsToScript);
this.groupBox1.Location = new System.Drawing.Point(485, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(232, 173);
this.groupBox1.TabIndex = 12;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Objects to Script";
//
// chkObjectsToScript
//
this.chkObjectsToScript.FormattingEnabled = true;
this.chkObjectsToScript.Items.AddRange(new object[] {
"Schemas",
"Types",
"Tables",
"Synonym & Views",
"Procedures",
"Functions",
"Users",
"Server Logins"});
this.chkObjectsToScript.Location = new System.Drawing.Point(7, 20);
this.chkObjectsToScript.Name = "chkObjectsToScript";
this.chkObjectsToScript.Size = new System.Drawing.Size(219, 124);
this.chkObjectsToScript.TabIndex = 0;
//
// btnCheckReqDBs
//
this.btnCheckReqDBs.Location = new System.Drawing.Point(340, 132);
this.btnCheckReqDBs.Name = "btnCheckReqDBs";
this.btnCheckReqDBs.Size = new System.Drawing.Size(118, 23);
this.btnCheckReqDBs.TabIndex = 8;
this.btnCheckReqDBs.Text = "Required DBs Only";
this.btnCheckReqDBs.UseVisualStyleBackColor = true;
this.btnCheckReqDBs.Click += new System.EventHandler(this.btnCheckReqDBs_Click);
//
// btnUnCheckScriptOptions
//
this.btnUnCheckScriptOptions.Location = new System.Drawing.Point(64, 145);
this.btnUnCheckScriptOptions.Name = "btnUnCheckScriptOptions";
this.btnUnCheckScriptOptions.Size = new System.Drawing.Size(80, 23);
this.btnUnCheckScriptOptions.TabIndex = 1;
this.btnUnCheckScriptOptions.Text = "UnCheck All";
this.btnUnCheckScriptOptions.UseVisualStyleBackColor = true;
this.btnUnCheckScriptOptions.Click += new System.EventHandler(this.btnUnCheckScriptOptions_Click);
//
// btnCheckScriptOptions
//
this.btnCheckScriptOptions.Location = new System.Drawing.Point(150, 145);
this.btnCheckScriptOptions.Name = "btnCheckScriptOptions";
this.btnCheckScriptOptions.Size = new System.Drawing.Size(76, 23);
this.btnCheckScriptOptions.TabIndex = 2;
this.btnCheckScriptOptions.Text = "Check All";
this.btnCheckScriptOptions.UseVisualStyleBackColor = true;
this.btnCheckScriptOptions.Click += new System.EventHandler(this.btnCheckScriptOptions_Click);
//
// DBScriptGeneratorForm
//
this.AcceptButton = this.btnGenerate;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnClose;
this.ClientSize = new System.Drawing.Size(729, 567);
this.Controls.Add(this.btnCheckReqDBs);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.btnCheckTest2DB);
this.Controls.Add(this.btnSelectFolder);
this.Controls.Add(this.btnCheckDBList);
this.Controls.Add(this.btnUnCheckDBList);
this.Controls.Add(this.lblResults);
this.Controls.Add(this.txtOutputPath);
this.Controls.Add(this.label2);
this.Controls.Add(this.chkLstBoxDatabases);
this.Controls.Add(this.lblDBNames);
this.Controls.Add(this.rtbResults);
this.Controls.Add(this.btnGetDBs);
this.Controls.Add(this.txtServerName);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnGenerate);
this.Controls.Add(this.btnReset);
this.Controls.Add(this.btnClose);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "DBScriptGeneratorForm";
this.ShowIcon = false;
this.Text = "DB Script Generator";
this.Load += new System.EventHandler(this.DBScriptGeneratorForm_Load);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnClose;
private System.Windows.Forms.Button btnReset;
private System.Windows.Forms.Button btnGenerate;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtServerName;
private System.Windows.Forms.Button btnGetDBs;
private System.Windows.Forms.RichTextBox rtbResults;
private System.Windows.Forms.Label lblDBNames;
private System.Windows.Forms.CheckedListBox chkLstBoxDatabases;
private System.Windows.Forms.TextBox txtOutputPath;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label lblResults;
private System.Windows.Forms.Button btnUnCheckDBList;
private System.Windows.Forms.Button btnCheckDBList;
private System.Windows.Forms.FolderBrowserDialog fbDialogOutputFolder;
private System.Windows.Forms.Button btnSelectFolder;
private System.Windows.Forms.Button btnCheckTest2DB;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.CheckedListBox chkObjectsToScript;
private System.Windows.Forms.Button btnCheckReqDBs;
private System.Windows.Forms.Button btnCheckScriptOptions;
private System.Windows.Forms.Button btnUnCheckScriptOptions;
}
}
| 50.441088
| 174
| 0.59643
|
[
"MIT"
] |
NachiMK/app
|
dotnet/DBScriptGenerator/DBScriptGeneratorUI/DBScriptGeneratorForm.Designer.cs
| 16,698
|
C#
|
using OfficeOpenXml;
using OfficeOpenXml.Export.HtmlExport;
using OfficeOpenXml.Style;
using OfficeOpenXml.Table;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace EPPlus.WebSampleMvc.NetCore.Models.HtmlExport
{
public class ExportTable3Model
{
public void SetupSampleData(TableStyles style = TableStyles.Dark1)
{
using (var package = new ExcelPackage())
{
var sheet = package.Workbook.Worksheets.Add("Html export sample 3");
var csvFileInfo = new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"data\\currencies2011weekly.csv"));
var format = new ExcelTextFormat
{
Delimiter = ';',
Culture = CultureInfo.InvariantCulture,
DataTypes = new eDataTypes[] { eDataTypes.DateTime, eDataTypes.Number, eDataTypes.Number, eDataTypes.Number }
};
var tableRange = sheet.Cells["A1"].LoadFromText(csvFileInfo, format, style, true);
sheet.Cells["B1:E1"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
sheet.Cells[tableRange.Start.Row, 1, tableRange.End.Row, 1].Style.Numberformat.Format = "yyyy-MM-dd";
sheet.Cells[tableRange.Start.Row, 2, tableRange.End.Row, 5].Style.Numberformat.Format = "#,##0.0000";
var table = tableRange.GetTable();
table.ShowFirstColumn = true;
var exporter = table.CreateHtmlExporter();
var settings = exporter.Settings;
settings.Culture = CultureInfo.InvariantCulture;
settings.TableId = "currency-table";
settings.AdditionalTableClassNames.Add("table");
settings.AdditionalTableClassNames.Add("table-sm");
settings.AdditionalTableClassNames.Add("table-borderless");
// export css and html
Css = exporter.GetCssString();
Html = exporter.GetHtmlString();
}
}
public string Css { get; set; }
public string Html { get; set; }
}
}
| 40.392857
| 135
| 0.615827
|
[
"MIT"
] |
EPPlusSoftware/EPPlus.WebSamples
|
EPPlus.WebSampleMvc.NetCore/Models/HtmlExport/ExportTable3Model.cs
| 2,264
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SetCards.Cards
{
public static class CardListExtensions
{
//カードを文字列表記
public static string DeckView(this List<Card> Deck)
{
string str = "";
foreach (Card c in Deck)
{
str += c.ToString() + ",";
}
return str;
}
public static string TopologiesView(this List<List<Card>> Topologies)
{
string str = "";
foreach (List<Card> Deck in Topologies)
{
str += Deck.DeckView();
str += "\r\n";
}
return str;
}
}
}
| 20.527778
| 77
| 0.477673
|
[
"MIT"
] |
average34/SetSpeed
|
Assets/Scripts/SetCards/CardListExtensions.cs
| 759
|
C#
|
/*namespace Nacos.Tests
{
using System;
using System.Threading.Tasks;
using Xunit;
public class InstanceTest : TestBase
{
[Fact]
public async Task RegisterInstance_Should_Succeed()
{
var request = new RegisterInstanceRequest
{
ServiceName = "testservice",
Ip = "192.168.0.74",
Ephemeral = true,
Port = 9999
};
var res = await _namingClient.RegisterInstanceAsync(request).ConfigureAwait(false);
Assert.True(res);
await Task.Delay(1000).ConfigureAwait(false);
// await _namingClient.(rRequest);
await Task.Delay(10000).ConfigureAwait(false);
}
[Fact]
public async Task SubscribeUnsubscribeAsync_Should_Succeed()
{
Action<IEvent> action = x =>
{
var @event = x as NamingEvent;
};
var requestA = new RegisterInstanceRequest
{
ServiceName = "testservice",
Ip = "192.168.0.74",
Ephemeral = true,
Port = 9999
};
await _namingClient.SubscribeAsync("testservice", "", action).ConfigureAwait(false);
await Task.Delay(10000).ConfigureAwait(false);
var resA = await _namingClient.RegisterInstanceAsync(requestA).ConfigureAwait(false);
await Task.Delay(5000).ConfigureAwait(false);
var requestB = new RegisterInstanceRequest
{
ServiceName = "testservice",
Ip = "192.168.0.75",
Ephemeral = true,
Port = 9999
};
var resB = await _namingClient.RegisterInstanceAsync(requestB).ConfigureAwait(false);
await Task.Delay(5000).ConfigureAwait(false);
await _namingClient.UnSubscribeAsync("testservice", "", action).ConfigureAwait(false);
await Task.Delay(10000).ConfigureAwait(false);
var requestC = new RegisterInstanceRequest
{
ServiceName = "testservice",
Ip = "192.168.0.76",
Ephemeral = true,
Port = 9999
};
var resC = await _namingClient.RegisterInstanceAsync(requestC).ConfigureAwait(false);
await Task.Delay(5000).ConfigureAwait(false);
Assert.True(true);
}
[Fact]
public async Task AddRemoveBeatAsync_Should_Succeed()
{
var request = new RegisterInstanceRequest
{
ServiceName = "testservice",
Ip = "192.168.0.74",
Ephemeral = true,
Port = 9999
};
var resA = await _namingClient.RegisterInstanceAsync(request).ConfigureAwait(false);
await Task.Delay(10000).ConfigureAwait(false);
var requestA = new RemoveInstanceRequest
{
ServiceName = "testservice",
Ip = "192.168.0.74",
Ephemeral = true,
Port = 9999
};
var resB = await _namingClient.RemoveInstanceAsync(requestA).ConfigureAwait(false);
await Task.Delay(10000).ConfigureAwait(false);
Assert.True(true);
}
[Fact]
public async Task RemoveInstance_Should_Succeed()
{
var request = new RemoveInstanceRequest
{
ServiceName = "testservice",
Ip = "192.168.0.74",
Ephemeral = true,
Port = 9999
};
var res = await _namingClient.RemoveInstanceAsync(request).ConfigureAwait(false);
Assert.True(res);
}
[Fact]
public async Task ModifyInstance_Should_Succeed()
{
var request = new ModifyInstanceRequest
{
ServiceName = "testservice",
Ip = "192.168.0.74",
Port = 5000
};
var res = await _namingClient.ModifyInstanceAsync(request).ConfigureAwait(false);
Assert.True(res);
}
[Fact]
public async Task ListInstances_Should_Succeed()
{
var request = new ListInstancesRequest
{
ServiceName = "testservice",
};
var res = await _namingClient.ListInstancesAsync(request).ConfigureAwait(false);
Assert.NotNull(res);
}
[Fact]
public async Task GetInstance_Should_Succeed()
{
var request = new GetInstanceRequest
{
ServiceName = "testservice",
Ip = "192.168.0.74",
Port = 9999,
};
var res = await _namingClient.GetInstanceAsync(request).ConfigureAwait(false);
Assert.NotNull(res);
}
[Fact]
public async Task SendHeartbeat_Should_Succeed()
{
var request = new SendHeartbeatRequest
{
ServiceName = "testservice",
BeatInfo = new BeatInfo
{
serviceName = "testservice",
ip = "192.168.0.74",
port = 9999,
}
};
var res = await _namingClient.SendHeartbeatAsync(request).ConfigureAwait(false);
Assert.True(res);
}
[Fact]
public async Task ModifyInstanceHealthStatus_Should_Succeed()
{
var request = new ModifyInstanceHealthStatusRequest
{
Ip = "192.168.0.74",
Port = 9999,
ServiceName = "testservice",
Healthy = false,
};
var res = await _namingClient.ModifyInstanceHealthStatusAsync(request).ConfigureAwait(false);
// 集群配置了健康检查时,该接口会返回错误
Assert.False(res);
}
}
}
*/
| 31.195876
| 105
| 0.518672
|
[
"Apache-2.0"
] |
SwingZhang/nacos-sdk-csharp
|
tests/Nacos.Tests/InstanceTest.cs
| 6,090
|
C#
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Utilities;
using System;
namespace Microsoft.MixedReality.Toolkit
{
/// <summary>
/// Attribute that defines the properties of a Mixed Reality Toolkit data provider.
/// </summary>
[AttributeUsage(System.AttributeTargets.Class, AllowMultiple = false)]
public class MixedRealityDataProviderAttribute : MixedRealityExtensionServiceAttribute
{
/// <summary>
/// The interface type of the IMixedRealityService for which the data provider is supported.
/// </summary>
public Type ServiceInterfaceType { get; }
public MixedRealityDataProviderAttribute(
Type serviceInterfaceType,
SupportedPlatforms runtimePlatforms,
string name = "",
string profilePath = "",
string packageFolder = "MixedRealityToolkit",
bool requiresProfile = false) : base(runtimePlatforms, name, profilePath, packageFolder, requiresProfile)
{
ServiceInterfaceType = serviceInterfaceType;
}
}
}
| 36.6875
| 118
| 0.662692
|
[
"MIT"
] |
ZealotWang-sudo/Project_Brahe
|
Asset Patch/com.microsoft.mixedreality.toolkit.foundation@2.5.1/Core/Attributes/MixedRealityDataProviderAttribute.cs
| 1,176
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using GoldKeyWebApi.Models;
namespace GoldKeyWebApi.Providers
{
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
private readonly string _publicClientId;
public ApplicationOAuthProvider(string publicClientId)
{
if (publicClientId == null)
{
throw new ArgumentNullException("publicClientId");
}
_publicClientId = publicClientId;
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "用户名或密码不正确。");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
context.AdditionalResponseParameters.Add(property.Key, property.Value);
}
return Task.FromResult<object>(null);
}
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
// 资源所有者密码凭据未提供客户端 ID。
if (context.ClientId == null)
{
context.Validated();
}
return Task.FromResult<object>(null);
}
public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
if (context.ClientId == _publicClientId)
{
Uri expectedRootUri = new Uri(context.Request.Uri, "/");
if (expectedRootUri.AbsoluteUri == context.RedirectUri)
{
context.Validated();
}
}
return Task.FromResult<object>(null);
}
public static AuthenticationProperties CreateProperties(string userName)
{
IDictionary<string, string> data = new Dictionary<string, string>
{
{ "userName", userName }
};
return new AuthenticationProperties(data);
}
}
}
| 34.346939
| 115
| 0.639037
|
[
"MIT"
] |
devide023/gkapi
|
GoldKeyWebApi/Providers/ApplicationOAuthProvider.cs
| 3,420
|
C#
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace IntroWPF
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 17.888889
| 42
| 0.701863
|
[
"MIT"
] |
bonbon2106/Csharp-Data-Visualization
|
YouTube/episodes/10 - Intro Animation/IntroWPF/App.xaml.cs
| 324
|
C#
|
#region Copyright and License
// Copyright 2010..2015 Alexander Reinert
//
// This file is part of the ARSoft.Tools.Net - C# DNS client/server and SPF Library (http://arsofttoolsnet.codeplex.com/)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System.Collections.Generic;
using MailTester.ARSoft.Tools.Net.Dns.DnsRecord;
namespace MailTester.ARSoft.Tools.Net.Dns
{
/// <summary>
/// Message returned as result to a dns query
/// </summary>
public class DnsMessage : DnsMessageBase
{
/// <summary>
/// Parses a the contents of a byte array as DnsMessage
/// </summary>
/// <param name="data">Buffer, that contains the message data</param>
/// <returns>A new instance of the DnsMessage class</returns>
public static DnsMessage Parse(byte[] data)
{
return Parse<DnsMessage>(data);
}
#region Header
/// <summary>
/// <para>Gets or sets the autoritive answer (AA) flag</para>
/// <para>
/// Defined in
/// <see cref="!:http://tools.ietf.org/html/rfc1035">RFC 1035</see>
/// </para>
/// </summary>
public bool IsAuthoritiveAnswer
{
get { return (Flags & 0x0400) != 0; }
set
{
if (value)
{
Flags |= 0x0400;
}
else
{
Flags &= 0xfbff;
}
}
}
/// <summary>
/// <para>Gets or sets the truncated response (TC) flag</para>
/// <para>
/// Defined in
/// <see cref="!:http://tools.ietf.org/html/rfc1035">RFC 1035</see>
/// </para>
/// </summary>
public bool IsTruncated
{
get { return (Flags & 0x0200) != 0; }
set
{
if (value)
{
Flags |= 0x0200;
}
else
{
Flags &= 0xfdff;
}
}
}
/// <summary>
/// <para>Gets or sets the recursion desired (RD) flag</para>
/// <para>
/// Defined in
/// <see cref="!:http://tools.ietf.org/html/rfc1035">RFC 1035</see>
/// </para>
/// </summary>
public bool IsRecursionDesired
{
get { return (Flags & 0x0100) != 0; }
set
{
if (value)
{
Flags |= 0x0100;
}
else
{
Flags &= 0xfeff;
}
}
}
/// <summary>
/// <para>Gets or sets the recursion allowed (RA) flag</para>
/// <para>
/// Defined in
/// <see cref="!:http://tools.ietf.org/html/rfc1035">RFC 1035</see>
/// </para>
/// </summary>
public bool IsRecursionAllowed
{
get { return (Flags & 0x0080) != 0; }
set
{
if (value)
{
Flags |= 0x0080;
}
else
{
Flags &= 0xff7f;
}
}
}
/// <summary>
/// <para>Gets or sets the authentic data (AD) flag</para>
/// <para>
/// Defined in
/// <see cref="!:http://tools.ietf.org/html/rfc4035">RFC 4035</see>
/// </para>
/// </summary>
public bool IsAuthenticData
{
get { return (Flags & 0x0020) != 0; }
set
{
if (value)
{
Flags |= 0x0020;
}
else
{
Flags &= 0xffdf;
}
}
}
/// <summary>
/// <para>Gets or sets the checking disabled (CD) flag</para>
/// <para>
/// Defined in
/// <see cref="!:http://tools.ietf.org/html/rfc4035">RFC 4035</see>
/// </para>
/// </summary>
public bool IsCheckingDisabled
{
get { return (Flags & 0x0010) != 0; }
set
{
if (value)
{
Flags |= 0x0010;
}
else
{
Flags &= 0xffef;
}
}
}
#endregion
/// <summary>
/// Gets or sets the entries in the question section
/// </summary>
public new List<DnsQuestion> Questions
{
get { return base.Questions; }
set { base.Questions = (value ?? new List<DnsQuestion>()); }
}
/// <summary>
/// Gets or sets the entries in the answer records section
/// </summary>
public new List<DnsRecordBase> AnswerRecords
{
get { return base.AnswerRecords; }
set { base.AnswerRecords = (value ?? new List<DnsRecordBase>()); }
}
/// <summary>
/// Gets or sets the entries in the authority records section
/// </summary>
public new List<DnsRecordBase> AuthorityRecords
{
get { return base.AuthorityRecords; }
set { base.AuthorityRecords = (value ?? new List<DnsRecordBase>()); }
}
internal override bool IsTcpUsingRequested
{
get { return (Questions.Count > 0) && ((Questions[0].RecordType == RecordType.Axfr) || (Questions[0].RecordType == RecordType.Ixfr)); }
}
internal override bool IsTcpResendingRequested
{
get { return IsTruncated; }
}
internal override bool IsTcpNextMessageWaiting(bool isSubsequentResponseMessage)
{
if (isSubsequentResponseMessage)
{
return (AnswerRecords.Count > 0) && (AnswerRecords[AnswerRecords.Count - 1].RecordType != RecordType.Soa);
}
if (Questions.Count == 0)
return false;
if ((Questions[0].RecordType != RecordType.Axfr) && (Questions[0].RecordType != RecordType.Ixfr))
return false;
return (AnswerRecords.Count > 0)
&& (AnswerRecords[0].RecordType == RecordType.Soa)
&& ((AnswerRecords.Count == 1) || (AnswerRecords[AnswerRecords.Count - 1].RecordType != RecordType.Soa));
}
}
}
| 23.713675
| 138
| 0.598847
|
[
"MIT"
] |
robledop/MailTester
|
MailTester/MailTester/ARSoft.Tools.Net/Dns/DnsMessage.cs
| 5,551
|
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Internal.NativeFormat;
namespace Internal.TypeSystem
{
[Flags]
public enum MethodSignatureFlags
{
None = 0x0000,
// TODO: Generic, etc.
UnmanagedCallingConventionMask = 0x000F,
UnmanagedCallingConventionCdecl = 0x0001,
UnmanagedCallingConventionStdCall = 0x0002,
UnmanagedCallingConventionThisCall = 0x0003,
CallingConventionVarargs = 0x0005,
UnmanagedCallingConvention = 0x0009,
Static = 0x0010,
}
public enum EmbeddedSignatureDataKind
{
RequiredCustomModifier = 0,
OptionalCustomModifier = 1
}
public struct EmbeddedSignatureData
{
public string index;
public EmbeddedSignatureDataKind kind;
public TypeDesc type;
}
/// <summary>
/// Represents the parameter types, the return type, and flags of a method.
/// </summary>
public sealed partial class MethodSignature : TypeSystemEntity
{
internal MethodSignatureFlags _flags;
internal int _genericParameterCount;
internal TypeDesc _returnType;
internal TypeDesc[] _parameters;
internal EmbeddedSignatureData[] _embeddedSignatureData;
// Value of <see cref="EmbeddedSignatureData.index" /> for any custom modifiers on the return type
public const string IndexOfCustomModifiersOnReturnType = "0.1.1.1";
// Value of <see cref="EmbeddedSignatureData.index" /> for any custom modifiers on
// SomeStruct when SomeStruct *, or SomeStruct & is the type of a parameter or return type
// Parameter index 0 represents the return type, and indices 1-n represent the parameters to the signature
public static string GetIndexOfCustomModifierOnPointedAtTypeByParameterIndex(int parameterIndex)
{
return $"0.1.1.2.{(parameterIndex + 1).ToStringInvariant()}.1";
}
public MethodSignature(MethodSignatureFlags flags, int genericParameterCount, TypeDesc returnType, TypeDesc[] parameters, EmbeddedSignatureData[] embeddedSignatureData = null)
{
_flags = flags;
_genericParameterCount = genericParameterCount;
_returnType = returnType;
_parameters = parameters;
_embeddedSignatureData = embeddedSignatureData;
Debug.Assert(parameters != null, "Parameters must not be null");
}
public MethodSignature ApplySubstitution(Instantiation substitution)
{
if (substitution.IsNull)
return this;
bool needsNewMethodSignature = false;
TypeDesc[] newParameters = _parameters; // Re-use existing array until conflict appears
TypeDesc returnTypeNew = _returnType.InstantiateSignature(substitution, default(Instantiation));
if (returnTypeNew != _returnType)
{
needsNewMethodSignature = true;
newParameters = (TypeDesc[])_parameters.Clone();
}
for (int i = 0; i < newParameters.Length; i++)
{
TypeDesc newParameter = newParameters[i].InstantiateSignature(substitution, default(Instantiation));
if (newParameter != newParameters[i])
{
if (!needsNewMethodSignature)
{
needsNewMethodSignature = true;
newParameters = (TypeDesc[])_parameters.Clone();
}
newParameters[i] = newParameter;
}
}
if (needsNewMethodSignature)
{
return new MethodSignature(_flags, _genericParameterCount, returnTypeNew, newParameters, _embeddedSignatureData);
}
else
{
return this;
}
}
public MethodSignatureFlags Flags
{
get
{
return _flags;
}
}
public bool IsStatic
{
get
{
return (_flags & MethodSignatureFlags.Static) != 0;
}
}
public int GenericParameterCount
{
get
{
return _genericParameterCount;
}
}
public TypeDesc ReturnType
{
get
{
return _returnType;
}
}
/// <summary>
/// Gets the parameter type at the specified index.
/// </summary>
[IndexerName("Parameter")]
public TypeDesc this[int index]
{
get
{
return _parameters[index];
}
}
/// <summary>
/// Gets the number of parameters of this method signature.
/// </summary>
public int Length
{
get
{
return _parameters.Length;
}
}
public bool HasEmbeddedSignatureData
{
get
{
return _embeddedSignatureData != null;
}
}
public EmbeddedSignatureData[] GetEmbeddedSignatureData()
{
if ((_embeddedSignatureData == null) || (_embeddedSignatureData.Length == 0))
return null;
return (EmbeddedSignatureData[])_embeddedSignatureData.Clone();
}
public bool Equals(MethodSignature otherSignature)
{
return Equals(otherSignature, allowCovariantReturn: false);
}
public bool EqualsWithCovariantReturnType(MethodSignature otherSignature)
{
return Equals(otherSignature, allowCovariantReturn: true);
}
private bool Equals(MethodSignature otherSignature, bool allowCovariantReturn)
{
// TODO: Generics, etc.
if (this._flags != otherSignature._flags)
return false;
if (this._genericParameterCount != otherSignature._genericParameterCount)
return false;
if (this._returnType != otherSignature._returnType)
{
if (!allowCovariantReturn)
return false;
if (!otherSignature._returnType.IsCompatibleWith(this._returnType))
return false;
}
if (this._parameters.Length != otherSignature._parameters.Length)
return false;
for (int i = 0; i < this._parameters.Length; i++)
{
if (this._parameters[i] != otherSignature._parameters[i])
return false;
}
if (this._embeddedSignatureData == null && otherSignature._embeddedSignatureData == null)
{
return true;
}
if (this._embeddedSignatureData != null && otherSignature._embeddedSignatureData != null)
{
if (this._embeddedSignatureData.Length != otherSignature._embeddedSignatureData.Length)
{
return false;
}
for (int i = 0; i < this._embeddedSignatureData.Length; i++)
{
if (this._embeddedSignatureData[i].index != otherSignature._embeddedSignatureData[i].index)
return false;
if (this._embeddedSignatureData[i].kind != otherSignature._embeddedSignatureData[i].kind)
return false;
if (this._embeddedSignatureData[i].type != otherSignature._embeddedSignatureData[i].type)
return false;
}
return true;
}
return false;
}
public override bool Equals(object obj)
{
return obj is MethodSignature && Equals((MethodSignature)obj);
}
public override int GetHashCode()
{
return TypeHashingAlgorithms.ComputeMethodSignatureHashCode(_returnType.GetHashCode(), _parameters);
}
public SignatureEnumerator GetEnumerator()
{
return new SignatureEnumerator(this);
}
public override TypeSystemContext Context => _returnType.Context;
public struct SignatureEnumerator
{
private int _index;
private MethodSignature _signature;
public SignatureEnumerator(MethodSignature signature)
{
_signature = signature;
_index = -1;
}
public TypeDesc Current => _signature[_index];
public bool MoveNext()
{
_index++;
return _index < _signature.Length;
}
}
}
/// <summary>
/// Helper structure for building method signatures by cloning an existing method signature.
/// </summary>
/// <remarks>
/// This can potentially avoid array allocation costs for allocating the parameter type list.
/// </remarks>
public struct MethodSignatureBuilder
{
private MethodSignature _template;
private MethodSignatureFlags _flags;
private int _genericParameterCount;
private TypeDesc _returnType;
private TypeDesc[] _parameters;
private EmbeddedSignatureData[] _customModifiers;
public MethodSignatureBuilder(MethodSignature template)
{
_template = template;
_flags = template._flags;
_genericParameterCount = template._genericParameterCount;
_returnType = template._returnType;
_parameters = template._parameters;
_customModifiers = template._embeddedSignatureData;
}
public MethodSignatureFlags Flags
{
set
{
_flags = value;
}
}
public TypeDesc ReturnType
{
set
{
_returnType = value;
}
}
[System.Runtime.CompilerServices.IndexerName("Parameter")]
public TypeDesc this[int index]
{
set
{
if (_parameters[index] == value)
return;
if (_template != null && _parameters == _template._parameters)
{
TypeDesc[] parameters = new TypeDesc[_parameters.Length];
for (int i = 0; i < parameters.Length; i++)
parameters[i] = _parameters[i];
_parameters = parameters;
}
_parameters[index] = value;
}
}
public int Length
{
set
{
_parameters = new TypeDesc[value];
_template = null;
}
}
public MethodSignature ToSignature()
{
if (_template == null ||
_flags != _template._flags ||
_genericParameterCount != _template._genericParameterCount ||
_returnType != _template._returnType ||
_parameters != _template._parameters)
{
_template = new MethodSignature(_flags, _genericParameterCount, _returnType, _parameters, _customModifiers);
}
return _template;
}
}
/// <summary>
/// Represents the fundamental base type for all methods within the type system.
/// </summary>
public abstract partial class MethodDesc : TypeSystemEntity
{
#pragma warning disable CA1825 // avoid Array.Empty<T>() instantiation for TypeLoader
public static readonly MethodDesc[] EmptyMethods = new MethodDesc[0];
#pragma warning restore CA1825
private int _hashcode;
/// <summary>
/// Allows a performance optimization that skips the potentially expensive
/// construction of a hash code if a hash code has already been computed elsewhere.
/// Use to allow objects to have their hashcode computed
/// independently of the allocation of a MethodDesc object
/// For instance, compute the hashcode when looking up the object,
/// then when creating the object, pass in the hashcode directly.
/// The hashcode specified MUST exactly match the algorithm implemented
/// on this type normally.
/// </summary>
protected void SetHashCode(int hashcode)
{
_hashcode = hashcode;
Debug.Assert(hashcode == ComputeHashCode());
}
public sealed override int GetHashCode()
{
if (_hashcode != 0)
return _hashcode;
return AcquireHashCode();
}
private int AcquireHashCode()
{
_hashcode = ComputeHashCode();
return _hashcode;
}
/// <summary>
/// Compute HashCode. Should only be overriden by a MethodDesc that represents an instantiated method.
/// </summary>
protected virtual int ComputeHashCode()
{
return TypeHashingAlgorithms.ComputeMethodHashCode(OwningType.GetHashCode(), TypeHashingAlgorithms.ComputeNameHashCode(Name));
}
public override bool Equals(object o)
{
// Its only valid to compare two MethodDescs in the same context
Debug.Assert(object.ReferenceEquals(o, null) || !(o is MethodDesc) || object.ReferenceEquals(((MethodDesc)o).Context, this.Context));
return object.ReferenceEquals(this, o);
}
/// <summary>
/// Gets the type that owns this method. This will be a <see cref="DefType"/> or
/// an <see cref="ArrayType"/>.
/// </summary>
public abstract TypeDesc OwningType
{
get;
}
/// <summary>
/// Gets the signature of the method.
/// </summary>
public abstract MethodSignature Signature
{
get;
}
/// <summary>
/// Gets the generic instantiation information of this method.
/// For generic definitions, retrieves the generic parameters of the method.
/// For generic instantiation, retrieves the generic arguments of the method.
/// </summary>
public virtual Instantiation Instantiation
{
get
{
return Instantiation.Empty;
}
}
/// <summary>
/// Gets a value indicating whether this method has a generic instantiation.
/// This will be true for generic method instantiations and generic definitions.
/// </summary>
public bool HasInstantiation
{
get
{
return this.Instantiation.Length != 0;
}
}
/// <summary>
/// Gets a value indicating whether this method is an instance constructor.
/// </summary>
public bool IsConstructor
{
get
{
// TODO: Precise check
// TODO: Cache?
return this.Name == ".ctor";
}
}
/// <summary>
/// Gets a value indicating whether this is a public parameterless instance constructor
/// on a non-abstract type.
/// </summary>
public virtual bool IsDefaultConstructor
{
get
{
return OwningType.GetDefaultConstructor() == this;
}
}
/// <summary>
/// Gets a value indicating whether this method is a static constructor.
/// </summary>
public bool IsStaticConstructor
{
get
{
return this == this.OwningType.GetStaticConstructor();
}
}
/// <summary>
/// Gets the name of the method as specified in the metadata.
/// </summary>
public virtual string Name
{
get
{
return null;
}
}
/// <summary>
/// Gets a value indicating whether the method is virtual.
/// </summary>
public virtual bool IsVirtual
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether this virtual method should not override any
/// virtual methods defined in any of the base classes.
/// </summary>
public virtual bool IsNewSlot
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether this virtual method needs to be overriden
/// by all non-abstract classes deriving from the method's owning type.
/// </summary>
public virtual bool IsAbstract
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating that this method cannot be overriden.
/// </summary>
public virtual bool IsFinal
{
get
{
return false;
}
}
public abstract bool HasCustomAttribute(string attributeNamespace, string attributeName);
/// <summary>
/// Retrieves the uninstantiated form of the method on the method's <see cref="OwningType"/>.
/// For generic methods, this strips method instantiation. For non-generic methods, returns 'this'.
/// To also strip instantiation of the owning type, use <see cref="GetTypicalMethodDefinition"/>.
/// </summary>
public virtual MethodDesc GetMethodDefinition()
{
return this;
}
/// <summary>
/// Gets a value indicating whether this is a method definition. This property
/// is true for non-generic methods and for uninstantiated generic methods.
/// </summary>
public bool IsMethodDefinition
{
get
{
return GetMethodDefinition() == this;
}
}
/// <summary>
/// Retrieves the generic definition of the method on the generic definition of the owning type.
/// To only uninstantiate the method without uninstantiating the owning type, use <see cref="GetMethodDefinition"/>.
/// </summary>
public virtual MethodDesc GetTypicalMethodDefinition()
{
return this;
}
/// <summary>
/// Gets a value indicating whether this is a typical definition. This property is true
/// if neither the owning type, nor the method are instantiated.
/// </summary>
public bool IsTypicalMethodDefinition
{
get
{
return GetTypicalMethodDefinition() == this;
}
}
/// <summary>
/// Gets a value indicating whether this is an uninstantiated generic method.
/// </summary>
public bool IsGenericMethodDefinition
{
get
{
return HasInstantiation && IsMethodDefinition;
}
}
public bool IsFinalizer
{
get
{
TypeDesc owningType = OwningType;
return (owningType.IsObject && Name == "Finalize") || (owningType.HasFinalizer && owningType.GetFinalizer() == this);
}
}
public virtual MethodDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation)
{
Instantiation instantiation = Instantiation;
TypeDesc[] clone = null;
for (int i = 0; i < instantiation.Length; i++)
{
TypeDesc uninst = instantiation[i];
TypeDesc inst = uninst.InstantiateSignature(typeInstantiation, methodInstantiation);
if (inst != uninst)
{
if (clone == null)
{
clone = new TypeDesc[instantiation.Length];
for (int j = 0; j < clone.Length; j++)
{
clone[j] = instantiation[j];
}
}
clone[i] = inst;
}
}
MethodDesc method = this;
TypeDesc owningType = method.OwningType;
TypeDesc instantiatedOwningType = owningType.InstantiateSignature(typeInstantiation, methodInstantiation);
if (owningType != instantiatedOwningType)
{
method = Context.GetMethodForInstantiatedType(method.GetTypicalMethodDefinition(), (InstantiatedType)instantiatedOwningType);
if (clone == null && instantiation.Length != 0)
return Context.GetInstantiatedMethod(method, instantiation);
}
return (clone == null) ? method : Context.GetInstantiatedMethod(method.GetMethodDefinition(), new Instantiation(clone));
}
}
}
| 32.35994
| 183
| 0.549821
|
[
"MIT"
] |
Emzi0767/dotnet-runtime
|
src/coreclr/src/tools/Common/TypeSystem/Common/MethodDesc.cs
| 21,487
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JX.Core;
using JX.Core.Entity;
namespace JX.Core
{
/// <summary>
/// 数据库表:FlowProcess 的仓储接口.
/// </summary>
public partial interface IFlowProcessRepository : IRepository<FlowProcess>
{
}
}
| 18.6875
| 75
| 0.745819
|
[
"Apache-2.0"
] |
lixiong24/IPS2.1
|
CodeSmith/output/IRepositories/IFlowProcessRepository.cs
| 321
|
C#
|
using System;
using System.Linq;
using System.Xml.Linq;
using Grynwald.MdDocs.ApiReference.Model;
using Grynwald.MdDocs.ApiReference.Model.XmlDocs;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;
namespace Grynwald.MdDocs.ApiReference.Test.Model.XmlDocs
{
public class XmlDocsReaderTest
{
private static ListElement ReadList(XDocument document)
{
var xmlDocsReader = new XmlDocsReader(NullLogger.Instance, document, Array.Empty<TypeId>());
var members = xmlDocsReader.Read();
Assert.Single(members);
Assert.Single(members.Single().Summary.Elements);
var element = members.Single().Summary.Elements.Single();
Assert.IsType<ListElement>(element);
var list = (ListElement)element;
return list;
}
private static XDocument GetDocumentFromListXml(string listXml)
{
return XDocument.Parse($@"<?xml version=""1.0""?>
<doc>
<assembly>
<name>AssemblyName</name>
</assembly>
<members>
<member name=""T:TypeName"">
<summary>
{listXml}
</summary>
</member>
</members>
</doc>");
}
private static XDocument GetDocumentFromListItemXml(string listItemXml)
{
return GetDocumentFromListXml(
$@"<list type=""bullet"">
<item>
{listItemXml}
</item>
</list>"
);
}
[Theory]
[InlineData(@"<list></list>", ListType.None, false, 0)]
[InlineData(@"<list type=""bullet""></list>", ListType.Bullet, false, 0)]
[InlineData(@"<list type=""number""></list>", ListType.Number, false, 0)]
[InlineData(@"<list type=""table""></list>", ListType.Table, false, 0)]
[InlineData(
@"<list type=""bullet"">
<item>
<description>description</description>
</item>
</list>",
ListType.Bullet, false, 1)]
[InlineData(
@"<list type=""bullet"">
<item>
<description>description</description>
</item>
<item>
<description>description</description>
</item>
</list>",
ListType.Bullet, false, 2)]
[InlineData(
@"<list type=""bullet"">
<listheader>
<description>description</description>
</listheader>
<item>
<description>description</description>
</item>
</list>",
ListType.Bullet, true, 1)]
public void Lists_are_parsed_correctly(string xml, ListType expectedListType, bool expectHeader, int expectedNumberOfListItems)
{
// ARRANGE
var document = GetDocumentFromListXml(xml);
// ACT
var list = ReadList(document);
// ASSERT
Assert.Equal(expectedListType, list.Type);
if (expectHeader)
Assert.NotNull(list.ListHeader);
else
Assert.Null(list.ListHeader);
Assert.Equal(expectedNumberOfListItems, list.Items.Count);
}
[Theory]
[InlineData("")]
[InlineData("<someElement></someElement>")]
[InlineData("<term></term>")]
public void Invalid_list_items_are_ignored(string xml)
{
// ARRANGE
var document = GetDocumentFromListItemXml(xml);
// ACT
var list = ReadList(document);
// ASSERT
Assert.Empty(list.Items);
}
[Theory]
[InlineData("<description>TestDescription</description>", false, true)]
[InlineData("<term>TestTerm</term><description>TestDescription</description>", true, true)]
public void List_items_are_parsed_correctly(string xml, bool expectTerm, bool expectDescription)
{
// ARRANGE
var document = GetDocumentFromListItemXml(xml);
// ACT
var list = ReadList(document);
// ASSERT
Assert.Single(list.Items);
var listItem = list.Items.Single();
Assert.NotNull(listItem.Term);
if (expectTerm)
Assert.False(listItem.Term.IsEmpty);
else
Assert.True(listItem.Term.IsEmpty);
if (expectDescription)
Assert.NotNull(listItem.Description);
else
Assert.Null(listItem.Description);
}
[Fact]
public void ReadTextBlock_returns_the_expected_elements_01()
{
var xml = @" <para>
Similar pages are also generated for interfaces, structs
and enums
</para> ";
ReadTextBlock_returns_the_expected_elements(
xml,
new TextElement("Similar pages are also generated for interfaces, structs and enums")
);
}
[Fact]
public void ReadTextBlock_returns_the_expected_elements_02()
{
var xml = @" <para>
<see cref=""T:DemoProject.DemoStruct"" />
</para> ";
ReadTextBlock_returns_the_expected_elements(
xml,
new SeeElement(MemberId.Parse("T:DemoProject.DemoStruct", Array.Empty<TypeId>()))
);
}
[Fact]
public void ReadTextBlock_returns_the_expected_elements_03()
{
var xml = @" <para>
Similar pages are also generated for interfaces, structs (see <see cref=""T:DemoProject.DemoStruct""/>)
and enums
</para> ";
ReadTextBlock_returns_the_expected_elements(
xml,
new TextElement("Similar pages are also generated for interfaces, structs (see "),
new SeeElement(MemberId.Parse("T:DemoProject.DemoStruct", Array.Empty<TypeId>())),
new TextElement(") and enums")
);
}
[Fact]
public void ReadTextBlock_returns_the_expected_elements_04()
{
var xml = @"<para>Lorem ipsum dolor sit amet.</para>";
ReadTextBlock_returns_the_expected_elements(
xml,
new TextElement("Lorem ipsum dolor sit amet.")
);
}
[Fact]
public void ReadTextBlock_returns_the_expected_elements_05()
{
var xml = @"<para><see cref=""T:DemoProject.DemoClass"" /></para>";
ReadTextBlock_returns_the_expected_elements(
xml,
new SeeElement(MemberId.Parse("T:DemoProject.DemoClass", Array.Empty<TypeId>()))
);
}
[Fact]
public void ReadTextBlock_returns_the_expected_elements_06()
{
var xml = @"<para><see cref=""T:DemoProject.DemoClass"">Lorem ipsum dolor sit amet.</see></para>";
ReadTextBlock_returns_the_expected_elements(
xml,
new SeeElement(
MemberId.Parse("T:DemoProject.DemoClass", Array.Empty<TypeId>()),
new TextBlock(new[]
{
new TextElement("Lorem ipsum dolor sit amet.")
}))
);
}
private void ReadTextBlock_returns_the_expected_elements(string xml, params Element[] expectedElements)
{
// ARRANGE
var sut = new XmlDocsReader(NullLogger.Instance, new XDocument(), Array.Empty<TypeId>());
var expected = new TextBlock(expectedElements);
// ACT
var actual = sut.ReadTextBlock(XElement.Parse(xml));
// ASSERT
Assert.Equal(expected, actual);
}
[Fact]
public void ReadTextBlock_correctly_reads_see_elements_01()
{
var xml = @"<see cref=""T:SomeNamespace.SomeClass"" />";
var expected = new SeeElement(MemberId.Parse("T:SomeNamespace.SomeClass", Array.Empty<TypeId>()));
ReadTextBlock_correctly_reads_see_elements(xml, expected);
}
[Fact]
public void ReadTextBlock_correctly_reads_see_elements_02()
{
var xml = @"<see cref=""T:SomeNamespace.SomeClass"">Lorem ipsum dolor sit amet.</see>";
var expected = new SeeElement(
MemberId.Parse("T:SomeNamespace.SomeClass", Array.Empty<TypeId>()),
new TextBlock(new[] { new TextElement("Lorem ipsum dolor sit amet.") }));
ReadTextBlock_correctly_reads_see_elements(xml, expected);
}
[Fact]
public void ReadTextBlock_correctly_reads_see_elements_03()
{
var xml = @"<see href=""http://example.com"" />";
var expected = new SeeElement(new Uri("http://example.com"));
ReadTextBlock_correctly_reads_see_elements(xml, expected);
}
[Fact]
public void ReadTextBlock_correctly_reads_see_elements_04()
{
var xml = @"<see href=""http://example.com"">Lorem ipsum dolor sit amet.</see>";
var expected = new SeeElement(
new Uri("http://example.com"),
new TextBlock(new[] { new TextElement("Lorem ipsum dolor sit amet.") }));
ReadTextBlock_correctly_reads_see_elements(xml, expected);
}
[Fact]
public void ReadTextBlock_correctly_reads_see_elements_05()
{
var xml = @"<see href=""http://example.com"" cref=""T:SomeNamespace.SomeClass"" />";
var expected = new SeeElement(MemberId.Parse("T:SomeNamespace.SomeClass", Array.Empty<TypeId>()));
ReadTextBlock_correctly_reads_see_elements(xml, expected);
}
[Fact]
public void ReadTextBlock_correctly_reads_see_elements_06()
{
var xml = @"<see href=""http://example.com"" cref=""T:SomeNamespace.SomeClass"">Lorem ipsum dolor sit amet.</see>";
var expected = new SeeElement(
MemberId.Parse("T:SomeNamespace.SomeClass", Array.Empty<TypeId>()),
new TextBlock(new[] { new TextElement("Lorem ipsum dolor sit amet.") }));
ReadTextBlock_correctly_reads_see_elements(xml, expected);
}
private void ReadTextBlock_correctly_reads_see_elements(string xml, SeeElement expected)
{
// ARRANGE
xml = $@"<para>{xml}</para>";
var sut = new XmlDocsReader(NullLogger.Instance, new XDocument(), Array.Empty<TypeId>());
// ACT
var textBlock = sut.ReadTextBlock(XElement.Parse(xml));
// ASSERT
var element = Assert.Single(textBlock.Elements);
var seeElement = Assert.IsType<SeeElement>(element);
Assert.Equal(expected, seeElement);
}
[Fact]
public void ReadMemberContent_correctly_parses_seealso_elements_01()
{
var xml = @"<seealso cref=""T:SomeNamespace.SomeClass"" />";
var expected = new SeeAlsoElement(MemberId.Parse("T:SomeNamespace.SomeClass", Array.Empty<TypeId>()));
ReadMemberContent_correctly_parses_seealso_elements(xml, expected);
}
[Fact]
public void ReadMemberContent_correctly_parses_seealso_elements_02()
{
var xml = @"<seealso cref=""T:SomeNamespace.SomeClass"">Lorem ipsum dolor sit ament.</seealso>";
var expected = new SeeAlsoElement(
MemberId.Parse("T:SomeNamespace.SomeClass", Array.Empty<TypeId>()),
new TextBlock(new[]
{
new TextElement("Lorem ipsum dolor sit ament.")
}));
ReadMemberContent_correctly_parses_seealso_elements(xml, expected);
}
[Fact]
public void ReadMemberContent_correctly_parses_seealso_elements_03()
{
var xml = @"<seealso href=""http://example.com"" />";
var expected = new SeeAlsoElement(new Uri("http://example.com"));
ReadMemberContent_correctly_parses_seealso_elements(xml, expected);
}
[Fact]
public void ReadMemberContent_correctly_parses_seealso_elements_04()
{
var xml = @"<seealso href=""http://example.com"">Lorem ipsum dolor sit ament.</seealso>";
var expected = new SeeAlsoElement(
new Uri("http://example.com"),
new TextBlock(new[]
{
new TextElement("Lorem ipsum dolor sit ament.")
}));
ReadMemberContent_correctly_parses_seealso_elements(xml, expected);
}
[Fact]
public void ReadMemberContent_correctly_parses_seealso_elements_05()
{
var xml = @"<seealso cref=""T:SomeNamespace.SomeClass"" href=""http://example.com"" />";
var expected = new SeeAlsoElement(MemberId.Parse("T:SomeNamespace.SomeClass", Array.Empty<TypeId>()));
ReadMemberContent_correctly_parses_seealso_elements(xml, expected);
}
[Fact]
public void ReadMemberContent_correctly_parses_seealso_elements_06()
{
var xml = @"<seealso cref=""T:SomeNamespace.SomeClass"" href=""http://example.com"">Lorem ipsum dolor sit ament.</seealso>";
var expected = new SeeAlsoElement(
MemberId.Parse("T:SomeNamespace.SomeClass", Array.Empty<TypeId>()),
new TextBlock(new[]
{
new TextElement("Lorem ipsum dolor sit ament.")
}));
ReadMemberContent_correctly_parses_seealso_elements(xml, expected);
}
private void ReadMemberContent_correctly_parses_seealso_elements(string xml, SeeAlsoElement expected)
{
// ARRANGE
xml = $@"<container>{xml}</container>";
var sut = new XmlDocsReader(NullLogger.Instance, new XDocument(), Array.Empty<TypeId>());
var memberElement = new MemberElement(MemberId.Parse("T:DemoProject.DemoClass", Array.Empty<TypeId>()));
// ACT
sut.ReadMemberContent(XElement.Parse(xml), memberElement);
// ASSERT
var actual = Assert.Single(memberElement.SeeAlso);
Assert.Equal(expected, actual);
}
}
}
| 35.140143
| 136
| 0.557861
|
[
"MIT"
] |
ap0llo/mddocs
|
src/MdDocs.ApiReference.Test/Model/XmlDocs/XmlDocsReaderTest.cs
| 14,796
|
C#
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Xunit;
namespace Microsoft.AspNetCore.Cors.Infrastructure
{
public class CorsEndpointConventionBuilderExtensionsTests
{
[Fact]
public void WithCorsPolicy_Name_MetadataAdded()
{
// Arrange
var testConventionBuilder = new TestEndpointConventionBuilder();
// Act
testConventionBuilder.WithCorsPolicy("TestPolicyName");
// Assert
var addCorsPolicy = Assert.Single(testConventionBuilder.Conventions);
var endpointModel = new TestEndpointBuilder();
addCorsPolicy(endpointModel);
var endpoint = endpointModel.Build();
var metadata = endpoint.Metadata.GetMetadata<IEnableCorsAttribute>();
Assert.NotNull(metadata);
Assert.Equal("TestPolicyName", metadata.PolicyName);
}
[Fact]
public void WithCorsPolicy_Policy_MetadataAdded()
{
// Arrange
var testConventionBuilder = new TestEndpointConventionBuilder();
// Act
testConventionBuilder.WithCorsPolicy(builder => builder.AllowAnyOrigin());
// Assert
var addCorsPolicy = Assert.Single(testConventionBuilder.Conventions);
var endpointBuilder = new TestEndpointBuilder();
addCorsPolicy(endpointBuilder);
var endpoint = endpointBuilder.Build();
var metadata = endpoint.Metadata.GetMetadata<ICorsPolicyMetadata>();
Assert.NotNull(metadata);
Assert.NotNull(metadata.Policy);
Assert.True(metadata.Policy.AllowAnyOrigin);
}
private class TestEndpointBuilder : EndpointBuilder
{
public override Endpoint Build()
{
return new Endpoint(RequestDelegate, new EndpointMetadataCollection(Metadata), DisplayName);
}
}
private class TestEndpointConventionBuilder : IEndpointConventionBuilder
{
public IList<Action<EndpointBuilder>> Conventions { get; } = new List<Action<EndpointBuilder>>();
public void Add(Action<EndpointBuilder> convention)
{
Conventions.Add(convention);
}
}
}
}
| 33.571429
| 111
| 0.642166
|
[
"Apache-2.0"
] |
CBaud/AspNetCore
|
src/Middleware/CORS/test/UnitTests/CorsEndpointConventionBuilderExtensionsTests.cs
| 2,585
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
namespace _02.Base_N_to_base_10
{
class Base_N_to_base_10
{
static void Main(string[] args)
{
var input = Console.ReadLine().Split();
string number = input[1].ToString();
BigInteger n = 1;
BigInteger r = 0;
for (int i = number.Length - 1; i >= 0; --i)
{
r += n * (number[i] - '0');
n *= int.Parse(input[0]);
}
Console.WriteLine(r);
}
}
}
| 22.884615
| 56
| 0.490756
|
[
"MIT"
] |
zrusev/SoftUni_2016
|
02. Programming Fundamentals - Jan 2017/09. Strings/02. Base-N to base-10/02. Base-N to base-10/Base_N_to_base_10.cs
| 597
|
C#
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Threading;
using System.Windows.Input;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using AndroidX.RecyclerView.Widget;
using Sharpnado.CollectionView.Droid.Helpers;
using Sharpnado.CollectionView.Helpers;
using Sharpnado.CollectionView.RenderedViews;
using Sharpnado.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using IList = System.Collections.IList;
using View = Android.Views.View;
namespace Sharpnado.CollectionView.Droid.Renderers
{
public partial class CollectionViewRenderer
{
private class ViewHolder : RecyclerView.ViewHolder
{
private readonly ViewCell _viewCell;
private readonly ICommand _tapCommand;
public ViewHolder(IntPtr javaReference, JniHandleOwnership transfer)
: base(javaReference, transfer)
{
}
public ViewHolder(View itemView, ViewCell viewCell, ICommand tapCommand)
: base(itemView)
{
_viewCell = viewCell;
_tapCommand = tapCommand;
if (_tapCommand != null)
{
ItemView.Clickable = true;
ItemView.Click += OnItemViewClick;
AddRiple();
}
}
public ViewCell ViewCell => _viewCell;
public object BindingContext => ViewCell?.BindingContext;
public void Bind(object context, CollectionView.RenderedViews.CollectionView parent)
{
_viewCell.BindingContext = context;
_viewCell.Parent = parent;
}
private void OnItemViewClick(object sender, EventArgs e)
{
if (_tapCommand.CanExecute(null))
{
_tapCommand.Execute(BindingContext);
}
}
private void AddRiple()
{
var outValue = new TypedValue();
var context = ItemView.Context;
context.Theme.ResolveAttribute(Android.Resource.Attribute.SelectableItemBackground, outValue, true);
ItemView.SetBackgroundResource(outValue.ResourceId);
}
}
private class EmptyViewHolder : RecyclerView.ViewHolder
{
public EmptyViewHolder(IntPtr javaReference, JniHandleOwnership transfer)
: base(javaReference, transfer)
{
}
public EmptyViewHolder(Context context)
: base(new View(context))
{
}
}
private class RecycleViewAdapter : RecyclerView.Adapter
{
private const string Tag = "Adapter";
private readonly Context _context;
private readonly CollectionView.RenderedViews.CollectionView _element;
private readonly WeakReference<RecyclerView> _weakParentView;
private readonly WeakReference<CollectionViewRenderer> _weakNativeView;
private readonly IEnumerable _elementItemsSource;
private readonly INotifyCollectionChanged _notifyCollectionChanged;
private readonly List<object> _dataSource;
private readonly ViewHolderQueue _viewHolderQueue;
private readonly List<DataTemplate> _dataTemplates = new List<DataTemplate>(3);
private readonly Dictionary<int, double> _sizeByType = new Dictionary<int, double>();
private readonly List<WeakReference<ViewCell>> _formsViews;
private CancellationTokenSource _enableDragAndDropCts;
private bool _collectionChangedBackfire;
private bool _isDisposed;
private int _currentMaxPosition = -1;
public RecycleViewAdapter(IntPtr javaReference, JniHandleOwnership transfer)
: base(javaReference, transfer)
{
}
public RecycleViewAdapter(CollectionView.RenderedViews.CollectionView element, CollectionViewRenderer nativeView, RecyclerView parentView, Context context)
{
_element = element;
_weakNativeView = new WeakReference<CollectionViewRenderer>(nativeView);
_weakParentView = new WeakReference<RecyclerView>(parentView);
_context = context;
_elementItemsSource = element.ItemsSource;
_dataSource = _elementItemsSource?.Cast<object>().ToList() ?? new List<object>();
_formsViews = new List<WeakReference<ViewCell>>();
if (_element.ItemTemplate is not DataTemplateSelector)
{
// Cache only support single DataTemplate
_viewHolderQueue = new ViewHolderQueue(element.ViewCacheSize, () => CreateViewHolder());
_viewHolderQueue.Build();
}
_notifyCollectionChanged = _elementItemsSource as INotifyCollectionChanged;
if (_notifyCollectionChanged != null)
{
_notifyCollectionChanged.CollectionChanged += OnCollectionChanged;
}
}
public override int ItemCount => _isDisposed || _dataSource == null ? 0 : _dataSource.Count;
public override long GetItemId(int position)
{
return position;
}
public override int GetItemViewType(int position)
{
if (_isDisposed)
{
return -1;
}
if (_element.ItemTemplate is DataTemplateSelector dataTemplateSelector)
{
var data = _dataSource[position];
var dataTemplate = dataTemplateSelector.SelectTemplate(data, _element);
int itemViewType = _dataTemplates.IndexOf(dataTemplate);
if (itemViewType == -1)
{
itemViewType = _dataTemplates.Count;
_dataTemplates.Add(dataTemplate);
}
if (!_element.IsLayoutLinear)
{
return itemViewType;
}
if (dataTemplate is SizedDataTemplate sizedDataTemplate)
{
_sizeByType[itemViewType] = sizedDataTemplate.Size;
}
else if (dataTemplateSelector is SizedDataTemplateSelector sizedDataTemplateSelector)
{
_sizeByType[itemViewType] = _element.IsLayoutHorizontal
? sizedDataTemplateSelector.GetItemSize(data, _element.ItemWidth)
: sizedDataTemplateSelector.GetItemSize(data, _element.ItemHeight);
}
return itemViewType;
}
return base.GetItemViewType(position);
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
if (_isDisposed)
{
return;
}
InternalLogger.Debug(Tag, () => $"OnBindViewHolder( position: {position} )");
var item = (ViewHolder)holder;
item.Bind(_dataSource[position], _element);
if (position > _currentMaxPosition)
{
_currentMaxPosition = position;
AnimateCell(item.ViewCell);
}
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
if (_isDisposed)
{
return new EmptyViewHolder(_context);
}
if (_element.ItemTemplate is DataTemplateSelector)
{
return CreateViewHolder(viewType);
}
return _viewHolderQueue.Dequeue();
}
public void OnEnableDragAndDropUpdated(bool isEnabled)
{
_enableDragAndDropCts?.Cancel();
_enableDragAndDropCts = new CancellationTokenSource();
if (!isEnabled)
{
return;
}
foreach (var weakFormsView in _formsViews)
{
if (!weakFormsView.TryGetTarget(out var formsView))
{
continue;
}
HandleDragAndDropEnabledAnimation(formsView);
}
}
public void OnItemMovedFromDragAndDrop(int from, int to)
{
if (_elementItemsSource is IList collection)
{
try
{
_collectionChangedBackfire = true;
var item = collection[from];
collection.RemoveAt(from);
collection.Insert(to, item);
}
finally
{
_collectionChangedBackfire = false;
}
}
}
public void OnItemMoving(int from, int to)
{
using (var h = new Handler(Looper.MainLooper))
{
h.Post(
() =>
{
if (_isDisposed)
{
return;
}
if (from < to)
{
for (int i = from; i < to; i++)
{
_dataSource.Swap(i, i + 1);
}
}
else
{
for (int i = from; i > to; i--)
{
_dataSource.Swap(i, i - 1);
}
}
NotifyItemMoved(from, to);
});
}
}
protected override void Dispose(bool disposing)
{
_isDisposed = true;
_viewHolderQueue?.Clear();
if (_notifyCollectionChanged != null)
{
_notifyCollectionChanged.CollectionChanged -= OnCollectionChanged;
}
base.Dispose(disposing);
}
private ViewHolder CreateViewHolder(int itemViewType = -1)
{
var view = CreateView(out var viewCell, itemViewType);
var viewHolder = new ViewHolder(view, viewCell, _element.TapCommand);
if (_element.DragAndDropTrigger == DragAndDropTrigger.Pan)
{
viewHolder.ItemView.Touch += (sender, e) => OnItemViewTouch(e, viewHolder);
}
return viewHolder;
}
private void OnItemViewTouch(TouchEventArgs e, ViewHolder item)
{
if (e.Event.ActionMasked == MotionEventActions.Down && _element.EnableDragAndDrop)
{
if (!_weakNativeView.TryGetTarget(out CollectionViewRenderer nativeView))
{
return;
}
nativeView.StartDragging(item);
}
e.Handled = false;
}
private void HandleDragAndDropEnabledAnimation(ViewCell viewCell)
{
if (_enableDragAndDropCts != null
&& !_enableDragAndDropCts.IsCancellationRequested
&& _element.EnableDragAndDrop
&& _element.DragAndDropEnabledAnimationAsync != null)
{
InternalLogger.Debug("HandleDragAndDropEnabledAnimation");
TaskMonitor.Create(_element.DragAndDropEnabledAnimationAsync(viewCell, _enableDragAndDropCts.Token));
}
}
private void AnimateCell(ViewCell cell)
{
TaskMonitor.Create(
async () =>
{
if (_element.PreRevealAnimationAsync != null)
{
await _element.PreRevealAnimationAsync(cell);
}
if (_element.RevealAnimationAsync != null)
{
await _element.RevealAnimationAsync(cell);
}
if (_element.PostRevealAnimationAsync != null)
{
await _element.PostRevealAnimationAsync(cell);
}
});
}
private View CreateView(out ViewCell viewCell, int itemViewType)
{
InternalLogger.Debug("Creating View");
var dataTemplate = _element.ItemTemplate;
if (itemViewType == -1)
{
viewCell = (ViewCell)dataTemplate.CreateContent();
}
else
{
var template = _dataTemplates[itemViewType];
if (template is SizedDataTemplate sizedDataTemplate)
{
template = sizedDataTemplate.DataTemplate;
}
viewCell = (ViewCell)template.CreateContent();
}
double itemWidth = _element.ItemWidth;
double itemHeight = _element.ItemHeight;
if (_element.IsLayoutLinear
&& _sizeByType.TryGetValue(itemViewType, out double itemSize))
{
if (_element.IsLayoutHorizontal)
{
itemWidth = itemSize;
}
else
{
itemHeight = itemSize;
}
}
_formsViews.Add(new WeakReference<ViewCell>(viewCell));
var view = viewCell.View;
var renderer = Platform.CreateRendererWithContext(view, _context);
Platform.SetRenderer(view, renderer);
renderer.Element.Layout(new Rectangle(0, 0, itemWidth, itemHeight));
renderer.UpdateLayout();
var itemView = renderer.View;
int topMargin = _element.IsLayoutHorizontal
? 0
: PlatformHelper.Instance.DpToPixels(MeasureHelper.RecyclerViewItemVerticalMarginDp);
int bottomMargin = _element.IsLayoutHorizontal
? 0
: PlatformHelper.Instance.DpToPixels(MeasureHelper.RecyclerViewItemVerticalMarginDp);
int width = PlatformHelper.Instance.DpToPixels(itemWidth, PlatformHelper.Rounding.Floor);
int height = PlatformHelper.Instance.DpToPixels(itemHeight);
itemView.LayoutParameters = new FrameLayout.LayoutParams(width, height)
{
Gravity = GravityFlags.CenterHorizontal,
TopMargin = topMargin,
BottomMargin = bottomMargin,
};
HandleDragAndDropEnabledAnimation(viewCell);
if (_element.IsLayoutLinear)
{
return itemView;
}
// If it's a grid list layer, we need to add it in a parent's view to have it centered
var container = new FrameLayout(_context)
{
LayoutParameters = new FrameLayout.LayoutParams(
LayoutParams.MatchParent,
height + topMargin + bottomMargin),
};
container.AddView(itemView);
return container;
}
private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (_isDisposed || _collectionChangedBackfire)
{
return;
}
if (!_weakParentView.TryGetTarget(out var parentView) || parentView.IsNullOrDisposed())
{
Dispose();
return;
}
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
OnItemAdded(e.NewStartingIndex, e.NewItems);
parentView.InvalidateItemDecorations();
break;
case NotifyCollectionChangedAction.Remove:
OnItemRemoved(e.OldStartingIndex, e.OldItems.Count);
parentView.InvalidateItemDecorations();
break;
case NotifyCollectionChangedAction.Move:
OnItemMoved(e.OldStartingIndex, e.NewStartingIndex);
parentView.InvalidateItemDecorations();
break;
case NotifyCollectionChangedAction.Replace:
OnItemReplaced(e.NewStartingIndex, e.NewItems[0]);
parentView.InvalidateItemDecorations();
break;
case NotifyCollectionChangedAction.Reset:
// Handled in the CollectionViewRenderer class, will just create a new adapter
break;
}
}
private void OnItemReplaced(int itemIndex, object newItem)
{
InternalLogger.Info($"OnItemReplaced( itemIndex: {itemIndex} )");
using var h = new Handler(Looper.MainLooper);
h.Post(
() =>
{
if (_isDisposed)
{
return;
}
_dataSource[itemIndex] = newItem;
NotifyItemChanged(itemIndex);
});
}
private void OnItemMoved(int from, int to)
{
InternalLogger.Info($"OnItemMoved( from: {from}, to: {to} )");
using var h = new Handler(Looper.MainLooper);
h.Post(
() =>
{
if (_isDisposed)
{
return;
}
var item = _dataSource[from];
_dataSource.RemoveAt(from);
_dataSource.Insert(to, item);
NotifyItemMoved(from, to);
});
}
private void OnItemAdded(int newIndex, IList items)
{
InternalLogger.Info($"OnItemAdded( newIndex: {newIndex}, itemCount: {items.Count} )");
using var h = new Handler(Looper.MainLooper);
h.Post(
() =>
{
if (_isDisposed)
{
return;
}
_dataSource.InsertRange(newIndex, items.Cast<object>());
if (items.Count == 1)
{
NotifyItemInserted(newIndex);
}
else
{
NotifyItemRangeInserted(newIndex, items.Count);
}
});
}
private void OnItemRemoved(int removedIndex, int itemCount)
{
InternalLogger.Info($"OnItemRemoved( newIndex: {removedIndex}, itemCount: {itemCount} )");
using var h = new Handler(Looper.MainLooper);
h.Post(
() =>
{
if (_isDisposed)
{
return;
}
for (int index = removedIndex; index < removedIndex + itemCount; index++)
{
var data = _dataSource[index];
Unbind(data);
}
_dataSource.RemoveRange(removedIndex, itemCount);
if (itemCount == 1)
{
NotifyItemRemoved(removedIndex);
}
else
{
NotifyItemRangeRemoved(removedIndex, itemCount);
}
});
}
private void Unbind(object data)
{
// System.Diagnostics.Debug.WriteLine($"Unbind( data: {data} )");
var weakViewCell = _formsViews.FirstOrDefault(
weakView => weakView.TryGetTarget(out ViewCell cell) && cell.BindingContext == data);
if (weakViewCell == null)
{
return;
}
if (weakViewCell.TryGetTarget(out var viewCell))
{
viewCell.BindingContext = null;
viewCell.Parent = null;
}
}
}
}
}
| 35.544141
| 167
| 0.477014
|
[
"MIT"
] |
ali-h2010/Testing-Sharpnado.CollectionView-main
|
Sharpnado.CollectionView.Droid/Renderers/CollectionViewRenderer.RecycleViewAdapter.cs
| 22,146
|
C#
|
using System;
using System.Collections.Generic;
using TetraSlide.Api.Exceptions;
using TetraSlide.Api.Models;
namespace TetraSlide.Api.Infrastructure
{
/// <summary>
///
/// </summary>
public class TestAccountRepository : IAccountRepository
{
IAccessTokenEncoder AccessTokenEncoder;
Dictionary<string, Account> Repository;
public TestAccountRepository( IAccessTokenEncoder accessTokenEncoder)
{
AccessTokenEncoder = accessTokenEncoder;
Repository = new Dictionary<string, Account>();
Account superAccount = Create(new Account()
{
email_address = "tetraslide@implbits.com",
name = "TetraSlide SuperUser",
identity_provider = Idp.Google
});
// The Super User account access_token is: dGV0cmFzbGlkZUBpbXBsYml0cy5jb201
}
public Account FindByAccessToken(string accessToken)
{
string callerEmail = AccessTokenEncoder.Decode(accessToken);
Account value = Get(callerEmail);
return value;
}
public Account Get(string emailAddress)
{
Account value;
lock (Repository)
{
if (Repository.TryGetValue(emailAddress, out value) == false)
{
throw new AccountNotFoundException(emailAddress);
}
}
return value;
}
public Account Create(Account account)
{
account.access_token = AccessTokenEncoder.Encode(account.email_address);
lock(Repository)
{
Repository.Remove(account.email_address);
Repository.Add(account.email_address, account);
}
return account;
}
public Account Update(string emailAddress, Account account)
{
lock (Repository)
{
// get the value we're gonna update
Account value = GetAccount(emailAddress);
// only update the stuff we need to.
if (account.access_token != null) { value.access_token = account.access_token; }
if (account.email_address != null) { value.email_address = account.email_address; }
if (account.identity_provider != null) { value.identity_provider = account.identity_provider; }
if (account.name != null) { value.name = account.name; }
Repository[emailAddress] = value;
return value;
}
}
public Account Delete(string emailAddress)
{
Account value = Get(emailAddress);
lock (Repository)
{
Repository.Remove(emailAddress);
}
return value;
}
protected Account GetAccount(string emailAddress)
{
Account value;
if (Repository.TryGetValue(emailAddress, out value) == false)
{
throw new AccountNotFoundException(emailAddress);
}
return value;
}
}
}
| 29.061947
| 111
| 0.542631
|
[
"MIT"
] |
petrsnd/tetrad
|
WebService/Api/Infrastructure/TestAccountRepository.cs
| 3,286
|
C#
|
[Serializable]
public sealed class DecoderFallbackException : ArgumentException // TypeDefIndex: 448
{
// Fields
private byte[] bytesUnknown; // 0x90
private int index; // 0x98
// Methods
// RVA: 0x2A74800 Offset: 0x2A74901 VA: 0x2A74800
public void .ctor() { }
// RVA: 0x2A74880 Offset: 0x2A74981 VA: 0x2A74880
internal void .ctor(SerializationInfo info, StreamingContext context) { }
// RVA: 0x2A73EB0 Offset: 0x2A73FB1 VA: 0x2A73EB0
public void .ctor(string message, byte[] bytesUnknown, int index) { }
}
| 26.15
| 85
| 0.732314
|
[
"MIT"
] |
SinsofSloth/RF5-global-metadata
|
System/Text/DecoderFallbackException.cs
| 523
|
C#
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.DotNet.XHarness.iOS.Shared.Execution;
using Microsoft.DotNet.XHarness.iOS.Shared.Logging;
namespace Microsoft.DotNet.XHarness.iOS.Shared.Hardware {
public interface ITCCDatabase {
Task<bool> AgreeToPromptsAsync (string simRuntime, string dataPath, string udid, ILog log, params string [] bundle_identifiers);
int GetTCCFormat (string simRuntime);
}
public class TCCDatabase : ITCCDatabase {
static readonly string iOSSimRuntimePrefix = "com.apple.CoreSimulator.SimRuntime.iOS-";
static readonly string tvOSSimRuntimePrefix = "com.apple.CoreSimulator.SimRuntime.tvOS-";
static readonly string watchOSRuntimePrefix = "com.apple.CoreSimulator.SimRuntime.watchOS-";
readonly IProcessManager processManager;
public TCCDatabase (IProcessManager processManager)
{
this.processManager = processManager ?? throw new ArgumentNullException (nameof (processManager));
}
public int GetTCCFormat (string simRuntime) {
// v1: < iOS 9
// v2: >= iOS 9 && < iOS 12
// v3: >= iOS 12
// v4: >= iOS 14
if (simRuntime.StartsWith (iOSSimRuntimePrefix, StringComparison.Ordinal)) {
var v = Version.Parse (simRuntime.Substring (iOSSimRuntimePrefix.Length).Replace ('-', '.'));
if (v.Major >= 14) {
return 4;
} else if (v.Major >= 12) {
return 3;
} else if (v.Major >= 9) {
return 2;
} else {
return 1;
}
} else if (simRuntime.StartsWith (tvOSSimRuntimePrefix, StringComparison.Ordinal)) {
var v = Version.Parse (simRuntime.Substring (tvOSSimRuntimePrefix.Length).Replace ('-', '.'));
if (v.Major >= 14) {
return 4;
} else if (v.Major >= 12) {
return 3;
} else {
return 2;
}
} else if (simRuntime.StartsWith (watchOSRuntimePrefix, StringComparison.Ordinal)) {
var v = Version.Parse (simRuntime.Substring (watchOSRuntimePrefix.Length).Replace ('-', '.'));
if (v.Major >= 7) {
return 4;
} else if (v.Major >= 5) {
return 3;
} else {
return 2;
}
} else {
throw new NotImplementedException ();
}
}
public async Task<bool> AgreeToPromptsAsync (string simRuntime, string TCCDb, string udid, ILog log, params string [] bundle_identifiers)
{
if (bundle_identifiers == null || bundle_identifiers.Length == 0) {
log.WriteLine ("No bundle identifiers given when requested permission editing.");
return false;
}
var sim_services = new string [] {
"kTCCServiceAll", // You'd think 'All' means all prompts, but some prompts still show up.
"kTCCServiceAddressBook",
"kTCCServiceCalendar",
"kTCCServicePhotos",
"kTCCServiceMediaLibrary",
"kTCCServiceMicrophone",
"kTCCServiceUbiquity",
"kTCCServiceWillow"
};
var failure = false;
var tcc_edit_timeout = 3;
var watch = new Stopwatch ();
watch.Start ();
var format = GetTCCFormat (simRuntime);
if (format >= 4) {
// We don't care if booting fails (it'll fail if it's already booted for instance)
await processManager.ExecuteXcodeCommandAsync ("simctl", new [] { "boot", udid }, log, TimeSpan.FromMinutes (1));
// execute 'simctl privacy <udid> grant all <bundle identifier>' for each bundle identifier
foreach (var bundle_identifier in bundle_identifiers) {
foreach (var bundle_id in new [] { bundle_identifier, bundle_identifier + ".watchkitapp" }) {
foreach (var service in sim_services) {
var args = new List<string> ();
args.Add ("privacy");
args.Add (udid);
args.Add ("grant");
args.Add (service);
args.Add (bundle_id);
var rv = await processManager.ExecuteXcodeCommandAsync ("simctl", args, log, TimeSpan.FromSeconds (30));
if (!rv.Succeeded) {
failure = true;
break;
}
}
}
if (failure)
break;
}
} else {
do {
if (failure) {
log.WriteLine ("Failed to edit TCC.db, trying again in 1 second... ", (int) (tcc_edit_timeout - watch.Elapsed.TotalSeconds));
await Task.Delay (TimeSpan.FromSeconds (1));
}
failure = false;
foreach (var bundle_identifier in bundle_identifiers) {
var args = new List<string> ();
var sql = new System.Text.StringBuilder ("\n");
args.Add (TCCDb);
foreach (var bundle_id in new [] { bundle_identifier, bundle_identifier + ".watchkitapp" }) {
foreach (var service in sim_services) {
switch (format) {
case 1:
// CREATE TABLE access (service TEXT NOT NULL, client TEXT NOT NULL, client_type INTEGER NOT NULL, allowed INTEGER NOT NULL, prompt_count INTEGER NOT NULL, csreq BLOB, CONSTRAINT key PRIMARY KEY (service, client, client_type));
sql.AppendFormat ("DELETE FROM access WHERE service = '{0}' AND client = '{1}';\n", service, bundle_id);
sql.AppendFormat ("INSERT INTO access VALUES('{0}','{1}',0,1,0,NULL);\n", service, bundle_id);
break;
case 2:
// CREATE TABLE access (service TEXT NOT NULL, client TEXT NOT NULL, client_type INTEGER NOT NULL, allowed INTEGER NOT NULL, prompt_count INTEGER NOT NULL, csreq BLOB, policy_id INTEGER, PRIMARY KEY (service, client, client_type), FOREIGN KEY (policy_id) REFERENCES policies(id) ON DELETE CASCADE ON UPDATE CASCADE);
sql.AppendFormat ("DELETE FROM access WHERE service = '{0}' AND client = '{1}';\n", service, bundle_id);
sql.AppendFormat ("INSERT INTO access VALUES('{0}','{1}',0,1,0,NULL,NULL);\n", service, bundle_id);
break;
case 3: // Xcode 10+
// CREATE TABLE access ( service TEXT NOT NULL, client TEXT NOT NULL, client_type INTEGER NOT NULL, allowed INTEGER NOT NULL, prompt_count INTEGER NOT NULL, csreq BLOB, policy_id INTEGER, indirect_object_identifier_type INTEGER, indirect_object_identifier TEXT, indirect_object_code_identity BLOB, flags INTEGER, last_modified INTEGER NOT NULL DEFAULT (CAST(strftime('%s','now') AS INTEGER)), PRIMARY KEY (service, client, client_type, indirect_object_identifier), FOREIGN KEY (policy_id) REFERENCES policies(id) ON DELETE CASCADE ON UPDATE CASCADE)
sql.AppendFormat ("INSERT OR REPLACE INTO access VALUES('{0}','{1}',0,1,0,NULL,NULL,NULL,'UNUSED',NULL,NULL,{2});\n", service, bundle_id, DateTimeOffset.Now.ToUnixTimeSeconds ());
break;
default:
throw new NotImplementedException ();
}
}
}
args.Add (sql.ToString ());
var rv = await processManager.ExecuteCommandAsync ("sqlite3", args, log, TimeSpan.FromSeconds (5));
if (!rv.Succeeded) {
failure = true;
break;
}
}
} while (failure && watch.Elapsed.TotalSeconds <= tcc_edit_timeout);
}
if (failure) {
log.WriteLine ("Failed to edit TCC.db, the test run might hang due to permission request dialogs");
} else {
log.WriteLine ("Successfully edited TCC.db");
}
log.WriteLine ("Current TCC database contents:");
await processManager.ExecuteCommandAsync ("sqlite3", new [] { TCCDb, ".dump" }, log, TimeSpan.FromSeconds (5));
return !failure;
}
}
}
| 43.313609
| 710
| 0.655328
|
[
"BSD-3-Clause"
] |
premun/xamarin-macios
|
tests/xharness/Microsoft.DotNet.XHarness.iOS.Shared/Hardware/TCCDatabase.cs
| 7,322
|
C#
|
using System.Web;
using System.Web.Mvc;
namespace LoadOnDemandSQL2016
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| 19.428571
| 80
| 0.665441
|
[
"MIT"
] |
jkelly295/LoadOnDemand
|
LoadOnDemandSQL2016/App_Start/FilterConfig.cs
| 274
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _01_Common_End
{
class Program
{
static void Main(string[] args)
{
string[] arr1 = Console.ReadLine().Split();
string[] arr2 = Console.ReadLine().Split();
int arr1Length = arr1.Length - 1;
int arr2Length = arr2.Length - 1;
bool isSame = false;
int countFromStart = 0;
for (int i = 0; i <= Math.Min(arr1Length, arr2Length); i++)
{
if (arr1[i] == arr2[i])
{
isSame = true;
countFromStart++;
continue;
}
if (isSame && arr1[i] != arr2[i])
{
break;
}
}
isSame = false;
int countFromEnd = 0;
while (arr1Length >= 0)
{
if (arr1Length < 0 || arr2Length < 0)
{
break;
}
if (arr1[arr1Length] == arr2[arr2Length])
{
isSame = true;
countFromEnd++;
}
if (isSame==true && arr1[arr1Length] != arr2[arr2Length])
{
break;
}
arr1Length--;
arr2Length--;
}
Console.WriteLine(Math.Max(countFromStart, countFromEnd));
}
}
}
| 27.241379
| 73
| 0.403165
|
[
"MIT"
] |
akkirilov/ProgrammingFundamentalsHomeworks
|
01_ProgrammingFundamentals/Homeworks/04_Arrays-Ex/01_Common End/Program.cs
| 1,582
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using BaroqueUI;
using System.Linq;
public interface IPongPad
{
void StartFollowing(Controller ctrl);
void FollowController();
void DestroyPad();
}
public abstract class PongBaseBuilder : MonoBehaviour
{
public GameObject padObjectPrefab, pausedPointerPrefab;
public Transform transformSpaceBase;
/*public GameObject preloadGameObject;*/
public static bool paused { get => paused_no_focus || paused_no_ctrl || paused_explicit; }
static bool paused_no_focus, paused_no_ctrl;
static protected bool paused_explicit;
protected virtual void Start()
{
Baroque.FadeToColor(Color.clear, 0.2f);
SilenceNow();
FadeInSounds(0.5f);
var ht = Controller.GlobalTracker(this);
ht.onControllersUpdate += Ht_onControllersUpdate;
UpdateTrackingSpacePosition();
StartCoroutine(TrackPosition());
}
private void OnApplicationFocus(bool focus)
{
#if !UNITY_EDITOR
paused_no_focus = !focus;
Time.timeScale = paused ? 0f : 1f;
#endif
}
public void SetPausedExplicit(bool pause)
{
paused_explicit = pause;
Time.timeScale = paused ? 0f : 1f;
if (!pause)
RemovePointersOnPausedExplicit();
}
bool _was_paused;
protected virtual void Update()
{
#if !UNITY_EDITOR
bool any_ctrl = Baroque.GetControllers().Where(ctrl => ctrl.isReady).Any();
if (any_ctrl == paused_no_ctrl)
{
paused_no_ctrl = !any_ctrl;
Time.timeScale = paused ? 0f : 1f;
}
#endif
if (paused)
{
foreach (var ctrl in Baroque.GetControllers())
{
var pad = ctrl.GetComponentInChildren<IPongPad>();
if (pad != null)
pad.DestroyPad();
}
PausedChange(true);
}
else if (_was_paused)
PausedChange(false);
_was_paused = paused;
}
protected abstract void PausedChange(bool paused);
public void UpdateTrackingSpacePosition()
{
var boundary = OVRManager.boundary;
Vector3[] geometry = boundary.GetGeometry(OVRBoundary.BoundaryType.PlayArea);
if (geometry != null && geometry.Length == 4 && OVRManager.instance != null)
{
Transform tracking_space = OVRManager.instance.transform;
/*string x(Vector3 v)
{
return v.x + "," + v.z;
}
Debug.LogError("size: " + x(size) + " geometry: " + string.Join(" ", geometry.Select(x)));*/
/* assume that geometry returned a perfect rectangle, but with a random center and orientation. */
Vector3 GlobalVec2(Vector3 local_v)
{
/* the documentation for GetGeometry() implies we need a
* TransformPoint() to get global coordinates, but it seems we don't
*/
Vector3 glob = local_v;
return new Vector3(glob.x, 0, glob.z);
}
Vector3 p0 = GlobalVec2(geometry[0]);
Vector3 p1 = GlobalVec2(geometry[1]);
Vector3 p2 = GlobalVec2(geometry[2]);
Vector3 p3 = GlobalVec2(geometry[3]);
//string s(Vector3 p) => p.x + ", " + p.z + " / ";
//Debug.Log("Recentered! " + s(p0) + s(p1) + s(p2) + s(p3));
float length = Mathf.Min(Vector3.Distance(p0, p1), Vector3.Distance(p2, p3));
float width = Mathf.Min(Vector3.Distance(p1, p2), Vector3.Distance(p3, p0));
if (length < 1e-3f || width < 1e-3f)
return;
if (width > length)
{
Vector3 t1 = p0; p0 = p1; p1 = p2; p2 = p3; p3 = t1;
}
Vector3 center = (p0 + p1 + p2 + p3) * 0.25f;
Vector3 bar = (p2 + p3) - (p1 + p0);
if (transformSpaceBase != null)
{
/* not completely right... works in our limited use cases */
center = transformSpaceBase.TransformPoint(center);
bar = transformSpaceBase.InverseTransformVector(bar);
}
tracking_space.position = center;
tracking_space.rotation = Quaternion.Inverse(Quaternion.LookRotation(bar));
}
}
IEnumerator TrackPosition()
{
yield return new WaitForSecondsRealtime(0.2f);
while (true)
{
UpdateTrackingSpacePosition();
/*if (preloadGameObject != null)
{
yield return new WaitForEndOfFrame();
Destroy((GameObject)preloadGameObject);
preloadGameObject = null;
}*/
yield return new WaitForSecondsRealtime(0.55f);
}
}
protected abstract void FrameByFrameUpdate();
private void Ht_onControllersUpdate(Controller[] controllers)
{
if (paused)
{
if (paused_explicit)
AddPointersOnPausedExplicit();
return;
}
FrameByFrameUpdate();
foreach (var ctrl in controllers)
if (ctrl.isReady)
{
var pad = ctrl.GetComponentInChildren<IPongPad>();
if (pad == null)
{
pad = Instantiate(padObjectPrefab, ctrl.transform).GetComponent<IPongPad>();
pad.StartFollowing(ctrl);
}
pad.FollowController();
}
}
private void OnDestroy()
{
/* scene change */
AudioListener.volume = 1;
foreach (var ctrl in Baroque.GetControllers())
{
var pad = ctrl.GetComponentInChildren<IPongPad>();
if (pad != null)
pad.DestroyPad();
}
RemovePointersOnPausedExplicit();
}
float _volume = 1;
Coroutine _volume_changer;
void _StopVolumeChanger()
{
if (_volume_changer != null)
{
StopCoroutine(_volume_changer);
_volume_changer = null;
}
}
public void FadeOutSounds(float delay)
{
_StopVolumeChanger();
StartCoroutine(_FadeOutSounds(delay));
}
public void FadeInSounds(float delay)
{
_StopVolumeChanger();
StartCoroutine(_FadeInSounds(delay));
}
public void SilenceNow()
{
_StopVolumeChanger();
_volume = 0;
AudioListener.volume = 0;
}
IEnumerator _FadeOutSounds(float delay)
{
while (true)
{
_volume -= Time.unscaledDeltaTime / delay;
if (_volume < 0f)
_volume = 0f;
AudioListener.volume = _volume;
if (_volume == 0f)
break;
yield return null;
}
}
IEnumerator _FadeInSounds(float delay)
{
while (true)
{
_volume += Time.unscaledDeltaTime / delay;
if (_volume > 1f)
_volume = 1f;
AudioListener.volume = _volume;
if (_volume == 1f)
break;
yield return null;
}
}
protected virtual void AddPointersOnPausedExplicit() { SetPausedExplicit(false); }
protected virtual void RemovePointersOnPausedExplicit() { }
}
| 28.770428
| 110
| 0.552475
|
[
"MIT"
] |
arigo/PongQuest
|
Assets/Scripts/PongBaseBuilder.cs
| 7,396
|
C#
|
//------------------------------------------------------------------------------
//----- PULALimitationsHandler ---------------------------------------------------
//------------------------------------------------------------------------------
//-------1---------2---------3---------4---------5---------6---------7---------8
// 01234567890123456789012345678901234567890123456789012345678901234567890
//-------+---------+---------+---------+---------+---------+---------+---------+
// copyright: 2012 WiM - USGS
// authors: Jeremy K. Newson USGS Wisconsin Internet Mapping
//
//
// purpose: Handles Site resources through the HTTP uniform interface.
// Equivalent to the controller in MVC.
//
//discussion: Handlers are objects which handle all interaction with resources in
// this case the resources are POCO classes derived from the EF.
// https://github.com/openrasta/openrasta/wiki/Handlers
//
//
#region Comments
// 11.09.12 - TR - Changed class name from SiteHandler to PULALimitationsHandler and removed ForUriName "Sites" references
// 10.19.12 - JB - Created from STN
#endregion
using BLTServices.Authentication;
using BLTServices.Resources;
using BLTDB;
using OpenRasta.Web;
using OpenRasta.Security;
using System;
using System.Data;
using System.Data.EntityClient;
using System.Data.Metadata.Edm;
using System.Data.Objects;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Runtime.InteropServices;
namespace BLTServices.Handlers
{
public class PULALimitationsHandler: HandlerBase
{
#region Properties
public override string entityName
{
get { return "pula_limitations"; }
}
#endregion
#region Routed Methods
#region GetMethods
//---------------------Returns List of objects---------------------
// returns all PULA_LIMITATIONS
[HttpOperation(HttpMethod.GET)]
public OperationResult Get()
{
List<pula_limitations> pulaLimit;
try
{
using (bltEntities aBLTE = GetRDS())
{
pulaLimit = GetEntities<pula_limitations>(aBLTE).ToList();
}//end using
return new OperationResult.OK { ResponseResource = pulaLimit };
}
catch (Exception ex)
{
return new OperationResult.InternalServerError { ResponseResource = ex.InnerException.ToString() };
}
}//end HttpMethod.GET
// returns all PULAs
[HttpOperation(HttpMethod.GET, ForUriName = "GetVersionedPULALimitations")]
public OperationResult GetVersionedPULALimitations(string status, string date)
{
IQueryable<pula_limitations> pulaLimitQuery;
List<pula_limitations> pulaLimitList;
try
{
StatusType statustype = getStatusType(status);
DateTime? thisDate = ValidDate(date);
if (!thisDate.HasValue)
thisDate = DateTime.Now.Date;
using (bltEntities aBLTE = GetRDS())
{
pulaLimitQuery = GetEntities<pula_limitations>(aBLTE);
switch (statustype)
{
case (StatusType.Published):
pulaLimitQuery.Where(ai => ai.version.published_time_stamp != null);
break;
case (StatusType.Reviewed):
pulaLimitQuery.Where(ai => ai.version.reviewed_time_stamp != null &&
ai.version.published_time_stamp == null);
break;
//created
default:
pulaLimitQuery.Where(ai => ai.version.reviewed_time_stamp == null &&
ai.version.published_time_stamp == null);
break;
}//end switch
pulaLimitQuery.Where(ai => !ai.version.expired_time_stamp.HasValue ||
ai.version.expired_time_stamp < thisDate.Value.Date);
pulaLimitList = pulaLimitQuery.ToList();
}//end using
return new OperationResult.OK { ResponseResource = pulaLimitList };
}
catch (Exception ex)
{
return new OperationResult.InternalServerError { ResponseResource = ex.InnerException.ToString() };
}
}//end HttpMethod.GET
// returns all active PULA_LIMITATIONS
[HttpOperation(HttpMethod.GET)]
public OperationResult Get(string date)
{
List<pula_limitations> pulaLimit = null;
try
{
DateTime? thisDate = ValidDate(date);
if (!thisDate.HasValue)
thisDate = DateTime.Now.Date;
//set the date to current date if request is not authorized
if (DateTime.Compare(thisDate.Value.Date, DateTime.Now.Date) < 0 && !CanManage()) thisDate = DateTime.Now.Date;
using (bltEntities aBLTE = GetRDS())
{
pulaLimit = GetActive(GetEntities<pula_limitations>(aBLTE), thisDate.Value.Date).ToList();
}//end using
return new OperationResult.OK { ResponseResource = pulaLimit };
}
catch (Exception ex)
{
return new OperationResult.InternalServerError { ResponseResource = ex.InnerException.ToString() };
}
}//end HttpMethod.GET
// returns all PULALimitations (active if date is supplied)
[HttpOperation(HttpMethod.GET)]
public OperationResult Get(Int32 pulaLimitationsID, [Optional] string date)
{
try
{
List<pula_limitations> pulaLimitationList;
DateTime? thisDate = ValidDate(date);
if (pulaLimitationsID < 0)
{ return new OperationResult.BadRequest(); }
using (bltEntities aBLTE = GetRDS())
{
IQueryable<pula_limitations> query;
query = GetEntities<pula_limitations>(aBLTE).Where(pl => pl.pula_limitation_id == pulaLimitationsID);
if (thisDate.HasValue)
query = GetActive(query, thisDate.Value.Date);
//process
pulaLimitationList = query.ToList();
}//end using
//activateLinks<pula_limitations>(pulaLimitationList);
return new OperationResult.OK { ResponseResource = pulaLimitationList };
}
catch (Exception ex)
{
return new OperationResult.InternalServerError { ResponseResource = ex.InnerException.ToString() };
}
}//end HttpMethod.GET
// returns Active PULA_LIMITATIONS for the given pulaID
[HttpOperation(HttpMethod.GET, ForUriName = "GetPULALimitations")]
public OperationResult GetPULALimitations(Int32 pulaId, [Optional]string date)
{
try
{
DateTime? thisDate = ValidDate(date);
if (!thisDate.HasValue)
thisDate = DateTime.Now.Date;
//set the date to current date if request is not authorized
if (DateTime.Compare(thisDate.Value.Date, DateTime.Now.Date) < 0 && !CanManage()) thisDate = DateTime.Now.Date;
List<pula_limitations> pulaLimitationList;
using (bltEntities aBLTE = GetRDS())
{
IQueryable<pula_limitations> query1 = GetEntities<pula_limitations>(aBLTE).Where(a => a.pula_id == pulaId);
pulaLimitationList = GetActive(query1, thisDate.Value.Date).ToList();
}//end using
return new OperationResult.OK { ResponseResource = pulaLimitationList };
}
catch (Exception ex)
{
return new OperationResult.InternalServerError { ResponseResource = ex.InnerException.ToString() };
}
}//end HttpMethod.GET
// returns Active PULA_LIMITATIONS for the given pulaID Int32 pulaId,
[HttpOperation(HttpMethod.GET, ForUriName = "GetMapperLimitations")]
public OperationResult GetMapperLimitations(Int32 pulaSHPID, string date)
{
try
{
DateTime? thisDate = ValidDate(date);
if (!thisDate.HasValue)
thisDate = DateTime.Now.Date;
//set the date to current date if request is not authorized
if (DateTime.Compare(thisDate.Value.Date, DateTime.Now.Date) < 0 && !CanManage()) thisDate = DateTime.Now.Date;
MapperLimitations MapLimitList = new MapperLimitations();
using (bltEntities aBLTE = GetRDS())
{
active_ingredient_pula thisPULA = aBLTE.active_ingredient_pula.Where(x=> x.pula_shape_id == pulaSHPID).FirstOrDefault();
//go get the limitations, then when populating each MapperLimit - go get each piece using the id of each
IQueryable<pula_limitations> query1 = GetEntities<pula_limitations>(aBLTE).Where(a => a.pula_id == thisPULA.pula_id);
List<pula_limitations> pulaLimitationList = GetActive(query1, thisDate.Value.Date).ToList();
MapLimitList.MapperLimits = pulaLimitationList.Select(p => new MapperLimit()
{
PULAID = thisPULA.pula_id,
PULASHPID = pulaSHPID,
NAME = GetAIorProdName(p.active_ingredient_id, p.product_id, thisDate.Value.Date, aBLTE),
USE = GetActive(aBLTE.crop_use.Where(u => u.crop_use_id == p.crop_use_id), thisDate.Value.Date).FirstOrDefault().use,
APPMETHOD = aBLTE.application_method.Where(u => u.application_method_id == p.application_method_id).FirstOrDefault().method,
FORM = aBLTE.formulations.Where(u => u.formulation_id == p.formulation_id).FirstOrDefault().form,
LIMIT = aBLTE.limitations.FirstOrDefault(u => u.limitation_id == p.limitation_id)
}).ToList();
}//end using
return new OperationResult.OK { ResponseResource = MapLimitList };
}
catch (Exception ex)
{
return new OperationResult.InternalServerError { ResponseResource = ex.InnerException.ToString() };
}
}
//---------------------Returns individual objects---------------------
[HttpOperation(HttpMethod.GET, ForUriName = "GetEntity")]
public OperationResult GetEntity(Int32 entityID)
{
pula_limitations aPULALimit;
try
{
using (bltEntities aBLTE = GetRDS())
{
aPULALimit = GetEntities<pula_limitations>(aBLTE).SingleOrDefault(ai => ai.pula_limitation_id == entityID);
}//end using
return new OperationResult.OK { ResponseResource = aPULALimit };
}
catch (Exception ex)
{
return new OperationResult.InternalServerError { ResponseResource = ex.InnerException.ToString() };
}
}//end HttpMethod.GET
#endregion
#region Status Methods
[WiMRequiresRole(new string[] { AdminRole, PublisherRole })]
[HttpOperation(HttpMethod.GET, ForUriName = "UpdatePulaLimitationsStatus")]
public OperationResult UpdatePulaLimitationsStatus(Int32 entityID, string status, [Optional] string date)
{
//No editing of tables are allowed. An edit call will create and activate a new entity, and expire the old one
user_ loggedInUser;
pula_limitations aPULALimitation;
try
{
StatusType statusType = getStatusType(status);
DateTime? thisDate = ValidDate(date);
if (!thisDate.HasValue || thisDate.Value.Date < DateTime.Now.Date)
thisDate = DateTime.Now.Date;
if (entityID <= 0 || string.IsNullOrEmpty(status) || statusType == StatusType.Created)
{ return new OperationResult.BadRequest(); }
using (EasySecureString securedPassword = GetSecuredPassword())
{
using (bltEntities aBLTE = GetRDS(securedPassword))
{
//version user
loggedInUser = LoggedInUser(aBLTE);
aPULALimitation = aBLTE.pula_limitations.FirstOrDefault(ai => ai.pula_limitation_id == entityID);
if (aPULALimitation == null)
{ return new OperationResult.BadRequest(); }
//assign version
aPULALimitation.version_id = SetVersion(aBLTE, aPULALimitation.version_id, loggedInUser.user_id, statusType, thisDate.Value.Date).version_id;
aBLTE.SaveChanges();
}//end using
}//end using
return new OperationResult.OK { ResponseResource = aPULALimitation };
}
catch (Exception)
{ return new OperationResult.BadRequest(); }
}//end HttpMethod.GET
#endregion
#region POST Methods
[WiMRequiresRole(new string[] { AdminRole, PublisherRole, CreatorRole })]
[HttpOperation(HttpMethod.POST)]
public OperationResult POST(pula_limitations anEntity)
{
try
{
using (EasySecureString securedPassword = GetSecuredPassword())
{
using (bltEntities aBLTE = GetRDS(securedPassword))
{
if (!Exists(aBLTE, ref anEntity))
{
//create version
anEntity.version_id = SetVersion(aBLTE, anEntity.version_id, LoggedInUser(aBLTE).user_id, StatusType.Published, DateTime.Now.Date).version_id;
aBLTE.pula_limitations.Add(anEntity);
aBLTE.SaveChanges();
}//end if
}//end using
}//end using
return new OperationResult.OK { ResponseResource = anEntity };
}
catch (Exception)
{ return new OperationResult.BadRequest(); }
}//end HttpMethod.GET
#endregion
#region PUT/EDIT Methods
[WiMRequiresRole(new string[] { AdminRole, PublisherRole })]
[HttpOperation(HttpMethod.PUT)]
public OperationResult Put(Int32 entityID, pula_limitations anEntity)
{
//No editing of tables are allowed. An edit call will create and activate a new entity, and expire the old one
user_ loggedInUser;
pula_limitations aPULALimit;
try
{
if (entityID <= 0)
{ return new OperationResult.BadRequest(); }
using (EasySecureString securedPassword = GetSecuredPassword())
{
using (bltEntities aBLTE = GetRDS(securedPassword))
{
//version user
loggedInUser = LoggedInUser(aBLTE);
aPULALimit = aBLTE.pula_limitations.FirstOrDefault(ai => ai.pula_limitation_id == entityID);
if (aPULALimit == null)
{ return new OperationResult.BadRequest(); }
if (aPULALimit.version.published_time_stamp.HasValue)
{
//can not edit a published entity. create new
// assign Version
anEntity.version_id = SetVersion(aBLTE, anEntity.version_id, loggedInUser.user_id, StatusType.Published, DateTime.Now.Date).version_id;
aBLTE.pula_limitations.Add(anEntity);
//expire originals
ExpireOtherEntities(aBLTE, LoggedInUser(aBLTE).user_id, anEntity, DateTime.Now.Date);
aPULALimit = anEntity;
}
else
{
aPULALimit.active_ingredient_id = anEntity.active_ingredient_id;
aPULALimit.application_method_id = anEntity.application_method_id;
aPULALimit.crop_use_id = anEntity.crop_use_id;
aPULALimit.formulation_id = anEntity.formulation_id;
aPULALimit.limitation_id = anEntity.limitation_id;
aPULALimit.product_id = anEntity.product_id;
aPULALimit.pula_id = anEntity.pula_id;
}//end if
aBLTE.SaveChanges();
//activateLinks<pula_limitations>(anEntity);
}//end using
}//end using
return new OperationResult.OK { ResponseResource = anEntity };
}
catch (Exception)
{ return new OperationResult.BadRequest(); }
}//end HttpMethod.GET
#endregion
#region DELETE Methods
[WiMRequiresRole(new string[] { AdminRole })]
[HttpOperation(HttpMethod.DELETE)]
public OperationResult Delete(Int32 entityID)
{
//Return BadRequest if missing required fields
if (entityID <= 0)
return new OperationResult.BadRequest();
//Get basic authentication password
using (EasySecureString securedPassword = GetSecuredPassword())
{
using (bltEntities aBLTE = GetRDS(securedPassword))
{
pula_limitations ObjectToBeDelete = aBLTE.pula_limitations.FirstOrDefault(f => f.pula_limitation_id == entityID);
if (ObjectToBeDelete == null)
{ return new OperationResult.BadRequest(); }
//NOTE: ShapeID can not be changed
//need to see if the PULA this PULA_LIMITATION is a part of is published (PULA_LIMITATION is published when created)
active_ingredient_pula thisPULA = aBLTE.active_ingredient_pula.FirstOrDefault(a => a.pula_id == ObjectToBeDelete.pula_id);
if (thisPULA.is_published == 1)
{
ObjectToBeDelete.version_id = SetVersion(ObjectToBeDelete.version_id, LoggedInUser(aBLTE).user_id, StatusType.Expired, DateTime.Now.Date).version_id;
}
else
{
aBLTE.pula_limitations.Remove(ObjectToBeDelete);
}//end if
aBLTE.SaveChanges();
}//end using
}//end using
//Return object to verify persisitance
return new OperationResult.OK { };
}//end HttpMethod.GET
#endregion
#endregion
#region Helper Methods
private bool Exists(bltEntities aBLTE, ref pula_limitations anEntity)
{
pula_limitations existingEntity;
pula_limitations thisEntity = anEntity;
//check if it exists
try
{
existingEntity = aBLTE.pula_limitations.FirstOrDefault(mt => mt.pula_id == thisEntity.pula_id &&
(mt.active_ingredient_id == thisEntity.active_ingredient_id || thisEntity.active_ingredient_id <= 0 || thisEntity.active_ingredient_id == null) &&
(mt.product_id == thisEntity.product_id || thisEntity.product_id <= 0 || thisEntity.product_id == null) &&
(mt.limitation_id == thisEntity.limitation_id || thisEntity.limitation_id <= 0 || thisEntity.limitation_id == null) &&
(mt.crop_use_id == thisEntity.crop_use_id || thisEntity.crop_use_id <= 0 || thisEntity.crop_use_id == null) &&
(mt.application_method_id == thisEntity.application_method_id || thisEntity.application_method_id <= 0 || thisEntity.application_method_id == null) &&
(mt.formulation_id == thisEntity.formulation_id || thisEntity.formulation_id <= 0 || thisEntity.formulation_id == null)
);
if (existingEntity == null)
return false;
//if exists then update ref
anEntity = existingEntity;
return true;
}
catch (Exception)
{
return false;
}
}//end Exists
protected void ExpireOtherEntities(bltEntities aBLTE, Int32 userId, pula_limitations pulaLimitation, DateTime dt)
{
//get all published, should only be 1
List<pula_limitations> aiList = aBLTE.pula_limitations.Where(p => p.pula_limitation_id == pulaLimitation.pula_limitation_id &&
p.version.published_time_stamp <= dt.Date).ToList();
if (aiList == null) return;
foreach (var p in aiList)
{
if (!p.Equals(pulaLimitation))
p.version = SetVersion(aBLTE, p.version_id, userId, StatusType.Expired, dt.Date);
}//next
}//end ExpireOtherEntities
protected override void ExpireEntities(bltEntities aBLTE, Int32 userId, Int32 Id, DateTime dt)
{
//get all published, should only be 1
List<pula_limitations> pulaLimitList = aBLTE.pula_limitations.Where(p => p.pula_limitation_id == Id &&
p.version.published_time_stamp <= dt.Date).ToList();
if (pulaLimitList == null) return;
foreach (var p in pulaLimitList)
{
p.version = SetVersion(aBLTE, p.version_id, userId, StatusType.Expired, dt.Date);
}//next
}
private string GetAIorProdName(decimal? AI_ID, decimal? PROD_ID, DateTime d, bltEntities aBLTE)
{
string name = string.Empty;
//IQueryable<PULA_LIMITATIONS> query1 = GetEntities<PULA_LIMITATIONS>(aBLTE).Where(a => a.PULA_ID == pulaId);
//List<PULA_LIMITATIONS> pulaLimitationList = GetActive(query1, thisDate.Value.Date).ToList();
if (AI_ID > 0)
{
IQueryable<active_ingredient> qA = aBLTE.active_ingredient.Where(x => x.active_ingredient_id == AI_ID);
name = GetActive(qA, d).FirstOrDefault().ingredient_name;
}
else
{
IQueryable<product> qP = aBLTE.products.Where(x => x.product_id == PROD_ID);
product qprod = GetActive(qP, d).FirstOrDefault();
name = qprod.product_name + " [" + qprod.product_registration_number + "]";
//PRODUCT aProd = GetActive(aBLTE.PRODUCT.Where(x => x.PRODUCT_ID == PROD_ID).FirstOrDefault, d);
//name = aProd.PRODUCT_NAME
}
return name;
}//end HttpMethod.GET
#endregion
}//end class PULALimitationsHandler
}//end namespace
| 44.23964
| 226
| 0.536594
|
[
"CC0-1.0",
"MIT"
] |
USGS-WiM/BLTServices-new
|
BLTServices/Handlers/PULALimitationsHandler.cs
| 24,555
|
C#
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using JetBrains.Annotations;
namespace Microsoft.EntityFrameworkCore.Metadata.Internal
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static class ConventionAnnotatableExtensions
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static void SetOrRemoveAnnotation(
[NotNull] this ConventionAnnotatable annotatable,
[NotNull] string name,
[CanBeNull] object value,
ConfigurationSource configurationSource)
{
if (value == null)
{
annotatable.RemoveAnnotation(name);
}
else
{
annotatable.SetAnnotation(name, value, configurationSource);
}
}
}
}
| 41.675676
| 113
| 0.643969
|
[
"Apache-2.0"
] |
BionStt/EntityFrameworkCore
|
src/EFCore/Metadata/Internal/ConventionAnnotatableExtensions.cs
| 1,542
|
C#
|
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Identity;
using Volo.Abp.ObjectExtending;
using Volo.Abp.Threading;
namespace ProductManagement.EntityFrameworkCore
{
public static class ProductManagementEfCoreEntityExtensionMappings
{
private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner();
public static void Configure()
{
ProductManagementGlobalFeatureConfigurator.Configure();
ProductManagementModuleExtensionConfigurator.Configure();
OneTimeRunner.Run(() =>
{
/* You can configure extra properties for the
* entities defined in the modules used by your application.
*
* This class can be used to map these extra properties to table fields in the database.
*
* USE THIS CLASS ONLY TO CONFIGURE EF CORE RELATED MAPPING.
* USE ProductManagementModuleExtensionConfigurator CLASS (in the Domain.Shared project)
* FOR A HIGH LEVEL API TO DEFINE EXTRA PROPERTIES TO ENTITIES OF THE USED MODULES
*
* Example: Map a property to a table field:
ObjectExtensionManager.Instance
.MapEfCoreProperty<IdentityUser, string>(
"MyProperty",
(entityBuilder, propertyBuilder) =>
{
propertyBuilder.HasMaxLength(128);
}
);
* See the documentation for more:
* https://docs.abp.io/en/abp/latest/Customizing-Application-Modules-Extending-Entities
*/
});
}
}
}
| 39.369565
| 104
| 0.563225
|
[
"MIT"
] |
PacktPublishing/Mastering-ABP-Framework
|
Samples/Chapter-03/ProductManagement/src/ProductManagement.EntityFrameworkCore/EntityFrameworkCore/ProductManagementEfCoreEntityExtensionMappings.cs
| 1,813
|
C#
|
namespace MyAutoPartsWebStore.Web
{
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MyAutoPartsStore.Data;
using MyAutoPartsStore.Data.Models;
using MyAutoPartsStore.Services.CategoryServices;
using MyAutoPartsStore.Services.DealersServices;
using MyAutoPartsStore.Services.OrderServices;
using MyAutoPartsStore.Services.ProductServices;
using MyAutoPartsWebStore.Web.Infrastructure.Extentions;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyAutoPartsStoreDbContext>(options => options
.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDatabaseDeveloperPageExceptionFilter();
services.AddDefaultIdentity<User>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequiredLength = 6;
options.User.RequireUniqueEmail = true;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<MyAutoPartsStoreDbContext>();
services.AddAutoMapper();
services.AddCustomServices();
services.AddMemoryCache();
services.AddControllersWithViews(options =>
{
options.Filters.Add<AutoValidateAntiforgeryTokenAttribute>();
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.PrepareDatabase();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app
.UseHttpsRedirection()
.UseStaticFiles()
.UseRouting()
.UseAuthentication()
.UseAuthorization()
.UseEndpoints(endpoints =>
{
endpoints.MapDefaultAreaRoute();
//endpoints.MapControllerRoute(
// name: "Details",
// pattern: "/Product/Description/{id}/{information}",
// defaults: new { controller = "Product", acttion = "Description" });
endpoints.MapDefaultControllerRoute();
endpoints.MapRazorPages();
});
}
}
}
| 34.357895
| 93
| 0.593137
|
[
"MIT"
] |
Morbidius/MyAutoPartsStore
|
MyAutoPartsWebStore/MyAutoPartsWebStore.Web/Startup.cs
| 3,264
|
C#
|
/***
* Created by: Anupam Terkonda
* Created: 1/24/22
*
* Last Edited by: N/A
* Last Edited: 1/26/22
*
* Description: Spawns multiple cubes prefabs into scene.
* ***/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomCubes : MonoBehaviour
{
//creating Variables
public GameObject cubePrefab; //new gameobject
public List<GameObject> gameObjectList; //list for all cubes
public float scalingFactor = 0.95f;
//[HideInInspector]
public int numberOfCubes = 0;
// Start is called before the first frame update
void Start()
{
gameObjectList = new List<GameObject>(); //instantiates the list
}
// Update is called once per frame
void Update()
{
numberOfCubes++; //add to the number of cubes
GameObject gObj = Instantiate<GameObject>(cubePrefab);
gObj.name = "Cube" + numberOfCubes; //name property of the object
gObj.transform.position = Random.insideUnitSphere; //random point inside a sphere radius of 1
Color randomColor = new Color(Random.value, Random.value, Random.value);
gObj.GetComponent<Renderer>().material.color = randomColor; //assign random color to cubes
gameObjectList.Add(gObj); //add cube to list
List<GameObject> removeList = new List<GameObject>(); //list of game objects to remove
foreach(GameObject goTemp in gameObjectList)
{
float scale = goTemp.transform.localScale.x; //record starting scale
scale *= scalingFactor; //set scale value
goTemp.transform.localScale = Vector3.one * scale; //transforms the scale
if(scale <= 0.1f)
{
removeList.Add(goTemp); //add to remove list
} //end if loop
} //end foreach loop
foreach(GameObject goTemp in removeList)
{
gameObjectList.Remove(goTemp); //remove from gameobject list
Destroy(goTemp); //destroy object from scene
}//end foreach loop
}
}
| 30.761194
| 101
| 0.646288
|
[
"MIT"
] |
Terkonda54/RandomCubes
|
RandomCubesUnity/Assets/Scripts/RandomCubes.cs
| 2,061
|
C#
|
using SitefinityWebApp.Mvc.Utilities;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace SitefinityWebApp.Mvc.Models
{/// <summary>
/// This class is a View Model which represents the collection of events
/// that will be presented to the user. The properties for ordering and filtration
/// are nullable as they are optional. The model validation is configured by attributes.
/// </summary>
public class IndexViewModel
{
public IndexViewModel(IQueryable<EventViewModel> eventItems)
{
EventItems = eventItems;
}
public IndexViewModel(IQueryable<EventViewModel> eventItems, DateTime? filterDate, CalendarNames calendarName, OrderTypes orderBy)
: this(eventItems)
{
FilterDate = filterDate;
CalendarName = calendarName;
OrderBy = orderBy;
}
public IQueryable<EventViewModel> EventItems { get; set; }
// This property will hold a state, selected by user.
[Display(Name = "Filter By Date")]
[DataType(DataType.Date)]
public DateTime? FilterDate { get; set; }
// This property holds an enumeration with the available options for calendars
//to choose from.
[Display(Name = "Filter By Calendar")]
[EnumDataType(typeof(CalendarNames))]
public CalendarNames CalendarName { get; set; }
//This property holds an enumeration with available options for ordering the results.
[Display(Name ="Order By")]
[EnumDataType(typeof(OrderTypes))]
public OrderTypes OrderBy { get; set; }
}
}
| 36.8
| 138
| 0.664855
|
[
"MIT"
] |
NevenaNikolova/SitefinityWidgetTask
|
Default/Mvc/Models/IndexViewModel.cs
| 1,658
|
C#
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// ReSharper disable MissingSerializationAttribute
namespace Apache.Ignite.Core.Tests.Cache
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Expiry;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Impl.Cache.Expiry;
using Apache.Ignite.Core.Tests.Query;
using Apache.Ignite.Core.Transactions;
using NUnit.Framework;
/// <summary>
///
/// </summary>
class CacheTestKey
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="id">ID.</param>
public CacheTestKey(int id)
{
Id = id;
}
/// <summary>
/// ID.
/// </summary>
public int Id
{
get;
set;
}
/** <inheritdoc /> */
public override bool Equals(object obj)
{
CacheTestKey other = obj as CacheTestKey;
return other != null && Id == other.Id;
}
/** <inheritdoc /> */
public override int GetHashCode()
{
return Id;
}
/** <inheritdoc /> */
public override string ToString()
{
return new StringBuilder()
.Append(typeof(CacheTestKey).Name)
.Append(" [id=").Append(Id)
.Append(']').ToString();
}
}
/// <summary>
///
/// </summary>
class TestReferenceObject
{
public TestReferenceObject Obj;
/// <summary>
/// Default constructor.
/// </summary>
public TestReferenceObject()
{
// No-op.
}
public TestReferenceObject(TestReferenceObject obj)
{
Obj = obj;
}
}
[Serializable]
public class TestSerializableObject
{
public string Name { get; set; }
public int Id { get; set; }
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
var other = (TestSerializableObject) obj;
return obj.GetType() == GetType() && (string.Equals(Name, other.Name) && Id == other.Id);
}
public override int GetHashCode()
{
unchecked
{
return ((Name != null ? Name.GetHashCode() : 0) * 397) ^ Id;
}
}
}
/// <summary>
/// Cache entry processor that adds argument value to the entry value.
/// </summary>
[Serializable]
public class AddArgCacheEntryProcessor : ICacheEntryProcessor<int, int, int, int>
{
// Expected exception text
public const string ExceptionText = "Exception from AddArgCacheEntryProcessor.";
// Error flag
public bool ThrowErr { get; set; }
// Error flag
public bool ThrowErrBinarizable { get; set; }
// Error flag
public bool ThrowErrNonSerializable { get; set; }
// Key value to throw error on
public int ThrowOnKey { get; set; }
// Remove flag
public bool Remove { get; set; }
// Exists flag
public bool Exists { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="AddArgCacheEntryProcessor"/> class.
/// </summary>
public AddArgCacheEntryProcessor()
{
Exists = true;
ThrowOnKey = -1;
}
/** <inheritdoc /> */
int ICacheEntryProcessor<int, int, int, int>.Process(IMutableCacheEntry<int, int> entry, int arg)
{
if (ThrowOnKey < 0 || ThrowOnKey == entry.Key)
{
if (ThrowErr)
throw new Exception(ExceptionText);
if (ThrowErrBinarizable)
throw new BinarizableTestException {Info = ExceptionText};
if (ThrowErrNonSerializable)
throw new NonSerializableException();
}
Assert.AreEqual(Exists, entry.Exists);
if (Remove)
entry.Remove();
else
entry.Value = entry.Value + arg;
return entry.Value;
}
/** <inheritdoc /> */
public int Process(IMutableCacheEntry<int, int> entry, int arg)
{
throw new Exception("Invalid method");
}
}
/// <summary>
/// Binary add processor.
/// </summary>
public class BinarizableAddArgCacheEntryProcessor : AddArgCacheEntryProcessor, IBinarizable
{
/** <inheritdoc /> */
public void WriteBinary(IBinaryWriter writer)
{
var w = writer.GetRawWriter();
w.WriteBoolean(ThrowErr);
w.WriteBoolean(ThrowErrBinarizable);
w.WriteBoolean(ThrowErrNonSerializable);
w.WriteInt(ThrowOnKey);
w.WriteBoolean(Remove);
w.WriteBoolean(Exists);
}
/** <inheritdoc /> */
public void ReadBinary(IBinaryReader reader)
{
var r = reader.GetRawReader();
ThrowErr = r.ReadBoolean();
ThrowErrBinarizable = r.ReadBoolean();
ThrowErrNonSerializable = r.ReadBoolean();
ThrowOnKey = r.ReadInt();
Remove = r.ReadBoolean();
Exists = r.ReadBoolean();
}
}
/// <summary>
/// Non-serializable processor.
/// </summary>
public class NonSerializableCacheEntryProcessor : AddArgCacheEntryProcessor, IBinarizable
{
/** <inheritdoc /> */
public void WriteBinary(IBinaryWriter writer)
{
throw new Exception("ExpectedException");
}
/** <inheritdoc /> */
public void ReadBinary(IBinaryReader reader)
{
throw new Exception("ExpectedException");
}
}
/// <summary>
/// Binary exception.
/// </summary>
public class BinarizableTestException : Exception, IBinarizable
{
/// <summary>
/// Gets or sets exception info.
/// </summary>
public string Info { get; set; }
/** <inheritdoc /> */
public override string Message
{
get { return Info; }
}
/** <inheritdoc /> */
public void WriteBinary(IBinaryWriter writer)
{
writer.GetRawWriter().WriteString(Info);
}
/** <inheritdoc /> */
public void ReadBinary(IBinaryReader reader)
{
Info = reader.GetRawReader().ReadString();
}
}
/// <summary>
/// Non-serializable exception.
/// </summary>
public class NonSerializableException : Exception, IBinarizable
{
/** <inheritdoc /> */
public void WriteBinary(IBinaryWriter writer)
{
throw new Exception("ExpectedException");
}
/** <inheritdoc /> */
public void ReadBinary(IBinaryReader reader)
{
throw new Exception("ExpectedException");
}
}
/// <summary>
///
/// </summary>
[SuppressMessage("ReSharper", "UnusedVariable")]
public abstract class CacheAbstractTest {
/// <summary>
///
/// </summary>
[TestFixtureSetUp]
public virtual void StartGrids() {
TestUtils.KillProcesses();
IgniteConfiguration cfg = new IgniteConfiguration();
BinaryConfiguration portCfg = new BinaryConfiguration();
ICollection<BinaryTypeConfiguration> portTypeCfgs = new List<BinaryTypeConfiguration>();
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizablePerson)));
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(CacheTestKey)));
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(TestReferenceObject)));
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableAddArgCacheEntryProcessor)));
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableTestException)));
portCfg.TypeConfigurations = portTypeCfgs;
cfg.BinaryConfiguration = portCfg;
cfg.JvmClasspath = TestUtils.CreateTestClasspath();
cfg.JvmOptions = TestUtils.TestJavaOptions();
cfg.SpringConfigUrl = "config\\native-client-test-cache.xml";
for (int i = 0; i < GridCount(); i++) {
cfg.IgniteInstanceName = "grid-" + i;
Ignition.Start(cfg);
}
Assert.AreEqual(GridCount(), GetIgnite(0).GetCluster().GetNodes().Count);
}
/// <summary>
///
/// </summary>
[TestFixtureTearDown]
public virtual void StopGrids() {
for (int i = 0; i < GridCount(); i++)
Ignition.Stop("grid-" + i, true);
}
/// <summary>
///
/// </summary>
[SetUp]
public virtual void BeforeTest()
{
Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name);
}
/// <summary>
///
/// </summary>
[TearDown]
public virtual void AfterTest() {
for (int i = 0; i < GridCount(); i++)
Cache(i).WithKeepBinary<object, object>().RemoveAll();
for (int i = 0; i < GridCount(); i++)
{
var cache = Cache(i);
var entries = cache.Select(pair => pair.ToString() + GetKeyAffinity(cache, pair.Key)).ToArray();
if (entries.Any())
Assert.Fail("Cache '{0}' is not empty in grid [{1}]: ({2})", CacheName(), i,
entries.Aggregate((acc, val) => string.Format("{0}, {1}", acc, val)));
var size = cache.GetSize();
Assert.AreEqual(0, size,
"Cache enumerator returned no entries, but cache '{0}' size is {1} in grid [{2}]",
CacheName(), size, i);
}
Console.WriteLine("Test finished: " + TestContext.CurrentContext.Test.Name);
}
public IIgnite GetIgnite(int idx)
{
return Ignition.GetIgnite("grid-" + idx);
}
public ICache<int, int> Cache(int idx) {
return Cache<int, int>(idx);
}
public ICache<TK, TV> Cache<TK, TV>(int idx) {
return GetIgnite(idx).GetCache<TK, TV>(CacheName());
}
public ICache<int, int> Cache()
{
return Cache<int, int>(0);
}
public ICache<TK, TV> Cache<TK, TV>()
{
return Cache<TK, TV>(0);
}
public ICacheAffinity Affinity()
{
return GetIgnite(0).GetAffinity(CacheName());
}
public ITransactions Transactions
{
get { return GetIgnite(0).GetTransactions(); }
}
[Test]
public void TestCircularReference()
{
var cache = Cache().WithKeepBinary<int, object>();
TestReferenceObject obj1 = new TestReferenceObject();
obj1.Obj = new TestReferenceObject(obj1);
cache.Put(1, obj1);
var po = (IBinaryObject) cache.Get(1);
Assert.IsNotNull(po);
TestReferenceObject objRef = po.Deserialize<TestReferenceObject>();
Assert.IsNotNull(objRef);
}
[Test]
public void TestName()
{
for (int i = 0; i < GridCount(); i++ )
Assert.AreEqual(CacheName(), Cache(i).Name);
}
[Test]
public void TestIsEmpty()
{
for (int i = 0; i < GridCount(); i++)
{
var cache = Cache(i);
Assert.IsTrue(cache.IsEmpty());
}
for (int i = 0; i < GridCount(); i++)
{
var cache = Cache(i);
cache.Put(PrimaryKeyForCache(cache), 1);
}
for (int i = 0; i < GridCount(); i++)
{
var cache = Cache(i);
Assert.IsFalse(cache.IsEmpty());
}
}
[Test]
public void TestContainsKey()
{
var cache = Cache();
int key = PrimaryKeyForCache(cache);
cache.Put(key, 1);
Assert.IsTrue(cache.ContainsKey(key));
Assert.IsFalse(cache.ContainsKey(-1));
}
[Test]
public void TestContainsKeys()
{
var cache = Cache();
var keys = PrimaryKeysForCache(cache, 5);
Assert.IsFalse(cache.ContainsKeys(keys));
cache.PutAll(keys.ToDictionary(k => k, k => k));
Assert.IsTrue(cache.ContainsKeys(keys));
Assert.IsFalse(cache.ContainsKeys(keys.Concat(new[] {int.MaxValue})));
}
[Test]
public void TestPeek()
{
var cache = Cache();
int key1 = PrimaryKeyForCache(cache);
cache.Put(key1, 1);
int val;
Assert.AreEqual(1, cache.LocalPeek(key1));
Assert.Throws<KeyNotFoundException>(() => cache.LocalPeek(-1));
Assert.IsFalse(cache.TryLocalPeek(-1, out val));
Assert.AreEqual(1, cache.LocalPeek(key1, CachePeekMode.All));
Assert.Throws<KeyNotFoundException>(() => cache.LocalPeek(-1, CachePeekMode.All));
Assert.AreEqual(false, cache.TryLocalPeek(-1, out val, CachePeekMode.All));
}
[Test]
public void TestGet()
{
var cache = Cache();
cache.Put(1, 1);
cache.Put(2, 2);
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.Throws<KeyNotFoundException>(() => cache.Get(3));
int value;
Assert.IsTrue(cache.TryGet(1, out value));
Assert.AreEqual(1, value);
Assert.IsTrue(cache.TryGet(2, out value));
Assert.AreEqual(2, value);
Assert.IsFalse(cache.TryGet(3, out value));
Assert.AreEqual(0, value);
}
[Test]
public void TestGetAsync()
{
var cache = Cache().WrapAsync();
cache.Put(1, 1);
cache.Put(2, 2);
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.IsFalse(cache.ContainsKey(3));
Assert.Throws<KeyNotFoundException>(() => cache.Get(3));
Assert.AreEqual(1, Cache().TryGetAsync(1).Result.Value);
Assert.IsFalse(Cache().TryGetAsync(3).Result.Success);
}
[Test]
public void TestGetAll()
{
var cache = Cache();
cache.Put(1, 1);
cache.Put(2, 2);
cache.Put(3, 3);
cache.Put(4, 4);
cache.Put(5, 5);
var map = cache.GetAll(new List<int> {0, 1, 2, 5}).ToDictionary(x => x.Key, x => x.Value);
Assert.AreEqual(3, map.Count);
Assert.AreEqual(1, map[1]);
Assert.AreEqual(2, map[2]);
}
[Test]
public void TestGetAllAsync()
{
var cache = Cache().WrapAsync();
cache.Put(1, 1);
cache.Put(2, 2);
cache.Put(3, 3);
var map = cache.GetAll(new List<int> {0, 1, 2}).ToDictionary(x => x.Key, x => x.Value);
Assert.AreEqual(2, map.Count);
Assert.AreEqual(1, map[1]);
Assert.AreEqual(2, map[2]);
}
[Test]
public void TestGetAndPut()
{
var cache = Cache();
Assert.AreEqual(false, cache.ContainsKey(1));
var old = cache.GetAndPut(1, 1);
Assert.IsFalse(old.Success);
Assert.AreEqual(1, cache.Get(1));
old = cache.GetAndPut(1, 2);
Assert.AreEqual(1, old.Value);
Assert.AreEqual(2, cache.Get(1));
}
[Test]
public void TestGetAndReplace()
{
var cache = Cache();
cache.Put(1, 10);
Assert.AreEqual(10, cache.GetAndReplace(1, 100).Value);
Assert.AreEqual(false, cache.GetAndReplace(2, 2).Success);
Assert.AreEqual(false, cache.ContainsKey(2));
Assert.AreEqual(100, cache.Get(1));
Assert.IsTrue(cache.Remove(1));
}
[Test]
public void TestGetAndRemove()
{
var cache = Cache();
cache.Put(1, 1);
Assert.AreEqual(1, cache.Get(1));
Assert.IsFalse(cache.GetAndRemove(0).Success);
Assert.AreEqual(1, cache.GetAndRemove(1).Value);
Assert.IsFalse(cache.GetAndRemove(1).Success);
Assert.IsFalse(cache.ContainsKey(1));
}
[Test]
public void TestGetAndPutAsync()
{
var cache = Cache().WrapAsync();
Assert.AreEqual(false, cache.ContainsKey(1));
var old = cache.GetAndPut(1, 1);
Assert.IsFalse(old.Success);
Assert.AreEqual(1, cache.Get(1));
old = cache.GetAndPut(1, 2);
Assert.AreEqual(1, old.Value);
Assert.AreEqual(2, cache.Get(1));
}
[Test]
public void TestPut()
{
var cache = Cache();
cache.Put(1, 1);
Assert.AreEqual(1, cache.Get(1));
}
[Test]
public void TestPutxAsync()
{
var cache = Cache().WrapAsync();
cache.Put(1, 1);
Assert.AreEqual(1, cache.Get(1));
}
[Test]
public void TestPutIfAbsent()
{
var cache = Cache();
Assert.IsFalse(cache.ContainsKey(1));
Assert.AreEqual(true, cache.PutIfAbsent(1, 1));
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(false, cache.PutIfAbsent(1, 2));
Assert.AreEqual(1, cache.Get(1));
}
[Test]
public void TestGetAndPutIfAbsent()
{
var cache = Cache();
Assert.IsFalse(cache.ContainsKey(1));
Assert.IsFalse(cache.GetAndPutIfAbsent(1, 1).Success);
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(1, cache.GetAndPutIfAbsent(1, 2).Value);
Assert.AreEqual(1, cache.Get(1));
}
[Test]
public void TestGetAndPutIfAbsentAsync()
{
var cache = Cache().WrapAsync();
Assert.IsFalse(cache.ContainsKey(1));
var old = cache.GetAndPutIfAbsent(1, 1);
Assert.IsFalse(old.Success);
Assert.AreEqual(1, cache.Get(1));
old = cache.GetAndPutIfAbsent(1, 2);
Assert.AreEqual(1, old.Value);
Assert.AreEqual(1, cache.Get(1));
}
[Test]
public void TestPutIfAbsentAsync()
{
var cache = Cache().WrapAsync();
Assert.Throws<KeyNotFoundException>(() => cache.Get(1));
Assert.IsFalse(cache.ContainsKey(1));
Assert.IsTrue(cache.PutIfAbsent(1, 1));
Assert.AreEqual(1, cache.Get(1));
Assert.IsFalse(cache.PutIfAbsent(1, 2));
Assert.AreEqual(1, cache.Get(1));
}
[Test]
public void TestReplace()
{
var cache = Cache();
Assert.IsFalse(cache.ContainsKey(1));
bool success = cache.Replace(1, 1);
Assert.AreEqual(false, success);
Assert.IsFalse(cache.ContainsKey(1));
cache.Put(1, 1);
Assert.AreEqual(1, cache.Get(1));
success = cache.Replace(1, 2);
Assert.AreEqual(true, success);
Assert.AreEqual(2, cache.Get(1));
Assert.IsFalse(cache.Replace(1, -1, 3));
Assert.AreEqual(2, cache.Get(1));
Assert.IsTrue(cache.Replace(1, 2, 3));
Assert.AreEqual(3, cache.Get(1));
}
[Test]
public void TestGetAndReplaceAsync()
{
var cache = Cache().WrapAsync();
Assert.IsFalse(cache.ContainsKey(1));
var old = cache.GetAndReplace(1, 1);
Assert.IsFalse(old.Success);
Assert.IsFalse(cache.ContainsKey(1));
cache.Put(1, 1);
Assert.AreEqual(1, cache.Get(1));
old = cache.GetAndReplace(1, 2);
Assert.AreEqual(1, old.Value);
Assert.AreEqual(2, cache.Get(1));
Assert.IsFalse(cache.Replace(1, -1, 3));
Assert.AreEqual(2, cache.Get(1));
Assert.IsTrue(cache.Replace(1, 2, 3));
Assert.AreEqual(3, cache.Get(1));
}
[Test]
public void TestReplacex()
{
var cache = Cache();
Assert.IsFalse(cache.ContainsKey(1));
Assert.IsFalse(cache.Replace(1, 1));
Assert.IsFalse(cache.ContainsKey(1));
cache.Put(1, 1);
Assert.AreEqual(1, cache.Get(1));
Assert.IsTrue(cache.Replace(1, 2));
Assert.AreEqual(2, cache.Get(1));
}
[Test]
public void TestReplaceAsync()
{
var cache = Cache().WrapAsync();
Assert.IsFalse(cache.ContainsKey(1));
Assert.IsFalse(cache.Replace(1, 1));
Assert.IsFalse(cache.ContainsKey(1));
cache.Put(1, 1);
Assert.AreEqual(1, cache.Get(1));
Assert.IsTrue(cache.Replace(1, 2));
Assert.AreEqual(2, cache.Get(1));
}
[Test]
public void TestPutAll()
{
var cache = Cache();
cache.PutAll(new Dictionary<int, int> { { 1, 1 }, { 2, 2 }, { 3, 3 } });
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.AreEqual(3, cache.Get(3));
}
[Test]
public void TestPutAllAsync()
{
var cache = Cache().WrapAsync();
cache.PutAll(new Dictionary<int, int> { { 1, 1 }, { 2, 2 }, { 3, 3 } });
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.AreEqual(3, cache.Get(3));
}
/// <summary>
/// Expiry policy tests.
/// </summary>
[Test]
public void TestWithExpiryPolicy()
{
TestWithExpiryPolicy((cache, policy) => cache.WithExpiryPolicy(policy), true);
}
/// <summary>
/// Expiry policy tests.
/// </summary>
[Test]
public void TestCacheConfigurationExpiryPolicy()
{
TestWithExpiryPolicy((cache, policy) =>
{
var cfg = cache.GetConfiguration();
cfg.Name = string.Format("expiryPolicyCache_{0}_{1}", GetType().Name, policy.GetHashCode());
cfg.ExpiryPolicyFactory = new ExpiryPolicyFactory(policy);
return cache.Ignite.CreateCache<int, int>(cfg);
}, false);
}
/// <summary>
/// Expiry policy tests.
/// </summary>
public void TestWithExpiryPolicy(Func<ICache<int, int>, IExpiryPolicy, ICache<int, int>> withPolicyFunc,
bool origCache)
{
ICache<int, int> cache0 = Cache(0);
int key0;
int key1;
if (LocalCache())
{
key0 = 0;
key1 = 1;
}
else
{
key0 = PrimaryKeyForCache(cache0);
key1 = PrimaryKeyForCache(Cache(1));
}
// Test unchanged expiration.
ICache<int, int> cache = withPolicyFunc(cache0, new ExpiryPolicy(null, null, null));
cache0 = origCache ? cache0 : cache;
cache.Put(key0, key0);
cache.Put(key1, key1);
Thread.Sleep(200);
Assert.IsTrue(cache0.ContainsKey(key0));
Assert.IsTrue(cache0.ContainsKey(key1));
cache.Put(key0, key0 + 1);
cache.Put(key1, key1 + 1);
Thread.Sleep(200);
Assert.IsTrue(cache0.ContainsKey(key0));
Assert.IsTrue(cache0.ContainsKey(key1));
cache.Get(key0);
cache.Get(key1);
Thread.Sleep(200);
Assert.IsTrue(cache0.ContainsKey(key0));
Assert.IsTrue(cache0.ContainsKey(key1));
cache0.RemoveAll(new List<int> { key0, key1 });
// Test eternal expiration.
cache = withPolicyFunc(cache0, new ExpiryPolicy(TimeSpan.MaxValue, TimeSpan.MaxValue, TimeSpan.MaxValue));
cache0 = origCache ? cache0 : cache;
cache.Put(key0, key0);
cache.Put(key1, key1);
Thread.Sleep(200);
Assert.IsTrue(cache0.ContainsKey(key0));
Assert.IsTrue(cache0.ContainsKey(key1));
cache.Put(key0, key0 + 1);
cache.Put(key1, key1 + 1);
Thread.Sleep(200);
Assert.IsTrue(cache0.ContainsKey(key0));
Assert.IsTrue(cache0.ContainsKey(key1));
cache.Get(key0);
cache.Get(key1);
Thread.Sleep(200);
Assert.IsTrue(cache0.ContainsKey(key0));
Assert.IsTrue(cache0.ContainsKey(key1));
cache0.RemoveAll(new List<int> { key0, key1 });
// Test regular expiration.
cache = withPolicyFunc(cache0, new ExpiryPolicy(TimeSpan.FromMilliseconds(100),
TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(100)));
cache0 = origCache ? cache0 : cache;
cache.Put(key0, key0);
cache.Put(key1, key1);
Assert.IsTrue(cache0.ContainsKey(key0));
Assert.IsTrue(cache0.ContainsKey(key1));
Thread.Sleep(200);
Assert.IsFalse(cache0.ContainsKey(key0));
Assert.IsFalse(cache0.ContainsKey(key1));
cache0.Put(key0, key0);
cache0.Put(key1, key1);
cache.Put(key0, key0 + 1);
cache.Put(key1, key1 + 1);
Assert.IsTrue(cache0.ContainsKey(key0));
Assert.IsTrue(cache0.ContainsKey(key1));
Thread.Sleep(200);
Assert.IsFalse(cache0.ContainsKey(key0));
Assert.IsFalse(cache0.ContainsKey(key1));
// Test sliding expiration
cache0.Put(key0, key0);
cache0.Put(key1, key1);
for (var i = 0; i < 3; i++)
{
Thread.Sleep(50);
// Prolong expiration by touching the entry
cache.Get(key0);
cache.Get(key1);
}
Assert.IsTrue(cache0.ContainsKey(key0));
Assert.IsTrue(cache0.ContainsKey(key1));
Thread.Sleep(200);
Assert.IsFalse(cache0.ContainsKey(key0));
Assert.IsFalse(cache0.ContainsKey(key1));
}
/// <summary>
/// Expiry policy tests for zero and negative expiry values.
/// </summary>
[Test]
[Ignore("IGNITE-1423")]
public void TestWithExpiryPolicyZeroNegative()
{
ICache<int, int> cache0 = Cache(0);
int key0;
int key1;
if (LocalCache())
{
key0 = 0;
key1 = 1;
}
else
{
key0 = PrimaryKeyForCache(cache0);
key1 = PrimaryKeyForCache(Cache(1));
}
// Test zero expiration.
var cache = cache0.WithExpiryPolicy(new ExpiryPolicy(TimeSpan.Zero, TimeSpan.Zero, TimeSpan.Zero));
cache.Put(key0, key0);
cache.Put(key1, key1);
Assert.IsFalse(cache0.ContainsKey(key0));
Assert.IsFalse(cache0.ContainsKey(key1));
cache0.Put(key0, key0);
cache0.Put(key1, key1);
Assert.IsTrue(cache0.ContainsKey(key0));
Assert.IsTrue(cache0.ContainsKey(key1));
cache.Put(key0, key0 + 1);
cache.Put(key1, key1 + 1);
Assert.IsFalse(cache0.ContainsKey(key0));
Assert.IsFalse(cache0.ContainsKey(key1));
cache0.Put(key0, key0);
cache0.Put(key1, key1);
cache.Get(key0);
cache.Get(key1);
Assert.IsFalse(cache0.ContainsKey(key0));
Assert.IsFalse(cache0.ContainsKey(key1));
cache0.RemoveAll(new List<int> { key0, key1 });
// Test negative expiration.
cache = cache0.WithExpiryPolicy(new ExpiryPolicy(TimeSpan.FromMilliseconds(-100),
TimeSpan.FromMilliseconds(-100), TimeSpan.FromMilliseconds(-100)));
cache.Put(key0, key0);
cache.Put(key1, key1);
Assert.IsFalse(cache0.ContainsKey(key0));
Assert.IsFalse(cache0.ContainsKey(key1));
cache0.Put(key0, key0);
cache0.Put(key1, key1);
Assert.IsTrue(cache0.ContainsKey(key0));
Assert.IsTrue(cache0.ContainsKey(key1));
cache.Put(key0, key0 + 1);
cache.Put(key1, key1 + 1);
Assert.IsFalse(cache0.ContainsKey(key0));
Assert.IsFalse(cache0.ContainsKey(key1));
cache0.Put(key0, key0);
cache0.Put(key1, key1);
cache.Get(key0);
cache.Get(key1);
Assert.IsFalse(cache0.ContainsKey(key0));
Assert.IsFalse(cache0.ContainsKey(key1));
cache0.RemoveAll(new List<int> { key0, key1 });
}
[Test]
[Ignore("IGNITE-4535")]
public void TestEvict()
{
var cache = Cache();
int key = PrimaryKeyForCache(cache);
cache.Put(key, 1);
Assert.AreEqual(1, PeekInt(cache, key));
cache.LocalEvict(new[] {key});
Assert.AreEqual(0, cache.GetLocalSize(CachePeekMode.Onheap));
Assert.AreEqual(0, PeekInt(cache, key));
Assert.AreEqual(1, cache.Get(key));
Assert.AreEqual(1, cache.GetLocalSize(CachePeekMode.Onheap));
Assert.AreEqual(1, PeekInt(cache, key));
}
[Test]
[Ignore("IGNITE-4535")]
public void TestEvictAllKeys()
{
var cache = Cache();
List<int> keys = PrimaryKeysForCache(cache, 3);
cache.Put(keys[0], 1);
cache.Put(keys[1], 2);
cache.Put(keys[2], 3);
Assert.AreEqual(1, PeekInt(cache, keys[0]));
Assert.AreEqual(2, PeekInt(cache, keys[1]));
Assert.AreEqual(3, PeekInt(cache, keys[2]));
cache.LocalEvict(new List<int> { -1, keys[0], keys[1] });
Assert.AreEqual(1, cache.GetLocalSize(CachePeekMode.Onheap));
Assert.AreEqual(0, PeekInt(cache, keys[0]));
Assert.AreEqual(0, PeekInt(cache, keys[1]));
Assert.AreEqual(3, PeekInt(cache, keys[2]));
Assert.AreEqual(1, cache.Get(keys[0]));
Assert.AreEqual(2, cache.Get(keys[1]));
Assert.AreEqual(3, cache.GetLocalSize());
Assert.AreEqual(1, PeekInt(cache, keys[0]));
Assert.AreEqual(2, PeekInt(cache, keys[1]));
Assert.AreEqual(3, PeekInt(cache, keys[2]));
}
[Test]
public void TestClear()
{
for (int i = 0; i < GridCount(); i++)
{
var cache = Cache(i);
cache.Put(PrimaryKeyForCache(cache, 500), 1);
Assert.IsFalse(cache.IsEmpty());
}
Cache().Clear();
for (int i = 0; i < GridCount(); i++)
Assert.IsTrue(Cache(i).IsEmpty());
}
[Test]
public void TestClearKey()
{
var cache = Cache();
var keys = PrimaryKeysForCache(cache, 10);
foreach (var key in keys)
cache.Put(key, 3);
var i = cache.GetSize();
foreach (var key in keys)
{
cache.Clear(key);
Assert.IsFalse(cache.ContainsKey(key));
Assert.Throws<KeyNotFoundException>(() => cache.Get(key));
Assert.Less(cache.GetSize(), i);
i = cache.GetSize();
}
}
[Test]
public void TestClearKeys()
{
var cache = Cache();
var keys = PrimaryKeysForCache(cache, 10);
foreach (var key in keys)
cache.Put(key, 3);
cache.ClearAll(keys);
Assert.IsFalse(cache.ContainsKeys(keys));
}
[Test]
public void TestLocalClearKey()
{
var cache = Cache();
var keys = PrimaryKeysForCache(cache, 10);
foreach (var key in keys)
cache.Put(key, 3);
var i = cache.GetSize();
foreach (var key in keys)
{
cache.LocalClear(key);
int val;
Assert.IsFalse(cache.TryLocalPeek(key, out val));
Assert.Less(cache.GetSize(), i);
i = cache.GetSize();
}
cache.Clear();
}
[Test]
public void TestLocalClearKeys()
{
var cache = Cache();
var keys = PrimaryKeysForCache(cache, 10);
foreach (var key in keys)
cache.Put(key, 3);
cache.LocalClearAll(keys);
int val;
foreach (var key in keys)
Assert.IsFalse(cache.TryLocalPeek(key, out val));
cache.Clear();
}
[Test]
public void TestRemove()
{
var cache = Cache();
cache.Put(1, 1);
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(true, cache.Remove(1));
Assert.AreEqual(0, cache.GetSize());
Assert.IsFalse(cache.ContainsKey(1));
cache.Put(1, 1);
Assert.AreEqual(1, cache.Get(1));
Assert.IsFalse(cache.Remove(1, -1));
Assert.IsTrue(cache.Remove(1, 1));
Assert.AreEqual(0, cache.GetSize());
Assert.IsFalse(cache.ContainsKey(1));
}
[Test]
public void TestGetAndRemoveAsync()
{
var cache = Cache().WrapAsync();
cache.Put(1, 1);
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(1, cache.GetAndRemove(1).Value);
Assert.AreEqual(0, cache.GetSize());
Assert.IsFalse(cache.ContainsKey(1));
cache.Put(1, 1);
Assert.AreEqual(1, cache.Get(1));
Assert.IsFalse(cache.Remove(1, -1));
Assert.IsTrue(cache.Remove(1, 1));
Assert.AreEqual(0, cache.GetSize());
Assert.IsFalse(cache.ContainsKey(1));
}
[Test]
public void TestRemovex()
{
var cache = Cache();
cache.Put(1, 1);
Assert.AreEqual(1, cache.Get(1));
Assert.IsFalse(cache.Remove(-1));
Assert.IsTrue(cache.Remove(1));
Assert.AreEqual(0, cache.GetSize());
Assert.IsFalse(cache.ContainsKey(1));
}
[Test]
public void TestRemoveAsync()
{
var cache = Cache().WrapAsync();
cache.Put(1, 1);
Assert.AreEqual(1, cache.Get(1));
Assert.IsFalse(cache.Remove(-1));
Assert.IsTrue(cache.Remove(1));
Assert.AreEqual(0, cache.GetSize());
Assert.IsFalse(cache.ContainsKey(1));
}
[Test]
public void TestRemoveAll()
{
var cache = Cache();
var keys = PrimaryKeysForCache(cache, 2);
cache.Put(keys[0], 1);
cache.Put(keys[1], 2);
Assert.AreEqual(1, cache.Get(keys[0]));
Assert.AreEqual(2, cache.Get(keys[1]));
cache.RemoveAll();
Assert.AreEqual(0, cache.GetSize());
Assert.IsFalse(cache.ContainsKeys(keys));
}
[Test]
public void TestRemoveAllAsync()
{
var cache = Cache().WrapAsync();
List<int> keys = PrimaryKeysForCache(cache, 2);
cache.Put(keys[0], 1);
cache.Put(keys[1], 2);
Assert.AreEqual(1, cache.Get(keys[0]));
Assert.AreEqual(2, cache.Get(keys[1]));
cache.RemoveAll();
Assert.AreEqual(0, cache.GetSize());
Assert.IsFalse(cache.ContainsKeys(keys));
}
[Test]
public void TestRemoveAllKeys()
{
var cache = Cache();
Assert.AreEqual(0, cache.GetSize());
cache.Put(1, 1);
cache.Put(2, 2);
cache.Put(3, 3);
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.AreEqual(3, cache.Get(3));
cache.RemoveAll(new List<int> { 0, 1, 2 });
Assert.AreEqual(1, cache.GetSize(CachePeekMode.Primary));
Assert.IsFalse(cache.ContainsKeys(new[] {1, 2}));
Assert.AreEqual(3, cache.Get(3));
}
[Test]
public void TestRemoveAllKeysAsync()
{
var cache = Cache().WrapAsync();
Assert.AreEqual(0, cache.GetSize());
cache.Put(1, 1);
cache.Put(2, 2);
cache.Put(3, 3);
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.AreEqual(3, cache.Get(3));
cache.RemoveAll(new List<int> { 0, 1, 2 });
Assert.AreEqual(1, cache.GetSize(CachePeekMode.Primary));
Assert.IsFalse(cache.ContainsKeys(new[] {1, 2}));
Assert.AreEqual(3, cache.Get(3));
}
[Test]
public void TestSizes()
{
for (int i = 0; i < GridCount(); i++)
{
var cache = Cache(i);
List<int> keys = PrimaryKeysForCache(cache, 2);
foreach (int key in keys)
cache.Put(key, 1);
Assert.IsTrue(cache.GetSize() >= 2);
Assert.AreEqual(2, cache.GetLocalSize(CachePeekMode.Primary));
}
ICache<int, int> cache0 = Cache();
Assert.AreEqual(GridCount() * 2, cache0.GetSize(CachePeekMode.Primary));
if (!LocalCache() && !ReplicatedCache())
{
int nearKey = NearKeyForCache(cache0);
cache0.Put(nearKey, 1);
Assert.AreEqual(NearEnabled() ? 1 : 0, cache0.GetSize(CachePeekMode.Near));
}
}
[Test]
public void TestLocalSize()
{
var cache = Cache();
var keys = PrimaryKeysForCache(cache, 3);
cache.Put(keys[0], 1);
cache.Put(keys[1], 2);
var localSize = cache.GetLocalSize();
cache.LocalEvict(keys.Take(2).ToArray());
//Assert.AreEqual(0, cache.GetLocalSize(CachePeekMode.Onheap)); // TODO: IGNITE-4535
Assert.AreEqual(localSize, cache.GetLocalSize(CachePeekMode.All));
cache.Put(keys[2], 3);
Assert.AreEqual(localSize + 1, cache.GetLocalSize(CachePeekMode.All));
cache.RemoveAll(keys.Take(2).ToArray());
}
/// <summary>
/// Test enumerators.
/// </summary>
[Test]
[SuppressMessage("ReSharper", "PossibleMultipleEnumeration")]
public void TestEnumerators()
{
var cache = Cache();
var keys = PrimaryKeysForCache(cache, 2);
cache.Put(keys[0], keys[0] + 1);
cache.Put(keys[1], keys[1] + 1);
// Check distributed enumerator.
IEnumerable<ICacheEntry<int, int>> e = cache;
CheckEnumerator(e.GetEnumerator(), keys);
CheckEnumerator(e.GetEnumerator(), keys);
// Check local enumerator.
e = cache.GetLocalEntries();
CheckEnumerator(e.GetEnumerator(), keys);
CheckEnumerator(e.GetEnumerator(), keys);
// Evict and check peek modes.
cache.LocalEvict(new List<int> { keys[0] } );
// TODO: IGNITE-4535
//e = cache.GetLocalEntries(CachePeekMode.Onheap);
//CheckEnumerator(e.GetEnumerator(), new List<int> { keys[1] });
//CheckEnumerator(e.GetEnumerator(), new List<int> { keys[1] });
e = cache.GetLocalEntries(CachePeekMode.All);
CheckEnumerator(e.GetEnumerator(), keys);
CheckEnumerator(e.GetEnumerator(), keys);
cache.Remove(keys[0]);
}
/// <summary>
/// Check enumerator content.
/// </summary>
/// <param name="e">Enumerator.</param>
/// <param name="keys">Keys.</param>
private static void CheckEnumerator(IEnumerator<ICacheEntry<int, int>> e, IList<int> keys)
{
CheckEnumerator0(e, keys);
e.Reset();
CheckEnumerator0(e, keys);
e.Dispose();
Assert.Throws<ObjectDisposedException>(() => { e.MoveNext(); });
Assert.Throws<ObjectDisposedException>(() => { var entry = e.Current; });
Assert.Throws<ObjectDisposedException>(e.Reset);
e.Dispose();
}
/// <summary>
/// Check enumerator content.
/// </summary>
/// <param name="e">Enumerator.</param>
/// <param name="keys">Keys.</param>
private static void CheckEnumerator0(IEnumerator<ICacheEntry<int, int>> e, IList<int> keys)
{
Assert.Throws<InvalidOperationException>(() => { var entry = e.Current; });
int cnt = 0;
while (e.MoveNext())
{
ICacheEntry<int, int> entry = e.Current;
Assert.IsTrue(keys.Contains(entry.Key), "Unexpected entry: " + entry);
Assert.AreEqual(entry.Key + 1, entry.Value);
cnt++;
}
Assert.AreEqual(keys.Count, cnt);
Assert.IsFalse(e.MoveNext());
Assert.Throws<InvalidOperationException>(() => { var entry = e.Current; });
}
[Test]
[Ignore("IGNITE-4535")]
public void TestPromote()
{
var cache = Cache();
int key = PrimaryKeyForCache(cache);
cache.Put(key, 1);
Assert.AreEqual(1, PeekInt(cache, key));
cache.LocalEvict(new[] {key});
Assert.AreEqual(0, cache.GetLocalSize(CachePeekMode.Onheap));
Assert.AreEqual(0, PeekInt(cache, key));
cache.LocalPromote(new[] { key });
Assert.AreEqual(1, cache.GetLocalSize(CachePeekMode.Onheap));
Assert.AreEqual(1, PeekInt(cache, key));
}
[Test]
[Ignore("IGNITE-4535")]
public void TestPromoteAll()
{
var cache = Cache();
List<int> keys = PrimaryKeysForCache(cache, 3);
cache.Put(keys[0], 1);
cache.Put(keys[1], 2);
cache.Put(keys[2], 3);
Assert.AreEqual(1, PeekInt(cache, keys[0]));
Assert.AreEqual(2, PeekInt(cache, keys[1]));
Assert.AreEqual(3, PeekInt(cache, keys[2]));
cache.LocalEvict(new List<int> { -1, keys[0], keys[1] });
Assert.AreEqual(1, cache.GetLocalSize(CachePeekMode.Onheap));
Assert.AreEqual(0, PeekInt(cache, keys[0]));
Assert.AreEqual(0, PeekInt(cache, keys[1]));
Assert.AreEqual(3, PeekInt(cache, keys[2]));
cache.LocalPromote(new[] {keys[0], keys[1]});
Assert.AreEqual(3, cache.GetLocalSize(CachePeekMode.Onheap));
Assert.AreEqual(1, PeekInt(cache, keys[0]));
Assert.AreEqual(2, PeekInt(cache, keys[1]));
Assert.AreEqual(3, PeekInt(cache, keys[2]));
}
[Test]
public void TestPutGetBinary()
{
var cache = Cache<int, BinarizablePerson>();
BinarizablePerson obj1 = new BinarizablePerson("obj1", 1);
cache.Put(1, obj1);
obj1 = cache.Get(1);
Assert.AreEqual("obj1", obj1.Name);
Assert.AreEqual(1, obj1.Age);
}
[Test]
public void TestPutGetBinaryAsync()
{
var cache = Cache<int, BinarizablePerson>().WrapAsync();
BinarizablePerson obj1 = new BinarizablePerson("obj1", 1);
cache.Put(1, obj1);
obj1 = cache.Get(1);
Assert.AreEqual("obj1", obj1.Name);
Assert.AreEqual(1, obj1.Age);
}
[Test]
public void TestPutGetBinaryKey()
{
var cache = Cache<CacheTestKey, string>();
int cnt = 100;
for (int i = 0; i < cnt; i++)
cache.Put(new CacheTestKey(i), "val-" + i);
for (int i = 0; i < cnt; i++)
Assert.AreEqual("val-" + i, cache.Get(new CacheTestKey(i)));
}
[Test]
public void TestGetAsync2()
{
var cache = Cache();
for (int i = 0; i < 100; i++)
cache.Put(i, i);
var futs = new List<Task<int>>();
for (int i = 0; i < 1000; i++)
{
futs.Add(cache.GetAsync(i % 100));
}
for (int i = 0; i < 1000; i++) {
Assert.AreEqual(i % 100, futs[i].Result, "Unexpected result: " + i);
Assert.IsTrue(futs[i].IsCompleted);
}
}
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestGetAsyncMultithreaded()
{
var cache = Cache();
for (int i = 0; i < 100; i++)
cache.Put(i, i);
TestUtils.RunMultiThreaded(() =>
{
for (int i = 0; i < 100; i++)
{
var futs = new List<Task<int>>();
for (int j = 0; j < 100; j++)
futs.Add(cache.GetAsync(j));
for (int j = 0; j < 100; j++)
Assert.AreEqual(j, futs[j].Result);
}
}, 10);
}
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestPutxAsyncMultithreaded()
{
var cache = Cache();
TestUtils.RunMultiThreaded(() =>
{
Random rnd = new Random();
for (int i = 0; i < 50; i++)
{
var futs = new List<Task>();
for (int j = 0; j < 10; j++)
futs.Add(cache.PutAsync(rnd.Next(1000), i));
foreach (var fut in futs)
fut.Wait();
}
}, 5);
}
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestPutGetAsyncMultithreaded()
{
var cache = Cache<CacheTestKey, BinarizablePerson>();
const int threads = 10;
const int objPerThread = 1000;
int cntr = 0;
TestUtils.RunMultiThreaded(() =>
{
// ReSharper disable once AccessToModifiedClosure
int threadIdx = Interlocked.Increment(ref cntr);
var futs = new List<Task>();
for (int i = 0; i < objPerThread; i++)
{
int key = threadIdx * objPerThread + i;
futs.Add(cache.PutAsync(new CacheTestKey(key), new BinarizablePerson("Person-" + key, key)));
}
foreach (var fut in futs)
{
fut.Wait();
Assert.IsTrue(fut.IsCompleted);
}
}, threads);
for (int i = 0; i < threads; i++)
{
int threadIdx = i + 1;
for (int j = 0; j < objPerThread; j++)
{
int key = threadIdx * objPerThread + i;
var p = cache.GetAsync(new CacheTestKey(key)).Result;
Assert.IsNotNull(p);
Assert.AreEqual(key, p.Age);
Assert.AreEqual("Person-" + key, p.Name);
}
}
cntr = 0;
TestUtils.RunMultiThreaded(() =>
{
int threadIdx = Interlocked.Increment(ref cntr);
for (int i = 0; i < objPerThread; i++)
{
int key = threadIdx * objPerThread + i;
cache.PutAsync(new CacheTestKey(key), new BinarizablePerson("Person-" + key, key)).Wait();
}
}, threads);
cntr = 0;
TestUtils.RunMultiThreaded(() =>
{
int threadIdx = Interlocked.Increment(ref cntr);
var futs = new List<Task<BinarizablePerson>>();
for (int i = 0; i < objPerThread; i++)
{
int key = threadIdx * objPerThread + i;
futs.Add(cache.GetAsync(new CacheTestKey(key)));
}
for (int i = 0; i < objPerThread; i++)
{
var fut = futs[i];
int key = threadIdx * objPerThread + i;
var p = fut.Result;
Assert.IsNotNull(p);
Assert.AreEqual(key, p.Age);
Assert.AreEqual("Person-" + key, p.Name);
}
}, threads);
}
//[Test]
//[Category(TestUtils.CATEGORY_INTENSIVE)]
public void TestAsyncMultithreadedKeepBinary()
{
var cache = Cache().WithKeepBinary<CacheTestKey, BinarizablePerson>();
var portCache = Cache().WithKeepBinary<CacheTestKey, IBinaryObject>();
const int threads = 10;
const int objPerThread = 1000;
int cntr = 0;
TestUtils.RunMultiThreaded(() =>
{
// ReSharper disable once AccessToModifiedClosure
int threadIdx = Interlocked.Increment(ref cntr);
var futs = new List<Task>();
for (int i = 0; i < objPerThread; i++)
{
int key = threadIdx * objPerThread + i;
var task = cache.PutAsync(new CacheTestKey(key), new BinarizablePerson("Person-" + key, key));
futs.Add(task);
}
foreach (var fut in futs)
fut.Wait();
}, threads);
for (int i = 0; i < threads; i++)
{
int threadIdx = i + 1;
for (int j = 0; j < objPerThread; j++)
{
int key = threadIdx * objPerThread + i;
IBinaryObject p = portCache.Get(new CacheTestKey(key));
Assert.IsNotNull(p);
Assert.AreEqual(key, p.GetField<int>("age"));
Assert.AreEqual("Person-" + key, p.GetField<string>("name"));
}
}
cntr = 0;
TestUtils.RunMultiThreaded(() =>
{
int threadIdx = Interlocked.Increment(ref cntr);
var futs = new List<Task<IBinaryObject>>();
for (int i = 0; i < objPerThread; i++)
{
int key = threadIdx * objPerThread + i;
futs.Add(portCache.GetAsync(new CacheTestKey(key)));
}
for (int i = 0; i < objPerThread; i++)
{
var fut = futs[i];
int key = threadIdx * objPerThread + i;
var p = fut.Result;
Assert.IsNotNull(p);
Assert.AreEqual(key, p.GetField<int>("age"));
Assert.AreEqual("Person-" + key, p.GetField<string>("name"));
}
}, threads);
cntr = 0;
TestUtils.RunMultiThreaded(() =>
{
int threadIdx = Interlocked.Increment(ref cntr);
var futs = new List<Task<bool>>();
for (int i = 0; i < objPerThread; i++)
{
int key = threadIdx * objPerThread + i;
futs.Add(cache.RemoveAsync(new CacheTestKey(key)));
}
for (int i = 0; i < objPerThread; i++)
{
var fut = futs[i];
Assert.IsTrue(fut.Result);
}
}, threads);
}
/// <summary>
/// Test thraed-locals leak.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestThreadLocalLeak()
{
var cache = Cache<string, string>();
Exception err = null;
const int threadCnt = 10;
Thread[] threads = new Thread[threadCnt];
ThreadStart[] threadStarts = new ThreadStart[threadCnt];
for (int j = 0; j < threadCnt; j++)
{
string key = "key" + j;
threadStarts[j] = () =>
{
try
{
cache.Put(key, key);
Assert.AreEqual(key, cache.Get(key));
}
catch (Exception e)
{
Interlocked.CompareExchange(ref err, e, null);
Assert.Fail("Unexpected error: " + e);
}
};
}
for (int i = 0; i < 100 && err == null; i++)
{
for (int j = 0 ; j < threadCnt; j++) {
Thread t = new Thread(threadStarts[j]);
threads[j] = t;
}
foreach (Thread t in threads)
t.Start();
foreach (Thread t in threads)
t.Join();
if (i % 500 == 0)
{
Console.WriteLine("Iteration: " + i);
GC.Collect();
}
}
Assert.IsNull(err);
}
/**
* Test tries to provoke garbage collection for .Net future before it was completed to verify
* futures pinning works.
*/
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestFuturesGc()
{
var cache = Cache();
cache.PutAsync(1, 1);
for (int i = 0; i < 10; i++)
{
TestUtils.RunMultiThreaded(() =>
{
for (int j = 0; j < 1000; j++)
cache.GetAsync(1);
}, 5);
GC.Collect();
Assert.AreEqual(1, cache.GetAsync(1).Result);
}
Thread.Sleep(2000);
}
[Test]
public void TestPartitions()
{
ICacheAffinity aff = Affinity();
for (int i = 0; i < 5; i++ )
Assert.AreEqual(CachePartitions(), aff.Partitions);
}
[Test]
public void TestKeyPartition()
{
ICacheAffinity aff = Affinity();
{
ISet<int> parts = new HashSet<int>();
for (int i = 0; i < 1000; i++)
parts.Add(aff.GetPartition(i));
if (LocalCache())
Assert.AreEqual(1, parts.Count);
else
Assert.IsTrue(parts.Count > 10);
}
{
ISet<int> parts = new HashSet<int>();
for (int i = 0; i < 1000; i++)
parts.Add(aff.GetPartition("key" + i));
if (LocalCache())
Assert.AreEqual(1, parts.Count);
else
Assert.IsTrue(parts.Count > 10);
}
}
[Test]
public void TestIsPrimaryOrBackup()
{
ICacheAffinity aff = Affinity();
ICollection<IClusterNode> nodes = GetIgnite(0).GetCluster().GetNodes();
Assert.IsTrue(nodes.Count > 0);
IClusterNode node = nodes.First();
{
bool found = false;
for (int i = 0; i < 1000; i++)
{
if (aff.IsPrimary(node, i))
{
Assert.IsTrue(aff.IsPrimaryOrBackup(node, i));
found = true;
if (nodes.Count > 1)
Assert.IsFalse(aff.IsPrimary(nodes.Last(), i));
break;
}
}
Assert.IsTrue(found, "Failed to find primary key for node " + node);
}
if (nodes.Count > 1)
{
bool found = false;
for (int i = 0; i < 1000; i++)
{
if (aff.IsBackup(node, i))
{
Assert.IsTrue(aff.IsPrimaryOrBackup(node, i));
found = true;
break;
}
}
Assert.IsTrue(found, "Failed to find backup key for node " + node);
}
}
[Test]
public void TestNodePartitions()
{
ICacheAffinity aff = Affinity();
ICollection<IClusterNode> nodes = GetIgnite(0).GetCluster().GetNodes();
Assert.IsTrue(nodes.Count > 0);
if (nodes.Count == 1)
{
IClusterNode node = nodes.First();
int[] parts = aff.GetBackupPartitions(node);
Assert.AreEqual(0, parts.Length);
parts = aff.GetAllPartitions(node);
Assert.AreEqual(CachePartitions(), parts.Length);
}
else
{
IList<int> allPrimaryParts = new List<int>();
IList<int> allBackupParts = new List<int>();
IList<int> allParts = new List<int>();
foreach(IClusterNode node in nodes) {
int[] parts = aff.GetPrimaryPartitions(node);
foreach (int part in parts)
allPrimaryParts.Add(part);
parts = aff.GetBackupPartitions(node);
foreach (int part in parts)
allBackupParts.Add(part);
parts = aff.GetAllPartitions(node);
foreach (int part in parts)
allParts.Add(part);
}
Assert.AreEqual(CachePartitions(), allPrimaryParts.Count);
Assert.AreEqual(CachePartitions() * Backups(), allBackupParts.Count);
Assert.AreEqual(CachePartitions() * (Backups() + 1), allParts.Count);
}
}
[Test]
public void TestAffinityKey()
{
ICacheAffinity aff = Affinity();
Assert.AreEqual(10, aff.GetAffinityKey<int, int>(10));
Assert.AreEqual("string", aff.GetAffinityKey<string, string>("string"));
}
[Test]
public void TestMapToNode()
{
ICacheAffinity aff = Affinity();
const int key = 1;
IClusterNode node = aff.MapKeyToNode(key);
Assert.IsNotNull(node);
Assert.IsTrue(GetIgnite(0).GetCluster().GetNodes().Contains(node));
Assert.IsTrue(aff.IsPrimary(node, key));
Assert.IsTrue(aff.IsPrimaryOrBackup(node, key));
Assert.IsFalse(aff.IsBackup(node, key));
int part = aff.GetPartition(key);
IClusterNode partNode = aff.MapPartitionToNode(part);
Assert.AreEqual(node, partNode);
}
[Test]
public void TestMapToPrimaryAndBackups()
{
ICacheAffinity aff = Affinity();
const int key = 1;
IList<IClusterNode> nodes = aff.MapKeyToPrimaryAndBackups(key);
Assert.IsTrue(nodes.Count > 0);
for (int i = 0; i < nodes.Count; i++)
{
if (i == 0)
Assert.IsTrue(aff.IsPrimary(nodes[i], key));
else
Assert.IsTrue(aff.IsBackup(nodes[i], key));
}
int part = aff.GetPartition(key);
IList<IClusterNode> partNodes = aff.MapPartitionToPrimaryAndBackups(part);
Assert.AreEqual(nodes, partNodes);
}
[Test]
public void TestMapKeysToNodes()
{
ICacheAffinity aff = Affinity();
IList<int> keys = new List<int> {1, 2, 3};
IDictionary<IClusterNode, IList<int>> map = aff.MapKeysToNodes(keys);
Assert.IsTrue(map.Count > 0);
foreach (int key in keys)
{
IClusterNode primary = aff.MapKeyToNode(key);
Assert.IsTrue(map.ContainsKey(primary));
IList<int> nodeKeys = map[primary];
Assert.IsNotNull(nodeKeys);
Assert.IsTrue(nodeKeys.Contains(key));
}
}
[Test]
public void TestMapPartitionsToNodes()
{
ICacheAffinity aff = Affinity();
if (LocalCache())
{
IList<int> parts = new List<int> { 0 };
IDictionary<int, IClusterNode> map = aff.MapPartitionsToNodes(parts);
Assert.AreEqual(parts.Count, map.Count);
Assert.AreEqual(GetIgnite(0).GetCluster().GetLocalNode(), map[0]);
}
else
{
IList<int> parts = new List<int> { 1, 2, 3 };
IDictionary<int, IClusterNode> map = aff.MapPartitionsToNodes(parts);
Assert.AreEqual(parts.Count, map.Count);
foreach (int part in parts)
{
Assert.IsTrue(map.ContainsKey(part));
IClusterNode primary = aff.MapPartitionToNode(part);
Assert.AreEqual(primary, map[part], "Wrong node for partition: " + part);
}
}
}
[Test]
public void TestKeepBinaryFlag()
{
TestKeepBinaryFlag(false);
}
[Test]
public void TestKeepBinaryFlagAsync()
{
TestKeepBinaryFlag(true);
}
[Test]
public void TestNearKeys()
{
if (!NearEnabled())
return;
const int count = 20;
var cache = Cache();
var aff = cache.Ignite.GetAffinity(cache.Name);
var node = cache.Ignite.GetCluster().GetLocalNode();
for (int i = 0; i < count; i++)
cache.Put(i, -i - 1);
var nearKeys = Enumerable.Range(0, count).Where(x => !aff.IsPrimaryOrBackup(node, x)).ToArray();
var nearKeysString = nearKeys.Select(x => x.ToString()).Aggregate((x, y) => x + ", " + y);
Console.WriteLine("Near keys: " + nearKeysString);
foreach (var nearKey in nearKeys.Take(3))
Assert.AreNotEqual(0, cache.Get(nearKey));
}
[Test]
public void TestSerializable()
{
var cache = Cache<int, TestSerializableObject>();
var obj = new TestSerializableObject {Name = "Vasya", Id = 128};
cache.Put(1, obj);
var resultObj = cache.Get(1);
Assert.AreEqual(obj, resultObj);
}
[Test]
public void TestSerializableKeepBinary()
{
var cache = Cache<int, TestSerializableObject>();
var obj = new TestSerializableObject {Name = "Vasya", Id = 128};
cache.Put(1, obj);
var binaryRes = cache.WithKeepBinary<int, IBinaryObject>().Get(1);
var resultObj = binaryRes.Deserialize<TestSerializableObject>();
Assert.AreEqual(obj, resultObj);
}
[Test]
public void TestInvoke()
{
TestInvoke(false);
}
[Test]
public void TestInvokeAsync()
{
TestInvoke(true);
}
private void TestInvoke(bool async)
{
TestInvoke<AddArgCacheEntryProcessor>(async);
TestInvoke<BinarizableAddArgCacheEntryProcessor>(async);
Assert.Throws<Exception>(() => TestInvoke<NonSerializableCacheEntryProcessor>(async));
}
private void TestInvoke<T>(bool async) where T: AddArgCacheEntryProcessor, new()
{
var cache = async ? Cache().WrapAsync() : Cache();
cache.Clear();
const int key = 1;
const int value = 3;
const int arg = 5;
cache.Put(key, value);
// Existing entry
Assert.AreEqual(value + arg, cache.Invoke(key, new T(), arg));
Assert.AreEqual(value + arg, cache.Get(key));
// Non-existing entry
Assert.AreEqual(arg, cache.Invoke(10, new T {Exists = false}, arg));
Assert.AreEqual(arg, cache.Get(10));
// Remove entry
Assert.AreEqual(0, cache.Invoke(key, new T {Remove = true}, arg));
Assert.AreEqual(false, cache.ContainsKey(key));
// Test exceptions
AssertThrowsCacheEntryProcessorException(() => cache.Invoke(key, new T {ThrowErr = true}, arg));
AssertThrowsCacheEntryProcessorException(
() => cache.Invoke(key, new T {ThrowErrBinarizable = true}, arg));
AssertThrowsCacheEntryProcessorException(
() => cache.Invoke(key, new T { ThrowErrNonSerializable = true }, arg), "ExpectedException");
}
private static void AssertThrowsCacheEntryProcessorException(Action action, string containsText = null)
{
try
{
action();
Assert.Fail();
}
catch (Exception ex)
{
Assert.IsInstanceOf<CacheEntryProcessorException>(ex);
if (string.IsNullOrEmpty(containsText))
{
Assert.IsNotNull(ex.InnerException);
Assert.AreEqual(AddArgCacheEntryProcessor.ExceptionText, ex.InnerException.Message);
}
else
Assert.IsTrue(ex.ToString().Contains(containsText),
"Expected: " + containsText + ", actual: " + ex);
}
}
[Test]
public void TestInvokeAll()
{
TestInvokeAll(false);
}
[Test]
public void TestInvokeAllAsync()
{
TestInvokeAll(true);
}
private void TestInvokeAll(bool async)
{
for (var i = 1; i < 10; i++)
{
TestInvokeAll<AddArgCacheEntryProcessor>(async, i);
TestInvokeAll<BinarizableAddArgCacheEntryProcessor>(async, i);
Assert.Throws<Exception>(() => TestInvokeAll<NonSerializableCacheEntryProcessor>(async, i));
}
}
public void TestInvokeAll<T>(bool async, int entryCount) where T : AddArgCacheEntryProcessor, new()
{
var cache = async ? Cache().WrapAsync() : Cache();
var entries = Enumerable.Range(1, entryCount).ToDictionary(x => x, x => x + 1);
cache.PutAll(entries);
const int arg = 5;
// Existing entries
var res = cache.InvokeAll(entries.Keys, new T(), arg);
var results = res.OrderBy(x => x.Key).Select(x => x.Result);
var expectedResults = entries.OrderBy(x => x.Key).Select(x => x.Value + arg);
Assert.IsTrue(results.SequenceEqual(expectedResults));
var resultEntries = cache.GetAll(entries.Keys);
Assert.IsTrue(resultEntries.All(x => x.Value == x.Key + 1 + arg));
// Remove entries
res = cache.InvokeAll(entries.Keys, new T {Remove = true}, arg);
Assert.IsTrue(res.All(x => x.Result == 0));
Assert.AreEqual(0, cache.GetAll(entries.Keys).Count);
// Non-existing entries
res = cache.InvokeAll(entries.Keys, new T {Exists = false}, arg);
Assert.IsTrue(res.All(x => x.Result == arg));
Assert.IsTrue(cache.GetAll(entries.Keys).All(x => x.Value == arg));
// Test exceptions
var errKey = entries.Keys.Reverse().Take(5).Last();
TestInvokeAllException(cache, entries, new T { ThrowErr = true, ThrowOnKey = errKey }, arg, errKey);
TestInvokeAllException(cache, entries, new T { ThrowErrBinarizable = true, ThrowOnKey = errKey },
arg, errKey);
TestInvokeAllException(cache, entries, new T { ThrowErrNonSerializable = true, ThrowOnKey = errKey },
arg, errKey, "ExpectedException");
}
private static void TestInvokeAllException<T>(ICache<int, int> cache, Dictionary<int, int> entries,
T processor, int arg, int errKey, string exceptionText = null) where T : AddArgCacheEntryProcessor
{
var res = cache.InvokeAll(entries.Keys, processor, arg);
foreach (var procRes in res)
{
if (procRes.Key == errKey)
// ReSharper disable once AccessToForEachVariableInClosure
AssertThrowsCacheEntryProcessorException(() => { var x = procRes.Result; }, exceptionText);
else
Assert.Greater(procRes.Result, 0);
}
}
/// <summary>
/// Test skip-store semantics.
/// </summary>
[Test]
public void TestSkipStore()
{
var cache = (CacheImpl<int, int>) Cache();
Assert.IsFalse(cache.IsSkipStore);
// Ensure correct flag set.
var cacheSkipStore1 = (CacheImpl<int, int>) cache.WithSkipStore();
Assert.AreNotSame(cache, cacheSkipStore1);
Assert.IsFalse(cache.IsSkipStore);
Assert.IsTrue(cacheSkipStore1.IsSkipStore);
// Ensure that the same instance is returned if flag is already set.
var cacheSkipStore2 = (CacheImpl<int, int>) cacheSkipStore1.WithSkipStore();
Assert.IsTrue(cacheSkipStore2.IsSkipStore);
Assert.AreSame(cacheSkipStore1, cacheSkipStore2);
// Ensure other flags are preserved.
Assert.IsTrue(((CacheImpl<int, int>) cache.WithKeepBinary<int, int>().WithSkipStore()).IsKeepBinary);
}
[Test]
public void TestRebalance()
{
var cache = Cache();
var task = cache.Rebalance();
task.Wait();
}
[Test]
public void TestCreate()
{
// Create a cache with random name
var randomName = "template" + Guid.NewGuid();
// Can't get non-existent cache with Cache method
Assert.Throws<ArgumentException>(() => GetIgnite(0).GetCache<int, int>(randomName));
Assert.IsFalse(GetIgnite(0).GetCacheNames().Contains(randomName));
var cache = GetIgnite(0).CreateCache<int, int>(randomName);
Assert.IsTrue(GetIgnite(0).GetCacheNames().Contains(randomName));
cache.Put(1, 10);
Assert.AreEqual(10, cache.Get(1));
// Can't create again
Assert.Throws<IgniteException>(() => GetIgnite(0).CreateCache<int, int>(randomName));
var cache0 = GetIgnite(0).GetCache<int, int>(randomName);
Assert.AreEqual(10, cache0.Get(1));
}
[Test]
public void TestGetOrCreate()
{
// Create a cache with random name
var randomName = "template" + Guid.NewGuid();
// Can't get non-existent cache with Cache method
Assert.Throws<ArgumentException>(() => GetIgnite(0).GetCache<int, int>(randomName));
var cache = GetIgnite(0).GetOrCreateCache<int, int>(randomName);
cache.Put(1, 10);
Assert.AreEqual(10, cache.Get(1));
var cache0 = GetIgnite(0).GetOrCreateCache<int, int>(randomName);
Assert.AreEqual(10, cache0.Get(1));
var cache1 = GetIgnite(0).GetCache<int, int>(randomName);
Assert.AreEqual(10, cache1.Get(1));
}
[Test]
public void TestDestroy()
{
var cacheName = "template" + Guid.NewGuid();
var ignite = GetIgnite(0);
var cache = ignite.CreateCache<int, int>(cacheName);
Assert.IsNotNull(ignite.GetCache<int, int>(cacheName));
Assert.IsTrue(GetIgnite(0).GetCacheNames().Contains(cacheName));
ignite.DestroyCache(cache.Name);
Assert.IsFalse(GetIgnite(0).GetCacheNames().Contains(cacheName));
var ex = Assert.Throws<ArgumentException>(() => ignite.GetCache<int, int>(cacheName));
Assert.IsTrue(ex.Message.StartsWith("Cache doesn't exist"));
Assert.Throws<InvalidOperationException>(() => cache.Get(1));
}
[Test]
public void TestCacheNames()
{
var cacheNames = GetIgnite(0).GetCacheNames();
var expectedNames = new[]
{
"local", "local_atomic", "partitioned", "partitioned_atomic",
"partitioned_near", "partitioned_atomic_near", "replicated", "replicated_atomic"
};
Assert.AreEqual(0, expectedNames.Except(cacheNames).Count());
}
[Test]
public void TestIndexer()
{
var cache = Cache();
Assert.Throws<KeyNotFoundException>(() => Console.WriteLine(cache[0])); // missing key throws
cache[1] = 5;
Assert.AreEqual(5, cache[1]);
}
/// <summary>
/// Tests that operations in TransactionScope work correctly in any cache mode (tx or non-tx).
/// </summary>
[Test]
public void TestTransactionScope()
{
var cache = Cache();
cache[1] = 1;
using (var ts = new TransactionScope())
{
cache[1] = 2;
ts.Complete();
}
Assert.AreEqual(2, cache[1]);
}
private void TestKeepBinaryFlag(bool async)
{
var cache0 = async ? Cache().WrapAsync() : Cache();
var cache = cache0.WithKeepBinary<int, BinarizablePerson>();
var binCache = cache0.WithKeepBinary<int, IBinaryObject>();
int cnt = 10;
IList<int> keys = new List<int>();
for (int i = 0; i < cnt; i++ ) {
cache.Put(i, new BinarizablePerson("person-" + i, i));
keys.Add(i);
}
IList<IBinaryObject> objs = new List<IBinaryObject>();
for (int i = 0; i < cnt; i++)
{
var obj = binCache.Get(i);
CheckPersonData(obj, "person-" + i, i);
objs.Add(obj);
}
// Check objects weren't corrupted by subsequent cache operations.
for (int i = 0; i < cnt; i++)
{
IBinaryObject obj = objs[i];
CheckPersonData(obj, "person-" + i, i);
}
// Check keepBinary for GetAll operation.
var allObjs1 = binCache.GetAll(keys).ToDictionary(x => x.Key, x => x.Value);
var allObjs2 = binCache.GetAll(keys).ToDictionary(x => x.Key, x => x.Value);
for (int i = 0; i < cnt; i++)
{
CheckPersonData(allObjs1[i], "person-" + i, i);
CheckPersonData(allObjs2[i], "person-" + i, i);
}
// Check keepBinary for Remove operation.
var success0 = cache.Remove(0);
var success1 = cache.Remove(1);
Assert.AreEqual(true, success0);
Assert.AreEqual(true, success1);
}
private void CheckPersonData(IBinaryObject obj, string expName, int expAge)
{
Assert.AreEqual(expName, obj.GetField<string>("name"));
Assert.AreEqual(expAge, obj.GetField<int>("age"));
BinarizablePerson person = obj.Deserialize<BinarizablePerson>();
Assert.AreEqual(expName, person.Name);
Assert.AreEqual(expAge, person.Age);
}
protected static int PrimaryKeyForCache(ICache<int, int> cache)
{
return PrimaryKeysForCache(cache, 1, 0).First();
}
protected static int PrimaryKeyForCache(ICache<int, int> cache, int startFrom)
{
return PrimaryKeysForCache(cache, 1, startFrom).First();
}
protected static List<int> PrimaryKeysForCache(ICache<int, int> cache, int cnt)
{
return PrimaryKeysForCache(cache, cnt, 0).Take(cnt).ToList();
}
protected static IEnumerable<int> PrimaryKeysForCache(ICache<int, int> cache, int cnt, int startFrom)
{
IClusterNode node = cache.Ignite.GetCluster().GetLocalNode();
ICacheAffinity aff = cache.Ignite.GetAffinity(cache.Name);
return Enumerable.Range(startFrom, int.MaxValue - startFrom).Where(x => aff.IsPrimary(node, x));
}
protected static int NearKeyForCache(ICache<int, int> cache)
{
IClusterNode node = cache.Ignite.GetCluster().GetLocalNode();
ICacheAffinity aff = cache.Ignite.GetAffinity(cache.Name);
for (int i = 0; i < 100000; i++)
{
if (!aff.IsPrimaryOrBackup(node, i))
return i;
}
Assert.Fail("Failed to find near key.");
return 0;
}
protected static string GetKeyAffinity(ICache<int, int> cache, int key)
{
if (cache.Ignite.GetAffinity(cache.Name).IsPrimary(cache.Ignite.GetCluster().GetLocalNode(), key))
return "primary";
if (cache.Ignite.GetAffinity(cache.Name).IsBackup(cache.Ignite.GetCluster().GetLocalNode(), key))
return "backup";
return "near";
}
protected virtual int CachePartitions()
{
return 1024;
}
protected virtual int Backups()
{
return 0;
}
protected virtual int GridCount()
{
return 1;
}
protected virtual string CacheName()
{
return "partitioned";
}
protected virtual bool NearEnabled()
{
return false;
}
protected virtual bool LocalCache()
{
return false;
}
protected virtual bool ReplicatedCache()
{
return true;
}
private static int PeekInt(ICache<int, int> cache, int key)
{
int val;
cache.TryLocalPeek(key, out val, CachePeekMode.Onheap);
return val;
}
}
}
| 28.628521
| 118
| 0.503684
|
[
"CC0-1.0"
] |
dropoutlabs/ignite
|
modules/platforms/dotnet/Apache.Ignite.Core.Tests/Cache/CacheAbstractTest.cs
| 81,305
|
C#
|
using MediatR;
using PharmVerse.Presentation.Patients.Models.Result;
using System;
namespace PharmVerse.Presentation.Patients.Commands
{
public class CreatePatientCommand : IRequest<CreatePatientCommandResult>
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Image { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string DoctorInCharge { get; set; }
public string Ailment { get; set; }
}
}
| 34.9
| 77
| 0.627507
|
[
"MIT"
] |
ddynamight/PharmVerse
|
PharmVerse/PharmVerse.Presentation/Patients/Commands/CreatePatientCommand.cs
| 700
|
C#
|
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20181101.Inputs
{
/// <summary>
/// Filter that is applied to packet capture request. Multiple filters can be applied.
/// </summary>
public sealed class PacketCaptureFilterArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Local IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5"? for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null.
/// </summary>
[Input("localIPAddress")]
public Input<string>? LocalIPAddress { get; set; }
/// <summary>
/// Local port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null.
/// </summary>
[Input("localPort")]
public Input<string>? LocalPort { get; set; }
/// <summary>
/// Protocol to be filtered on.
/// </summary>
[Input("protocol")]
public InputUnion<string, Pulumi.AzureNextGen.Network.V20181101.PcProtocol>? Protocol { get; set; }
/// <summary>
/// Local IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null.
/// </summary>
[Input("remoteIPAddress")]
public Input<string>? RemoteIPAddress { get; set; }
/// <summary>
/// Remote port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null.
/// </summary>
[Input("remotePort")]
public Input<string>? RemotePort { get; set; }
public PacketCaptureFilterArgs()
{
Protocol = "Any";
}
}
}
| 46.425926
| 293
| 0.654966
|
[
"Apache-2.0"
] |
pulumi/pulumi-azure-nextgen
|
sdk/dotnet/Network/V20181101/Inputs/PacketCaptureFilterArgs.cs
| 2,507
|
C#
|
// Copyright (c) 2020, mParticle, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using MP.Json;
using MP.Json.Validation;
using Xunit;
namespace JsonSchemaTestSuite.Draft7
{
public class Items
{
/// <summary>
/// 1 - a schema given for items
/// </summary>
[Theory]
[InlineData(
"valid items",
"[ 1, 2, 3 ]",
true
)]
[InlineData(
"wrong type of items",
"[ 1, 'x' ]",
false
)]
[InlineData(
"ignores non-arrays",
"{ 'foo':'bar' }",
true
)]
[InlineData(
"JavaScript pseudo-array is valid",
"{ '0':'invalid', 'length':1 }",
true
)]
public void ASchemaGivenForItems(string desc, string data, bool expected)
{
// a schema given for items
Console.Error.WriteLine(desc);
string schemaData = "{ 'items':{ 'type':'integer' } }";
MPJson schemaJson = MPJson.Parse(schemaData);
MPJson json = MPJson.Parse(data);
MPSchema schema = schemaJson;
var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft7 };
bool actual = validator.Validate(schema, json);
Assert.Equal(expected, actual);
}
/// <summary>
/// 2 - an array of schemas for items
/// </summary>
[Theory]
[InlineData(
"correct types",
"[ 1, 'foo' ]",
true
)]
[InlineData(
"wrong types",
"[ 'foo', 1 ]",
false
)]
[InlineData(
"incomplete array of items",
"[ 1 ]",
true
)]
[InlineData(
"array with additional items",
"[ 1, 'foo', true ]",
true
)]
[InlineData(
"empty array",
"[ ]",
true
)]
[InlineData(
"JavaScript pseudo-array is valid",
"{ '0':'invalid', '1':'valid', 'length':2 }",
true
)]
public void AnArrayOfSchemasForItems(string desc, string data, bool expected)
{
// an array of schemas for items
Console.Error.WriteLine(desc);
string schemaData = "{ 'items':[ { 'type':'integer' }, { 'type':'string' } ] }";
MPJson schemaJson = MPJson.Parse(schemaData);
MPJson json = MPJson.Parse(data);
MPSchema schema = schemaJson;
var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft7 };
bool actual = validator.Validate(schema, json);
Assert.Equal(expected, actual);
}
/// <summary>
/// 3 - items with boolean schema (true)
/// </summary>
[Theory]
[InlineData(
"any array is valid",
"[ 1, 'foo', true ]",
true
)]
[InlineData(
"empty array is valid",
"[ ]",
true
)]
public void ItemsWithBooleanSchemaTrue(string desc, string data, bool expected)
{
// items with boolean schema (true)
Console.Error.WriteLine(desc);
string schemaData = "{ 'items':true }";
MPJson schemaJson = MPJson.Parse(schemaData);
MPJson json = MPJson.Parse(data);
MPSchema schema = schemaJson;
var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft7 };
bool actual = validator.Validate(schema, json);
Assert.Equal(expected, actual);
}
/// <summary>
/// 4 - items with boolean schema (false)
/// </summary>
[Theory]
[InlineData(
"any non-empty array is invalid",
"[ 1, 'foo', true ]",
false
)]
[InlineData(
"empty array is valid",
"[ ]",
true
)]
public void ItemsWithBooleanSchemaFalse(string desc, string data, bool expected)
{
// items with boolean schema (false)
Console.Error.WriteLine(desc);
string schemaData = "{ 'items':false }";
MPJson schemaJson = MPJson.Parse(schemaData);
MPJson json = MPJson.Parse(data);
MPSchema schema = schemaJson;
var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft7 };
bool actual = validator.Validate(schema, json);
Assert.Equal(expected, actual);
}
/// <summary>
/// 5 - items with boolean schemas
/// </summary>
[Theory]
[InlineData(
"array with one item is valid",
"[ 1 ]",
true
)]
[InlineData(
"array with two items is invalid",
"[ 1, 'foo' ]",
false
)]
[InlineData(
"empty array is valid",
"[ ]",
true
)]
public void ItemsWithBooleanSchemas(string desc, string data, bool expected)
{
// items with boolean schemas
Console.Error.WriteLine(desc);
string schemaData = "{ 'items':[ true, false ] }";
MPJson schemaJson = MPJson.Parse(schemaData);
MPJson json = MPJson.Parse(data);
MPSchema schema = schemaJson;
var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft7 };
bool actual = validator.Validate(schema, json);
Assert.Equal(expected, actual);
}
/// <summary>
/// 6 - items and subitems
/// </summary>
[Theory]
[InlineData(
"valid items",
"[ [ { 'foo':null }, { 'foo':null } ], [ { 'foo':null }, { 'foo':null } ], [ { 'foo':null }, { 'foo':null } ] ]",
true
)]
[InlineData(
"too many items",
"[ [ { 'foo':null }, { 'foo':null } ], [ { 'foo':null }, { 'foo':null } ], [ { 'foo':null }, { 'foo':null } ], [ { 'foo':null }, { 'foo':null } ] ]",
false
)]
[InlineData(
"too many sub-items",
"[ [ { 'foo':null }, { 'foo':null }, { 'foo':null } ], [ { 'foo':null }, { 'foo':null } ], [ { 'foo':null }, { 'foo':null } ] ]",
false
)]
[InlineData(
"wrong item",
"[ { 'foo':null }, [ { 'foo':null }, { 'foo':null } ], [ { 'foo':null }, { 'foo':null } ] ]",
false
)]
[InlineData(
"wrong sub-item",
"[ [ { }, { 'foo':null } ], [ { 'foo':null }, { 'foo':null } ], [ { 'foo':null }, { 'foo':null } ] ]",
false
)]
[InlineData(
"fewer items is valid",
"[ [ { 'foo':null } ], [ { 'foo':null } ] ]",
true
)]
public void ItemsAndSubitems(string desc, string data, bool expected)
{
// items and subitems
Console.Error.WriteLine(desc);
string schemaData = "{ 'additionalItems':false, 'definitions':{ 'item':{ 'additionalItems':false, 'items':[ { '$ref':'#/definitions/sub-item' }, { '$ref':'#/definitions/sub-item' } ], 'type':'array' }, 'sub-item':{ 'required':[ 'foo' ], 'type':'object' } }, 'items':[ { '$ref':'#/definitions/item' }, { '$ref':'#/definitions/item' }, { '$ref':'#/definitions/item' } ], 'type':'array' }";
MPJson schemaJson = MPJson.Parse(schemaData);
MPJson json = MPJson.Parse(data);
MPSchema schema = schemaJson;
var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft7 };
bool actual = validator.Validate(schema, json);
Assert.Equal(expected, actual);
}
/// <summary>
/// 7 - nested items
/// </summary>
[Theory]
[InlineData(
"valid nested array",
"[ [ [ [ 1 ] ], [ [ 2 ], [ 3 ] ] ], [ [ [ 4 ], [ 5 ], [ 6 ] ] ] ]",
true
)]
[InlineData(
"nested array with invalid type",
"[ [ [ [ '1' ] ], [ [ 2 ], [ 3 ] ] ], [ [ [ 4 ], [ 5 ], [ 6 ] ] ] ]",
false
)]
[InlineData(
"not deep enough",
"[ [ [ 1 ], [ 2 ], [ 3 ] ], [ [ 4 ], [ 5 ], [ 6 ] ] ]",
false
)]
public void NestedItems(string desc, string data, bool expected)
{
// nested items
Console.Error.WriteLine(desc);
string schemaData = "{ 'items':{ 'items':{ 'items':{ 'items':{ 'type':'number' }, 'type':'array' }, 'type':'array' }, 'type':'array' }, 'type':'array' }";
MPJson schemaJson = MPJson.Parse(schemaData);
MPJson json = MPJson.Parse(data);
MPSchema schema = schemaJson;
var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft7 };
bool actual = validator.Validate(schema, json);
Assert.Equal(expected, actual);
}
}
}
| 31.104101
| 399
| 0.479716
|
[
"Apache-2.0"
] |
mParticle/mparticle-json
|
MP.Json.Test/generated/Draft7/Items.cs
| 9,860
|
C#
|
namespace Win.ERP
{
partial class FormReporteFactura
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// FormReporteFactura
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 261);
this.Name = "FormReporteFactura";
this.Text = "Facturas";
this.ResumeLayout(false);
}
#endregion
}
}
| 30.413043
| 107
| 0.548249
|
[
"MIT"
] |
damarisparedes/sistema-erp
|
SISTEMA ERP/Win.ERP/FormReporteFactura.Designer.cs
| 1,401
|
C#
|
//
// settings.cs: All compiler settings
//
// Author: Miguel de Icaza (miguel@ximian.com)
// Ravi Pratap (ravi@ximian.com)
// Marek Safar (marek.safar@gmail.com)
//
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
//
// Copyright 2001 Ximian, Inc (http://www.ximian.com)
// Copyright 2004-2008 Novell, Inc
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Globalization;
using System;
namespace Mono.CSharp {
public enum LanguageVersion
{
ISO_1 = 1,
ISO_2 = 2,
V_3 = 3,
V_4 = 4,
V_5 = 5,
Future = 100,
Default = LanguageVersion.V_5,
}
public enum RuntimeVersion
{
v1,
v2,
v4
}
public enum Target
{
Library = 1, Exe = 2, Module = 4, WinExe = 8, JavaScript = 16, Cpp = 32,
IsTextTarget = 48
}
public enum Platform
{
AnyCPU,
AnyCPU32Preferred,
Arm,
X86,
X64,
IA64
}
public class CompilerSettings
{
public Target Target;
public Platform Platform;
public string TargetExt;
public bool VerifyClsCompliance;
public bool Optimize;
public LanguageVersion Version;
public bool EnhancedWarnings;
public bool LoadDefaultReferences;
public string SdkVersion;
public string StrongNameKeyFile;
public string StrongNameKeyContainer;
public bool StrongNameDelaySign;
public int TabSize;
public bool WarningsAreErrors;
public int WarningLevel;
//
// Assemblies references to be loaded
//
public List<string> AssemblyReferences;
//
// External aliases for assemblies
//
public List<Tuple<string, string>> AssemblyReferencesAliases;
//
// Modules to be embedded
//
public List<string> Modules;
//
// Lookup paths for referenced assemblies
//
public List<string> ReferencesLookupPaths;
//
// Encoding.
//
public Encoding Encoding;
//
// If set, enable XML documentation generation
//
public string DocumentationFile;
public string MainClass;
//
// Output file
//
public string OutputFile;
//
// The default compiler checked state
//
public bool Checked;
//
// If true, the compiler is operating in statement mode,
// this currently turns local variable declaration into
// static variables of a class
//
public bool StatementMode; // TODO: SUPER UGLY
//
// Whether to allow Unsafe code
//
public bool Unsafe;
public string Win32ResourceFile;
public string Win32IconFile;
//
// A list of resource files for embedding
//
public List<AssemblyResource> Resources;
public bool GenerateDebugInfo;
#region Compiler debug flags only
public bool ParseOnly, TokenizeOnly, Timestamps;
public int DebugFlags;
public int VerboseParserFlag;
public int FatalCounter;
public bool Stacktrace;
#endregion
public bool ShowFullPaths;
//
// Whether we are being linked against the standard libraries.
// This is only used to tell whether `System.Object' should
// have a base class or not.
//
public bool StdLib;
public RuntimeVersion StdLibRuntimeVersion;
public bool WriteMetadataOnly;
readonly List<string> conditional_symbols;
readonly List<SourceFile> source_files;
List<int> warnings_as_error;
List<int> warnings_only;
HashSet<int> warning_ignore_table;
public CompilerSettings ()
{
StdLib = true;
Target = Target.Exe;
TargetExt = ".exe";
Platform = Platform.AnyCPU;
Version = LanguageVersion.Default;
VerifyClsCompliance = true;
Encoding = Encoding.UTF8;
LoadDefaultReferences = true;
StdLibRuntimeVersion = RuntimeVersion.v4;
WarningLevel = 4;
// Default to 1 or mdb files would be platform speficic
TabSize = 1;
AssemblyReferences = new List<string> ();
AssemblyReferencesAliases = new List<Tuple<string, string>> ();
Modules = new List<string> ();
ReferencesLookupPaths = new List<string> ();
conditional_symbols = new List<string> ();
//
// Add default mcs define
//
conditional_symbols.Add ("__MonoCS__");
source_files = new List<SourceFile> ();
}
#region Properties
public SourceFile FirstSourceFile {
get {
return source_files.Count > 0 ? source_files [0] : null;
}
}
public bool HasKeyFileOrContainer {
get {
return StrongNameKeyFile != null || StrongNameKeyContainer != null;
}
}
public bool NeedsEntryPoint {
get {
return Target == Target.Exe || Target == Target.WinExe;
}
}
public List<SourceFile> SourceFiles {
get {
return source_files;
}
}
#endregion
public void AddConditionalSymbol (string symbol)
{
if (!conditional_symbols.Contains (symbol))
conditional_symbols.Add (symbol);
}
public void AddWarningAsError (int id)
{
if (warnings_as_error == null)
warnings_as_error = new List<int> ();
warnings_as_error.Add (id);
}
public void AddWarningOnly (int id)
{
if (warnings_only == null)
warnings_only = new List<int> ();
warnings_only.Add (id);
}
public bool IsConditionalSymbolDefined (string symbol)
{
return conditional_symbols.Contains (symbol);
}
public bool IsWarningAsError (int code)
{
bool is_error = WarningsAreErrors;
// Check specific list
if (warnings_as_error != null)
is_error |= warnings_as_error.Contains (code);
// Ignore excluded warnings
if (warnings_only != null && warnings_only.Contains (code))
is_error = false;
return is_error;
}
public bool IsWarningEnabled (int code, int level)
{
if (WarningLevel < level)
return false;
return !IsWarningDisabledGlobally (code);
}
public bool IsWarningDisabledGlobally (int code)
{
return warning_ignore_table != null && warning_ignore_table.Contains (code);
}
public void SetIgnoreWarning (int code)
{
if (warning_ignore_table == null)
warning_ignore_table = new HashSet<int> ();
warning_ignore_table.Add (code);
}
}
public class CommandLineParser
{
enum ParseResult
{
Success,
Error,
Stop,
UnknownOption
}
static readonly char[] argument_value_separator = new char[] { ';', ',' };
static readonly char[] numeric_value_separator = new char[] { ';', ',', ' ' };
readonly TextWriter output;
readonly Report report;
bool stop_argument;
Dictionary<string, int> source_file_index;
public event Func<string[], int, int> UnknownOptionHandler;
CompilerSettings parser_settings;
public CommandLineParser (TextWriter errorOutput)
: this (errorOutput, Console.Out)
{
}
public CommandLineParser (TextWriter errorOutput, TextWriter messagesOutput)
{
var rp = new StreamReportPrinter (errorOutput);
parser_settings = new CompilerSettings ();
report = new Report (new CompilerContext (parser_settings, rp), rp);
this.output = messagesOutput;
}
public bool HasBeenStopped {
get {
return stop_argument;
}
}
void About ()
{
#if PLAYSCRIPT
output.WriteLine (
"The PlayScript compiler parts Copyright 2013, Zynga, Inc.\n" +
"Based on Mono MCS Compiler Copyright 2001-2011, Novell, Inc.\n\n" +
"The compiler source code is released under the terms of the \n" +
"MIT X11 or GNU GPL licenses\n\n" +
"For more information on PlayScript, visit the project Web site\n" +
" http://www.playscriptlang.com\n\n" +
"For more information on Mono, visit the project Web site\n" +
" http://www.mono-project.com\n\n" +
"The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto\n" +
"The PlayScript/ActionScript compiler was written by Ben Cooley and Icer Addis - Zynga");
#else
output.WriteLine (
"The Mono C# compiler is Copyright 2001-2011, Novell, Inc.\n\n" +
"The compiler source code is released under the terms of the \n" +
"MIT X11 or GNU GPL licenses\n\n" +
"For more information on Mono, visit the project Web site\n" +
" http://www.mono-project.com\n\n" +
"The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
#endif
}
public CompilerSettings ParseArguments (string[] args)
{
CompilerSettings settings = new CompilerSettings ();
List<string> response_file_list = null;
bool parsing_options = true;
stop_argument = false;
source_file_index = new Dictionary<string, int> ();
for (int i = 0; i < args.Length; i++) {
string arg = args[i];
if (arg.Length == 0)
continue;
if (arg[0] == '@') {
string[] extra_args;
string response_file = arg.Substring (1);
if (response_file_list == null)
response_file_list = new List<string> ();
if (response_file_list.Contains (response_file)) {
report.Error (1515, "Response file `{0}' specified multiple times", response_file);
return null;
}
response_file_list.Add (response_file);
extra_args = LoadArgs (response_file);
if (extra_args == null) {
report.Error (2011, "Unable to open response file: " + response_file);
return null;
}
args = AddArgs (args, extra_args);
continue;
}
if (parsing_options) {
if (arg == "--") {
parsing_options = false;
continue;
}
bool dash_opt = arg[0] == '-';
bool slash_opt = arg[0] == '/';
if (dash_opt) {
switch (ParseOptionUnix (arg, ref args, ref i, settings)) {
case ParseResult.Error:
case ParseResult.Success:
continue;
case ParseResult.Stop:
stop_argument = true;
return settings;
case ParseResult.UnknownOption:
if (UnknownOptionHandler != null) {
var ret = UnknownOptionHandler (args, i);
if (ret != -1) {
i = ret;
continue;
}
}
break;
}
}
if (dash_opt || slash_opt) {
// Try a -CSCOPTION
string csc_opt = dash_opt ? "/" + arg.Substring (1) : arg;
switch (ParseOption (csc_opt, ref args, settings)) {
case ParseResult.Error:
case ParseResult.Success:
continue;
case ParseResult.UnknownOption:
// Need to skip `/home/test.cs' however /test.cs is considered as error
if ((slash_opt && arg.Length > 3 && arg.IndexOf ('/', 2) > 0))
break;
if (UnknownOptionHandler != null) {
var ret = UnknownOptionHandler (args, i);
if (ret != -1) {
i = ret;
continue;
}
}
Error_WrongOption (arg);
return null;
case ParseResult.Stop:
stop_argument = true;
return settings;
}
}
}
ProcessSourceFiles (arg, false, settings.SourceFiles);
}
if (report.Errors > 0)
return null;
return settings;
}
void ProcessSourceFiles (string spec, bool recurse, List<SourceFile> sourceFiles)
{
string path, pattern;
SplitPathAndPattern (spec, out path, out pattern);
if (pattern.IndexOf ('*') == -1) {
AddSourceFile (spec, sourceFiles);
return;
}
string[] files = null;
try {
files = Directory.GetFiles (path, pattern);
} catch (System.IO.DirectoryNotFoundException) {
report.Error (2001, "Source file `" + spec + "' could not be found");
return;
} catch (System.IO.IOException) {
report.Error (2001, "Source file `" + spec + "' could not be found");
return;
}
foreach (string f in files) {
AddSourceFile (f, sourceFiles);
}
if (!recurse)
return;
string[] dirs = null;
try {
dirs = Directory.GetDirectories (path);
} catch {
}
foreach (string d in dirs) {
// Don't include path in this string, as each
// directory entry already does
ProcessSourceFiles (d + "/" + pattern, true, sourceFiles);
}
}
static string[] AddArgs (string[] args, string[] extra_args)
{
string[] new_args;
new_args = new string[extra_args.Length + args.Length];
// if args contains '--' we have to take that into account
// split args into first half and second half based on '--'
// and add the extra_args before --
int split_position = Array.IndexOf (args, "--");
if (split_position != -1) {
Array.Copy (args, new_args, split_position);
extra_args.CopyTo (new_args, split_position);
Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
} else {
args.CopyTo (new_args, 0);
extra_args.CopyTo (new_args, args.Length);
}
return new_args;
}
void AddAssemblyReference (string alias, string assembly, CompilerSettings settings)
{
if (assembly.Length == 0) {
report.Error (1680, "Invalid reference alias `{0}='. Missing filename", alias);
return;
}
if (!IsExternAliasValid (alias)) {
report.Error (1679, "Invalid extern alias for -reference. Alias `{0}' is not a valid identifier", alias);
return;
}
settings.AssemblyReferencesAliases.Add (Tuple.Create (alias, assembly));
}
void AddResource (AssemblyResource res, CompilerSettings settings)
{
if (settings.Resources == null) {
settings.Resources = new List<AssemblyResource> ();
settings.Resources.Add (res);
return;
}
if (settings.Resources.Contains (res)) {
report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", res.Name);
return;
}
settings.Resources.Add (res);
}
void AddSourceFile (string fileName, List<SourceFile> sourceFiles)
{
string path = Path.GetFullPath (fileName);
int index;
if (source_file_index.TryGetValue (path, out index)) {
string other_name = sourceFiles[index - 1].Name;
if (fileName.Equals (other_name))
report.Warning (2002, 1, "Source file `{0}' specified multiple times", other_name);
else
report.Warning (2002, 1, "Source filenames `{0}' and `{1}' both refer to the same file: {2}", fileName, other_name, path);
return;
}
var unit = new SourceFile (fileName, path, sourceFiles.Count + 1);
sourceFiles.Add (unit);
source_file_index.Add (path, unit.Index);
}
public bool ProcessWarningsList (string text, Action<int> action)
{
bool valid = true;
foreach (string wid in text.Split (numeric_value_separator)) {
int id;
if (!int.TryParse (wid, NumberStyles.AllowLeadingWhite, CultureInfo.InvariantCulture, out id)) {
report.Error (1904, "`{0}' is not a valid warning number", wid);
valid = false;
continue;
}
if (report.CheckWarningCode (id, Location.Null))
action (id);
}
return valid;
}
void Error_RequiresArgument (string option)
{
report.Error (2006, "Missing argument for `{0}' option", option);
}
void Error_RequiresFileName (string option)
{
report.Error (2005, "Missing file specification for `{0}' option", option);
}
void Error_WrongOption (string option)
{
report.Error (2007, "Unrecognized command-line option: `{0}'", option);
}
static bool IsExternAliasValid (string identifier)
{
return Tokenizer.IsValidIdentifier (identifier);
}
static string[] LoadArgs (string file)
{
StreamReader f;
var args = new List<string> ();
string line;
try {
f = new StreamReader (file);
} catch {
return null;
}
StringBuilder sb = new StringBuilder ();
while ((line = f.ReadLine ()) != null) {
int t = line.Length;
for (int i = 0; i < t; i++) {
char c = line[i];
if (c == '"' || c == '\'') {
char end = c;
for (i++; i < t; i++) {
c = line[i];
if (c == end)
break;
sb.Append (c);
}
} else if (c == ' ') {
if (sb.Length > 0) {
args.Add (sb.ToString ());
sb.Length = 0;
}
} else
sb.Append (c);
}
if (sb.Length > 0) {
args.Add (sb.ToString ());
sb.Length = 0;
}
}
return args.ToArray ();
}
void OtherFlags ()
{
output.WriteLine (
"Other flags in the compiler\n" +
" --fatal[=COUNT] Makes error after COUNT fatal\n" +
" --lint Enhanced warnings\n" +
" --metadata-only Produced assembly will contain metadata only\n" +
" --parse Only parses the source file\n" +
" --runtime:VERSION Sets mscorlib.dll metadata version: v1, v2, v4\n" +
" --stacktrace Shows stack trace at error location\n" +
" --timestamp Displays time stamps of various compiler events\n" +
" -v Verbose parsing (for debugging the parser)\n" +
" --mcs-debug X Sets MCS debugging level to X\n");
}
//
// This parses the -arg and /arg options to the compiler, even if the strings
// in the following text use "/arg" on the strings.
//
ParseResult ParseOption (string option, ref string[] args, CompilerSettings settings)
{
int idx = option.IndexOf (':');
string arg, value;
if (idx == -1) {
arg = option;
value = "";
} else {
arg = option.Substring (0, idx);
value = option.Substring (idx + 1);
}
switch (arg.ToLowerInvariant ()) {
case "/nologo":
return ParseResult.Success;
case "/t":
case "/target":
bool is_dotnet = true;
switch (value) {
case "exe":
settings.Target = Target.Exe;
break;
case "winexe":
settings.Target = Target.WinExe;
break;
case "library":
settings.Target = Target.Library;
settings.TargetExt = ".dll";
break;
case "module":
settings.Target = Target.Module;
settings.TargetExt = ".netmodule";
break;
case "javascript":
settings.Target = Target.JavaScript;
settings.TargetExt = ".js";
settings.AddConditionalSymbol ("TARGET_JS");
is_dotnet = false;
break;
case "cpp":
settings.Target = Target.Cpp;
settings.TargetExt = ".cpp";
settings.AddConditionalSymbol ("TARGET_CPP");
is_dotnet = false;
break;
default:
report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library', `module', `javascript' or `cpp'");
return ParseResult.Error;
}
if (is_dotnet) {
settings.AddConditionalSymbol ("TARGET_IL");
}
return ParseResult.Success;
case "/out":
if (value.Length == 0) {
Error_RequiresFileName (option);
return ParseResult.Error;
}
settings.OutputFile = value;
return ParseResult.Success;
case "/o":
case "/o+":
case "/optimize":
case "/optimize+":
settings.Optimize = true;
return ParseResult.Success;
case "/o-":
case "/optimize-":
settings.Optimize = false;
return ParseResult.Success;
// TODO: Not supported by csc 3.5+
case "/incremental":
case "/incremental+":
case "/incremental-":
// nothing.
return ParseResult.Success;
case "/d":
case "/define": {
if (value.Length == 0) {
Error_RequiresArgument (option);
return ParseResult.Error;
}
foreach (string d in value.Split (argument_value_separator)) {
string conditional = d.Trim ();
if (!Tokenizer.IsValidIdentifier (conditional)) {
report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional);
continue;
}
settings.AddConditionalSymbol (conditional);
}
return ParseResult.Success;
}
case "/bugreport":
//
// We should collect data, runtime, etc and store in the file specified
//
output.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
return ParseResult.Success;
case "/pkg": {
string packages;
if (value.Length == 0) {
Error_RequiresArgument (option);
return ParseResult.Error;
}
packages = String.Join (" ", value.Split (new Char[] { ';', ',', '\n', '\r' }));
string pkgout = Driver.GetPackageFlags (packages, report);
if (pkgout == null)
return ParseResult.Error;
string[] xargs = pkgout.Trim (new Char[] { ' ', '\n', '\r', '\t' }).Split (new Char[] { ' ', '\t' });
args = AddArgs (args, xargs);
return ParseResult.Success;
}
case "/linkres":
case "/linkresource":
case "/res":
case "/resource":
AssemblyResource res = null;
string[] s = value.Split (argument_value_separator, StringSplitOptions.RemoveEmptyEntries);
switch (s.Length) {
case 1:
if (s[0].Length == 0)
goto default;
res = new AssemblyResource (s[0], Path.GetFileName (s[0]));
break;
case 2:
res = new AssemblyResource (s[0], s[1]);
break;
case 3:
if (s[2] != "public" && s[2] != "private") {
report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s[2]);
return ParseResult.Error;
}
res = new AssemblyResource (s[0], s[1], s[2] == "private");
break;
default:
report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
return ParseResult.Error;
}
if (res != null) {
res.IsEmbeded = arg[1] == 'r' || arg[1] == 'R';
AddResource (res, settings);
}
return ParseResult.Success;
case "/recurse":
if (value.Length == 0) {
Error_RequiresFileName (option);
return ParseResult.Error;
}
ProcessSourceFiles (value, true, settings.SourceFiles);
return ParseResult.Success;
case "/r":
case "/reference": {
if (value.Length == 0) {
Error_RequiresFileName (option);
return ParseResult.Error;
}
string[] refs = value.Split (argument_value_separator);
foreach (string r in refs) {
if (r.Length == 0)
continue;
string val = r;
int index = val.IndexOf ('=');
if (index > -1) {
string alias = r.Substring (0, index);
string assembly = r.Substring (index + 1);
AddAssemblyReference (alias, assembly, settings);
if (refs.Length != 1) {
report.Error (2034, "Cannot specify multiple aliases using single /reference option");
return ParseResult.Error;
}
} else {
settings.AssemblyReferences.Add (val);
}
}
return ParseResult.Success;
}
case "/addmodule": {
if (value.Length == 0) {
Error_RequiresFileName (option);
return ParseResult.Error;
}
string[] refs = value.Split (argument_value_separator);
foreach (string r in refs) {
settings.Modules.Add (r);
}
return ParseResult.Success;
}
case "/win32res": {
if (value.Length == 0) {
Error_RequiresFileName (option);
return ParseResult.Error;
}
if (settings.Win32IconFile != null)
report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
settings.Win32ResourceFile = value;
return ParseResult.Success;
}
case "/win32icon": {
if (value.Length == 0) {
Error_RequiresFileName (option);
return ParseResult.Error;
}
if (settings.Win32ResourceFile != null)
report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
settings.Win32IconFile = value;
return ParseResult.Success;
}
case "/doc": {
if (value.Length == 0) {
Error_RequiresFileName (option);
return ParseResult.Error;
}
settings.DocumentationFile = value;
return ParseResult.Success;
}
case "/lib": {
string[] libdirs;
if (value.Length == 0) {
return ParseResult.Error;
}
libdirs = value.Split (argument_value_separator);
foreach (string dir in libdirs)
settings.ReferencesLookupPaths.Add (dir);
return ParseResult.Success;
}
case "/debug-":
settings.GenerateDebugInfo = false;
return ParseResult.Success;
case "/debug":
if (value.Equals ("full", StringComparison.OrdinalIgnoreCase) || value.Equals ("pdbonly", StringComparison.OrdinalIgnoreCase) || idx < 0) {
settings.GenerateDebugInfo = true;
return ParseResult.Success;
}
if (value.Length > 0) {
report.Error (1902, "Invalid debug option `{0}'. Valid options are `full' or `pdbonly'", value);
} else {
Error_RequiresArgument (option);
}
return ParseResult.Error;
case "/debug+":
settings.GenerateDebugInfo = true;
return ParseResult.Success;
case "/checked":
case "/checked+":
settings.Checked = true;
return ParseResult.Success;
case "/checked-":
settings.Checked = false;
return ParseResult.Success;
case "/clscheck":
case "/clscheck+":
settings.VerifyClsCompliance = true;
return ParseResult.Success;
case "/clscheck-":
settings.VerifyClsCompliance = false;
return ParseResult.Success;
case "/unsafe":
case "/unsafe+":
settings.Unsafe = true;
return ParseResult.Success;
case "/unsafe-":
settings.Unsafe = false;
return ParseResult.Success;
case "/warnaserror":
case "/warnaserror+":
if (value.Length == 0) {
settings.WarningsAreErrors = true;
parser_settings.WarningsAreErrors = true;
} else {
if (!ProcessWarningsList (value, v => settings.AddWarningAsError (v)))
return ParseResult.Error;
}
return ParseResult.Success;
case "/warnaserror-":
if (value.Length == 0) {
settings.WarningsAreErrors = false;
} else {
if (!ProcessWarningsList (value, v => settings.AddWarningOnly (v)))
return ParseResult.Error;
}
return ParseResult.Success;
case "/warn":
case "/w":
if (value.Length == 0) {
Error_RequiresArgument (option);
return ParseResult.Error;
}
SetWarningLevel (value, settings);
return ParseResult.Success;
case "/nowarn":
if (value.Length == 0) {
Error_RequiresArgument (option);
return ParseResult.Error;
}
if (!ProcessWarningsList (value, v => settings.SetIgnoreWarning (v)))
return ParseResult.Error;
return ParseResult.Success;
case "/noconfig":
settings.LoadDefaultReferences = false;
return ParseResult.Success;
case "/platform":
if (value.Length == 0) {
Error_RequiresArgument (option);
return ParseResult.Error;
}
switch (value.ToLowerInvariant ()) {
case "arm":
settings.Platform = Platform.Arm;
break;
case "anycpu":
settings.Platform = Platform.AnyCPU;
break;
case "x86":
settings.Platform = Platform.X86;
break;
case "x64":
settings.Platform = Platform.X64;
break;
case "itanium":
settings.Platform = Platform.IA64;
break;
case "anycpu32bitpreferred":
settings.Platform = Platform.AnyCPU32Preferred;
break;
default:
report.Error (1672, "Invalid -platform option `{0}'. Valid options are `anycpu', `anycpu32bitpreferred', `arm', `x86', `x64' or `itanium'",
value);
return ParseResult.Error;
}
return ParseResult.Success;
case "/sdk":
if (value.Length == 0) {
Error_RequiresArgument (option);
return ParseResult.Error;
}
settings.SdkVersion = value;
return ParseResult.Success;
// We just ignore this.
case "/errorreport":
case "/filealign":
if (value.Length == 0) {
Error_RequiresArgument (option);
return ParseResult.Error;
}
return ParseResult.Success;
// We just ignore this.
case "/errorendlocation":
case "/highentropyva-":
case "/highentropyva+":
case "/highentropyva":
case "/utf8output":
return ParseResult.Success;
// We just ignore this.
case "/preferreduilang":
switch (value.ToLowerInvariant())
{
default:
return ParseResult.Success;
}
case "/helpinternal":
OtherFlags ();
return ParseResult.Stop;
case "/help":
case "/?":
Usage ();
return ParseResult.Stop;
case "/main":
case "/m":
if (value.Length == 0) {
Error_RequiresArgument (option);
return ParseResult.Error;
}
settings.MainClass = value;
return ParseResult.Success;
case "/nostdlib":
case "/nostdlib+":
settings.StdLib = false;
return ParseResult.Success;
case "/nostdlib-":
settings.StdLib = true;
return ParseResult.Success;
case "/fullpaths":
settings.ShowFullPaths = true;
return ParseResult.Success;
case "/keyfile":
if (value.Length == 0) {
Error_RequiresFileName (option);
return ParseResult.Error;
}
settings.StrongNameKeyFile = value;
return ParseResult.Success;
case "/keycontainer":
if (value.Length == 0) {
Error_RequiresArgument (option);
return ParseResult.Error;
}
settings.StrongNameKeyContainer = value;
return ParseResult.Success;
case "/delaysign+":
case "/delaysign":
settings.StrongNameDelaySign = true;
return ParseResult.Success;
case "/delaysign-":
settings.StrongNameDelaySign = false;
return ParseResult.Success;
case "/langversion":
if (value.Length == 0) {
Error_RequiresArgument (option);
return ParseResult.Error;
}
switch (value.ToLowerInvariant ()) {
case "iso-1":
settings.Version = LanguageVersion.ISO_1;
return ParseResult.Success;
case "default":
settings.Version = LanguageVersion.Default;
return ParseResult.Success;
case "iso-2":
settings.Version = LanguageVersion.ISO_2;
return ParseResult.Success;
case "3":
settings.Version = LanguageVersion.V_3;
return ParseResult.Success;
case "4":
settings.Version = LanguageVersion.V_4;
return ParseResult.Success;
case "5":
settings.Version = LanguageVersion.V_5;
return ParseResult.Success;
case "future":
settings.Version = LanguageVersion.Future;
return ParseResult.Success;
}
report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3', `4', `5', `Default' or `Future'", value);
return ParseResult.Error;
case "/codepage":
if (value.Length == 0) {
Error_RequiresArgument (option);
return ParseResult.Error;
}
switch (value) {
case "utf8":
settings.Encoding = Encoding.UTF8;
break;
case "reset":
settings.Encoding = Encoding.Default;
break;
default:
try {
settings.Encoding = Encoding.GetEncoding (int.Parse (value));
} catch {
report.Error (2016, "Code page `{0}' is invalid or not installed", value);
}
return ParseResult.Error;
}
return ParseResult.Success;
default:
return ParseResult.UnknownOption;
}
}
//
// Currently handles the Unix-like command line options, but will be
// deprecated in favor of the CSCParseOption, which will also handle the
// options that start with a dash in the future.
//
ParseResult ParseOptionUnix (string arg, ref string[] args, ref int i, CompilerSettings settings)
{
switch (arg){
case "-v":
settings.VerboseParserFlag++;
return ParseResult.Success;
case "--version":
Version ();
return ParseResult.Stop;
case "--parse":
settings.ParseOnly = true;
return ParseResult.Success;
case "--main": case "-m":
report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
if ((i + 1) >= args.Length){
Error_RequiresArgument (arg);
return ParseResult.Error;
}
settings.MainClass = args[++i];
return ParseResult.Success;
case "--unsafe":
report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
settings.Unsafe = true;
return ParseResult.Success;
case "/?": case "/h": case "/help":
case "--help":
Usage ();
return ParseResult.Stop;
case "--define":
report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
if ((i + 1) >= args.Length){
Error_RequiresArgument (arg);
return ParseResult.Error;
}
settings.AddConditionalSymbol (args [++i]);
return ParseResult.Success;
case "--tokenize":
settings.TokenizeOnly = true;
return ParseResult.Success;
case "-o":
case "--output":
report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
if ((i + 1) >= args.Length){
Error_RequiresArgument (arg);
return ParseResult.Error;
}
settings.OutputFile = args[++i];
return ParseResult.Success;
case "--checked":
report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
settings.Checked = true;
return ParseResult.Success;
case "--stacktrace":
settings.Stacktrace = true;
return ParseResult.Success;
case "--linkresource":
case "--linkres":
report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
if ((i + 1) >= args.Length){
Error_RequiresArgument (arg);
return ParseResult.Error;
}
AddResource (new AssemblyResource (args[++i], args[i]), settings);
return ParseResult.Success;
case "--resource":
case "--res":
report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
if ((i + 1) >= args.Length){
Error_RequiresArgument (arg);
return ParseResult.Error;
}
AddResource (new AssemblyResource (args[++i], args[i], true), settings);
return ParseResult.Success;
case "--target":
report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
if ((i + 1) >= args.Length){
Error_RequiresArgument (arg);
return ParseResult.Error;
}
string type = args [++i];
switch (type){
case "library":
settings.Target = Target.Library;
settings.TargetExt = ".dll";
break;
case "exe":
settings.Target = Target.Exe;
break;
case "winexe":
settings.Target = Target.WinExe;
break;
case "module":
settings.Target = Target.Module;
settings.TargetExt = ".dll";
break;
default:
report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
break;
}
return ParseResult.Success;
case "-r":
report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
if ((i + 1) >= args.Length){
Error_RequiresArgument (arg);
return ParseResult.Error;
}
string val = args [++i];
int idx = val.IndexOf ('=');
if (idx > -1) {
string alias = val.Substring (0, idx);
string assembly = val.Substring (idx + 1);
AddAssemblyReference (alias, assembly, settings);
return ParseResult.Success;
}
settings.AssemblyReferences.Add (val);
return ParseResult.Success;
case "-L":
report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
if ((i + 1) >= args.Length){
Error_RequiresArgument (arg);
return ParseResult.Error;
}
settings.ReferencesLookupPaths.Add (args [++i]);
return ParseResult.Success;
case "--lint":
settings.EnhancedWarnings = true;
return ParseResult.Success;
case "--nostdlib":
report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
settings.StdLib = false;
return ParseResult.Success;
case "--nowarn":
report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
if ((i + 1) >= args.Length){
Error_RequiresArgument (arg);
return ParseResult.Error;
}
int warn = 0;
try {
warn = int.Parse (args [++i]);
} catch {
Usage ();
Environment.Exit (1);
}
settings.SetIgnoreWarning (warn);
return ParseResult.Success;
case "--wlevel":
report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
if ((i + 1) >= args.Length){
Error_RequiresArgument (arg);
return ParseResult.Error;
}
SetWarningLevel (args [++i], settings);
return ParseResult.Success;
case "--mcs-debug":
if ((i + 1) >= args.Length){
Error_RequiresArgument (arg);
return ParseResult.Error;
}
try {
settings.DebugFlags = int.Parse (args [++i]);
} catch {
Error_RequiresArgument (arg);
return ParseResult.Error;
}
return ParseResult.Success;
case "--about":
About ();
return ParseResult.Stop;
case "--recurse":
report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
if ((i + 1) >= args.Length){
Error_RequiresArgument (arg);
return ParseResult.Error;
}
ProcessSourceFiles (args [++i], true, settings.SourceFiles);
return ParseResult.Success;
case "--timestamp":
settings.Timestamps = true;
return ParseResult.Success;
case "--debug": case "-g":
report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
settings.GenerateDebugInfo = true;
return ParseResult.Success;
case "--noconfig":
report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
settings.LoadDefaultReferences = false;
return ParseResult.Success;
case "--metadata-only":
settings.WriteMetadataOnly = true;
return ParseResult.Success;
default:
if (arg.StartsWith ("--fatal", StringComparison.Ordinal)){
int fatal = 1;
if (arg.StartsWith ("--fatal=", StringComparison.Ordinal))
int.TryParse (arg.Substring (8), out fatal);
settings.FatalCounter = fatal;
return ParseResult.Success;
}
if (arg.StartsWith ("--runtime:", StringComparison.Ordinal)) {
string version = arg.Substring (10);
switch (version) {
case "v1":
case "V1":
settings.StdLibRuntimeVersion = RuntimeVersion.v1;
break;
case "v2":
case "V2":
settings.StdLibRuntimeVersion = RuntimeVersion.v2;
break;
case "v4":
case "V4":
settings.StdLibRuntimeVersion = RuntimeVersion.v4;
break;
}
return ParseResult.Success;
}
return ParseResult.UnknownOption;
}
}
void SetWarningLevel (string s, CompilerSettings settings)
{
int level = -1;
try {
level = int.Parse (s);
} catch {
}
if (level < 0 || level > 4) {
report.Error (1900, "Warning level must be in the range 0-4");
return;
}
settings.WarningLevel = level;
}
//
// Given a path specification, splits the path from the file/pattern
//
static void SplitPathAndPattern (string spec, out string path, out string pattern)
{
int p = spec.LastIndexOf ('/');
if (p != -1) {
//
// Windows does not like /file.cs, switch that to:
// "\", "file.cs"
//
if (p == 0) {
path = "\\";
pattern = spec.Substring (1);
} else {
path = spec.Substring (0, p);
pattern = spec.Substring (p + 1);
}
return;
}
p = spec.LastIndexOf ('\\');
if (p != -1) {
path = spec.Substring (0, p);
pattern = spec.Substring (p + 1);
return;
}
path = ".";
pattern = spec;
}
void Usage ()
{
output.WriteLine (
#if PLAYSCRIPT
"PlayScript compiler, parts Copyright 2013 Zynga, Inc.\n" +
"Based on MCS compiler Copyright 2001-2011 Novell, Inc., Copyright 2011-2012 Xamarin, Inc\n" +
"playc [options] source-files\n" +
" --about About the PlayScript compiler\n" +
#else
"Mono C# compiler, Copyright 2001-2011 Novell, Inc., Copyright 2011-2012 Xamarin, Inc\n" +
"mcs [options] source-files\n" +
" --about About the Mono C# compiler\n" +
#endif
" -addmodule:M1[,Mn] Adds the module to the generated assembly\n" +
" -checked[+|-] Sets default aritmetic overflow context\n" +
" -clscheck[+|-] Disables CLS Compliance verifications\n" +
" -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
" -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" +
" -debug[+|-], -g Generate debugging information\n" +
" -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
" -doc:FILE Process documentation comments to XML file\n" +
" -fullpaths Any issued error or warning uses absolute file path\n" +
" -help Lists all compiler options (short: -?)\n" +
" -keycontainer:NAME The key pair container used to sign the output assembly\n" +
" -keyfile:FILE The key file used to strongname the ouput assembly\n" +
" -langversion:TEXT Specifies language version: ISO-1, ISO-2, 3, 4, 5, Default or Future\n" +
" -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" +
" -main:CLASS Specifies the class with the Main method (short: -m)\n" +
" -noconfig Disables implicitly referenced assemblies\n" +
" -nostdlib[+|-] Does not reference mscorlib.dll library\n" +
" -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" +
" -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" +
" -out:FILE Specifies output assembly name\n" +
" -pkg:P1[,Pn] References packages P1..Pn\n" +
" -platform:ARCH Specifies the target platform of the output assembly\n" +
" ARCH can be one of: anycpu, anycpu32bitpreferred, arm,\n" +
" x86, x64 or itanium. The default is anycpu.\n" +
" -recurse:SPEC Recursively compiles files according to SPEC pattern\n" +
" -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" +
" -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" +
" -sdk:VERSION Specifies SDK version of referenced assemblies\n" +
" VERSION can be one of: 2, 4, 4.5 (default) or a custom value\n" +
" -target:KIND Specifies the format of the output assembly (short: -t)\n" +
" KIND can be one of: exe, winexe, library, module\n" +
" -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" +
" -warnaserror[+|-] Treats all warnings as errors\n" +
" -warnaserror[+|-]:W1[,Wn] Treats one or more compiler warnings as errors\n" +
" -warn:0-4 Sets warning level, the default is 4 (short -w:)\n" +
" -helpinternal Shows internal and advanced compiler options\n" +
"\n" +
"Resources:\n" +
" -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
" -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" +
" -win32res:FILE Specifies Win32 resource file (.res)\n" +
" -win32icon:FILE Use this icon for the output\n" +
" @file Read response file for more options\n\n" +
"Options can be of the form -option or /option");
}
void Version ()
{
string version = System.Reflection.MethodBase.GetCurrentMethod ().DeclaringType.Assembly.GetName ().Version.ToString ();
output.WriteLine ("Mono C# compiler version {0}", version);
}
}
public class RootContext
{
//
// Contains the parsed tree
//
static ModuleContainer root;
static public ModuleContainer ToplevelTypes {
get { return root; }
set { root = value; }
}
}
}
| 26.729115
| 144
| 0.625325
|
[
"Apache-2.0"
] |
luiseduardohdbackup/playscript-mono
|
mcs/mcs/settings.cs
| 43,515
|
C#
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
namespace BLToolkit.Reflection
{
using TypeBuilder;
class ExprTypeAccessor<T,TOriginal> : TypeAccessor
{
static ExprTypeAccessor()
{
// Create Instance.
//
var type = typeof(T);
var typeInit = typeof(InitContext);
var initPar = Expression.Parameter(typeInit, "ctx");
if (type.IsValueType)
{
_createInstance = () => default(T);
_createInstanceInit = ctx => default(T);
}
else
{
var ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, Type.EmptyTypes, null);
var ctorInit = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, new[] { typeInit }, null);
if (ctor == null && ctorInit == null)
{
Expression<Func<T>> mi = () => ThrowException();
var body = Expression.Call(null, ((MethodCallExpression)mi.Body).Method);
_createInstance = Expression.Lambda<Func<T>>(body).Compile();
_createInstanceInit = Expression.Lambda<Func<InitContext, T>>(body, initPar).Compile();
}
else
{
_createInstance = ctor != null ?
Expression.Lambda<Func<T>>(Expression.New(ctor)).Compile() :
Expression.Lambda<Func<T>>(Expression.New(ctorInit, Expression.Constant(null))).Compile();
_createInstanceInit = ctorInit != null ?
Expression.Lambda<Func<InitContext, T>>(Expression.New(ctorInit, initPar), initPar).Compile() :
Expression.Lambda<Func<InitContext, T>>(Expression.New(ctor), initPar).Compile();
}
}
var originalType = typeof(TOriginal);
// Add fields.
//
foreach (var fi in originalType.GetFields(BindingFlags.Instance | BindingFlags.Public))
_members.Add(fi);
foreach (var pi in originalType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
if (pi.GetIndexParameters().Length == 0)
_members.Add(pi);
// Add explicit iterface implementation properties support
// Or maybe we should support all private fields/properties?
var interfaceMethods = originalType.GetInterfaces().SelectMany(ti => originalType.GetInterfaceMap(ti).TargetMethods).ToList();
if (interfaceMethods.Count > 0)
{
foreach (var pi in originalType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic))
{
if (pi.GetIndexParameters().Length == 0)
{
var getMethod = pi.GetGetMethod(true);
var setMethod = pi.GetSetMethod(true);
if ((getMethod == null || interfaceMethods.Contains(getMethod)) &&
(setMethod == null || interfaceMethods.Contains(setMethod)))
{
_members.Add(pi);
}
}
}
}
// ObjectFactory
//
var attr = TypeHelper.GetFirstAttribute(type, typeof(ObjectFactoryAttribute));
if (attr != null)
_objectFactory = ((ObjectFactoryAttribute)attr).ObjectFactory;
}
static T ThrowException()
{
throw new TypeBuilderException(string.Format("The '{0}' type must have default or init constructor.", typeof(TOriginal).FullName));
}
static readonly List<MemberInfo> _members = new List<MemberInfo>();
static readonly IObjectFactory _objectFactory;
public ExprTypeAccessor()
{
foreach (var member in _members)
AddMember(ExprMemberAccessor.GetMemberAccessor(this, member.Name));
ObjectFactory = _objectFactory;
}
static readonly Func<T> _createInstance;
public override object CreateInstance()
{
return _createInstance();
}
static readonly Func<InitContext,T> _createInstanceInit;
public override object CreateInstance(InitContext context)
{
return _createInstanceInit(context);
}
public override Type Type { get { return typeof(T); } }
public override Type OriginalType { get { return typeof(TOriginal); } }
}
}
| 31.650794
| 142
| 0.67327
|
[
"MIT"
] |
igor-tkachev/bltoolkit
|
Source/Reflection/ExprTypeAccessor.cs
| 3,990
|
C#
|
namespace ExerciseTwo
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.ProductLabel = new System.Windows.Forms.Label();
this.ProductTextBox = new System.Windows.Forms.TextBox();
this.DiscountLabel = new System.Windows.Forms.Label();
this.QuantityLabel = new System.Windows.Forms.Label();
this.PriceLabel = new System.Windows.Forms.Label();
this.QuantityTextBox = new System.Windows.Forms.TextBox();
this.DiscountTextBox = new System.Windows.Forms.TextBox();
this.PriceTextBox = new System.Windows.Forms.TextBox();
this.SaleValueLabel = new System.Windows.Forms.Label();
this.SalesValueTextBox = new System.Windows.Forms.TextBox();
this.NewSaleBtn = new System.Windows.Forms.Button();
this.Finishbtn = new System.Windows.Forms.Button();
this.TotalBtn = new System.Windows.Forms.Button();
this.ExitBtn = new System.Windows.Forms.Button();
this.TotalGroupBox = new System.Windows.Forms.GroupBox();
this.TotalTextBox = new System.Windows.Forms.TextBox();
this.TotalLabel = new System.Windows.Forms.Label();
this.TotalDiscountTextBox = new System.Windows.Forms.TextBox();
this.TotalDiscountLabel = new System.Windows.Forms.Label();
this.TotalSalesCountTextBox = new System.Windows.Forms.TextBox();
this.SalesCountValue = new System.Windows.Forms.Label();
this.TotalGroupBox.SuspendLayout();
this.SuspendLayout();
//
// ProductLabel
//
this.ProductLabel.AutoSize = true;
this.ProductLabel.Location = new System.Drawing.Point(40, 34);
this.ProductLabel.Name = "ProductLabel";
this.ProductLabel.Size = new System.Drawing.Size(48, 13);
this.ProductLabel.TabIndex = 0;
this.ProductLabel.Text = "Артикул";
//
// ProductTextBox
//
this.ProductTextBox.Location = new System.Drawing.Point(135, 34);
this.ProductTextBox.Name = "ProductTextBox";
this.ProductTextBox.Size = new System.Drawing.Size(100, 20);
this.ProductTextBox.TabIndex = 1;
//
// DiscountLabel
//
this.DiscountLabel.AutoSize = true;
this.DiscountLabel.Location = new System.Drawing.Point(40, 159);
this.DiscountLabel.Name = "DiscountLabel";
this.DiscountLabel.Size = new System.Drawing.Size(56, 13);
this.DiscountLabel.TabIndex = 2;
this.DiscountLabel.Text = "Отстъпка";
//
// QuantityLabel
//
this.QuantityLabel.AutoSize = true;
this.QuantityLabel.Location = new System.Drawing.Point(40, 117);
this.QuantityLabel.Name = "QuantityLabel";
this.QuantityLabel.Size = new System.Drawing.Size(66, 13);
this.QuantityLabel.TabIndex = 3;
this.QuantityLabel.Text = "Количество";
//
// PriceLabel
//
this.PriceLabel.AutoSize = true;
this.PriceLabel.Location = new System.Drawing.Point(40, 78);
this.PriceLabel.Name = "PriceLabel";
this.PriceLabel.Size = new System.Drawing.Size(84, 13);
this.PriceLabel.TabIndex = 4;
this.PriceLabel.Text = "Единична Цена";
//
// QuantityTextBox
//
this.QuantityTextBox.Location = new System.Drawing.Point(135, 117);
this.QuantityTextBox.Name = "QuantityTextBox";
this.QuantityTextBox.Size = new System.Drawing.Size(100, 20);
this.QuantityTextBox.TabIndex = 5;
//
// DiscountTextBox
//
this.DiscountTextBox.Location = new System.Drawing.Point(135, 159);
this.DiscountTextBox.Name = "DiscountTextBox";
this.DiscountTextBox.ReadOnly = true;
this.DiscountTextBox.Size = new System.Drawing.Size(100, 20);
this.DiscountTextBox.TabIndex = 6;
//
// PriceTextBox
//
this.PriceTextBox.Location = new System.Drawing.Point(135, 78);
this.PriceTextBox.Name = "PriceTextBox";
this.PriceTextBox.Size = new System.Drawing.Size(100, 20);
this.PriceTextBox.TabIndex = 7;
//
// SaleValueLabel
//
this.SaleValueLabel.AutoSize = true;
this.SaleValueLabel.Location = new System.Drawing.Point(40, 201);
this.SaleValueLabel.Name = "SaleValueLabel";
this.SaleValueLabel.Size = new System.Drawing.Size(54, 13);
this.SaleValueLabel.TabIndex = 8;
this.SaleValueLabel.Text = "Стойност";
//
// SalesValueTextBox
//
this.SalesValueTextBox.Location = new System.Drawing.Point(135, 201);
this.SalesValueTextBox.Name = "SalesValueTextBox";
this.SalesValueTextBox.ReadOnly = true;
this.SalesValueTextBox.Size = new System.Drawing.Size(100, 20);
this.SalesValueTextBox.TabIndex = 9;
//
// NewSaleBtn
//
this.NewSaleBtn.Enabled = false;
this.NewSaleBtn.Location = new System.Drawing.Point(389, 30);
this.NewSaleBtn.Name = "NewSaleBtn";
this.NewSaleBtn.Size = new System.Drawing.Size(159, 23);
this.NewSaleBtn.TabIndex = 10;
this.NewSaleBtn.Text = "Нова продажба";
this.NewSaleBtn.UseVisualStyleBackColor = true;
this.NewSaleBtn.Click += new System.EventHandler(this.NewSaleBtn_Click);
//
// Finishbtn
//
this.Finishbtn.Location = new System.Drawing.Point(389, 172);
this.Finishbtn.Name = "Finishbtn";
this.Finishbtn.Size = new System.Drawing.Size(159, 23);
this.Finishbtn.TabIndex = 11;
this.Finishbtn.Text = "Приключване";
this.Finishbtn.UseVisualStyleBackColor = true;
this.Finishbtn.Click += new System.EventHandler(this.Finishbtn_Click);
//
// TotalBtn
//
this.TotalBtn.Location = new System.Drawing.Point(389, 59);
this.TotalBtn.Name = "TotalBtn";
this.TotalBtn.Size = new System.Drawing.Size(159, 23);
this.TotalBtn.TabIndex = 12;
this.TotalBtn.Text = "Тотал";
this.TotalBtn.UseVisualStyleBackColor = true;
this.TotalBtn.Click += new System.EventHandler(this.TotalBtn_Click);
//
// ExitBtn
//
this.ExitBtn.Location = new System.Drawing.Point(389, 201);
this.ExitBtn.Name = "ExitBtn";
this.ExitBtn.Size = new System.Drawing.Size(159, 23);
this.ExitBtn.TabIndex = 13;
this.ExitBtn.Text = "Изход";
this.ExitBtn.UseVisualStyleBackColor = true;
this.ExitBtn.Click += new System.EventHandler(this.ExitBtn_Click);
//
// TotalGroupBox
//
this.TotalGroupBox.Controls.Add(this.TotalTextBox);
this.TotalGroupBox.Controls.Add(this.TotalLabel);
this.TotalGroupBox.Controls.Add(this.TotalDiscountTextBox);
this.TotalGroupBox.Controls.Add(this.TotalDiscountLabel);
this.TotalGroupBox.Controls.Add(this.TotalSalesCountTextBox);
this.TotalGroupBox.Controls.Add(this.SalesCountValue);
this.TotalGroupBox.Location = new System.Drawing.Point(43, 261);
this.TotalGroupBox.Name = "TotalGroupBox";
this.TotalGroupBox.Size = new System.Drawing.Size(505, 83);
this.TotalGroupBox.TabIndex = 14;
this.TotalGroupBox.TabStop = false;
this.TotalGroupBox.Text = "Тотал";
//
// TotalTextBox
//
this.TotalTextBox.Location = new System.Drawing.Point(346, 43);
this.TotalTextBox.Name = "TotalTextBox";
this.TotalTextBox.ReadOnly = true;
this.TotalTextBox.Size = new System.Drawing.Size(100, 20);
this.TotalTextBox.TabIndex = 19;
//
// TotalLabel
//
this.TotalLabel.AutoSize = true;
this.TotalLabel.Location = new System.Drawing.Point(343, 23);
this.TotalLabel.Name = "TotalLabel";
this.TotalLabel.Size = new System.Drawing.Size(85, 13);
this.TotalLabel.TabIndex = 18;
this.TotalLabel.Text = "Обща стойност";
//
// TotalDiscountTextBox
//
this.TotalDiscountTextBox.Location = new System.Drawing.Point(183, 43);
this.TotalDiscountTextBox.Name = "TotalDiscountTextBox";
this.TotalDiscountTextBox.ReadOnly = true;
this.TotalDiscountTextBox.Size = new System.Drawing.Size(100, 20);
this.TotalDiscountTextBox.TabIndex = 17;
//
// TotalDiscountLabel
//
this.TotalDiscountLabel.AutoSize = true;
this.TotalDiscountLabel.Location = new System.Drawing.Point(180, 23);
this.TotalDiscountLabel.Name = "TotalDiscountLabel";
this.TotalDiscountLabel.Size = new System.Drawing.Size(56, 13);
this.TotalDiscountLabel.TabIndex = 16;
this.TotalDiscountLabel.Text = "Отстъпка";
//
// TotalSalesCountTextBox
//
this.TotalSalesCountTextBox.Location = new System.Drawing.Point(28, 43);
this.TotalSalesCountTextBox.Name = "TotalSalesCountTextBox";
this.TotalSalesCountTextBox.ReadOnly = true;
this.TotalSalesCountTextBox.Size = new System.Drawing.Size(100, 20);
this.TotalSalesCountTextBox.TabIndex = 15;
//
// SalesCountValue
//
this.SalesCountValue.AutoSize = true;
this.SalesCountValue.Location = new System.Drawing.Point(25, 27);
this.SalesCountValue.Name = "SalesCountValue";
this.SalesCountValue.Size = new System.Drawing.Size(85, 13);
this.SalesCountValue.TabIndex = 3;
this.SalesCountValue.Text = "Брой продажби";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(638, 370);
this.Controls.Add(this.TotalGroupBox);
this.Controls.Add(this.ExitBtn);
this.Controls.Add(this.TotalBtn);
this.Controls.Add(this.Finishbtn);
this.Controls.Add(this.NewSaleBtn);
this.Controls.Add(this.SalesValueTextBox);
this.Controls.Add(this.SaleValueLabel);
this.Controls.Add(this.PriceTextBox);
this.Controls.Add(this.DiscountTextBox);
this.Controls.Add(this.QuantityTextBox);
this.Controls.Add(this.PriceLabel);
this.Controls.Add(this.QuantityLabel);
this.Controls.Add(this.DiscountLabel);
this.Controls.Add(this.ProductTextBox);
this.Controls.Add(this.ProductLabel);
this.Name = "Form1";
this.Text = "Информационна система продажби";
this.TotalGroupBox.ResumeLayout(false);
this.TotalGroupBox.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label ProductLabel;
private System.Windows.Forms.TextBox ProductTextBox;
private System.Windows.Forms.Label DiscountLabel;
private System.Windows.Forms.Label QuantityLabel;
private System.Windows.Forms.Label PriceLabel;
private System.Windows.Forms.TextBox QuantityTextBox;
private System.Windows.Forms.TextBox DiscountTextBox;
private System.Windows.Forms.TextBox PriceTextBox;
private System.Windows.Forms.Label SaleValueLabel;
private System.Windows.Forms.TextBox SalesValueTextBox;
private System.Windows.Forms.Button NewSaleBtn;
private System.Windows.Forms.Button Finishbtn;
private System.Windows.Forms.Button TotalBtn;
private System.Windows.Forms.Button ExitBtn;
private System.Windows.Forms.GroupBox TotalGroupBox;
private System.Windows.Forms.TextBox TotalTextBox;
private System.Windows.Forms.Label TotalLabel;
private System.Windows.Forms.TextBox TotalDiscountTextBox;
private System.Windows.Forms.Label TotalDiscountLabel;
private System.Windows.Forms.TextBox TotalSalesCountTextBox;
private System.Windows.Forms.Label SalesCountValue;
}
}
| 46.531773
| 107
| 0.596852
|
[
"MIT"
] |
RuzmanovDev/UNWE
|
User-Interface/WinFormsExercises/02.ExerciseTwo/ExerciseTwo/Form1.Designer.cs
| 14,058
|
C#
|
using System;
using System.ComponentModel;
using EfsTools.Attributes;
using EfsTools.Utils;
using Newtonsoft.Json;
namespace EfsTools.Items.Efs
{
[Serializable]
[EfsFile("/nv/item_files/rfnv/00023696", true, 0xE1FF)]
[Attributes(9)]
public class LteB34TxMismatchComp
{
[ElementsCount(2)]
[ElementType("int16")]
[Description("")]
public short[] Value { get; set; }
}
}
| 21.619048
| 60
| 0.614537
|
[
"MIT"
] |
HomerSp/EfsTools
|
EfsTools/Items/Efs/LteB34TxMismatchCompI.cs
| 454
|
C#
|
using System.Threading.Tasks;
using NServiceBus;
using NServiceBus.Logging;
#region CommandMessageHandler
public class CommandMessageHandler :
IHandleMessages<Command>
{
static ILog log = LogManager.GetLogger<CommandMessageHandler>();
public Task Handle(Command message, IMessageHandlerContext context)
{
log.Info("Hello from CommandMessageHandler");
Task reply;
if (message.Id % 2 == 0)
{
log.Info("Returning Fail");
reply = context.Reply(ErrorCodes.Fail);
}
else
{
log.Info("Returning None");
reply = context.Reply(ErrorCodes.None);
}
return reply;
}
}
#endregion
| 24.633333
| 72
| 0.598106
|
[
"Apache-2.0"
] |
A-Franklin/docs.particular.net
|
samples/web/asp-mvc-application/Core_6/Server/CommandMessageHandler.cs
| 712
|
C#
|
using BAYSOFT.Core.Domain.Entities.StockWallet;
using BAYSOFT.Core.Domain.Interfaces.Infrastructures.Data.Contexts;
using BAYSOFT.Core.Domain.Interfaces.Services.StockWallet.SubSectors;
using ModelWrapper.Extensions.Post;
using System.Threading;
using System.Threading.Tasks;
namespace BAYSOFT.Core.Application.StockWallet.SubSectors.Commands.PostSubSector
{
public class PostSubSectorCommandHandler : ApplicationRequestHandler<SubSector, PostSubSectorCommand, PostSubSectorCommandResponse>
{
private IStockWalletDbContext Context { get; set; }
private IPostSubSectorService PostService { get; set; }
public PostSubSectorCommandHandler(
IStockWalletDbContext context,
IPostSubSectorService postService
)
{
Context = context;
PostService = postService;
}
public override async Task<PostSubSectorCommandResponse> Handle(PostSubSectorCommand request, CancellationToken cancellationToken)
{
var data = request.Post();
await PostService.Run(data);
await Context.SaveChangesAsync();
return new PostSubSectorCommandResponse(request, data, "Successful operation!", 1);
}
}
}
| 36.794118
| 138
| 0.719424
|
[
"MIT"
] |
BAYSOFT-001/baysoft-stockwallet
|
src/BAYSOFT.Core.Application/StockWallet/SubSectors/Commands/PostSubSector/PostSubSectorCommandHandler.cs
| 1,251
|
C#
|
namespace Hills.IdentityServer4.Deployment
{
partial class ucEndPointsEditor
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lnkRemove = new System.Windows.Forms.LinkLabel();
this.lnkEdit = new System.Windows.Forms.LinkLabel();
this.lnkAdd = new System.Windows.Forms.LinkLabel();
this.lblTitle = new System.Windows.Forms.Label();
this.lstEndPoints = new System.Windows.Forms.ListView();
this.colName = new System.Windows.Forms.ColumnHeader();
this.colIpAddress = new System.Windows.Forms.ColumnHeader();
this.colPort = new System.Windows.Forms.ColumnHeader();
this.colHttps = new System.Windows.Forms.ColumnHeader();
this.colCertType = new System.Windows.Forms.ColumnHeader();
this.colCertFileName = new System.Windows.Forms.ColumnHeader();
this.colValidity = new System.Windows.Forms.ColumnHeader();
this.SuspendLayout();
//
// lnkRemove
//
this.lnkRemove.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.lnkRemove.AutoSize = true;
this.lnkRemove.Location = new System.Drawing.Point(71, 298);
this.lnkRemove.Name = "lnkRemove";
this.lnkRemove.Size = new System.Drawing.Size(50, 15);
this.lnkRemove.TabIndex = 12;
this.lnkRemove.TabStop = true;
this.lnkRemove.Text = "Remove";
this.lnkRemove.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkRemove_LinkClicked);
//
// lnkEdit
//
this.lnkEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.lnkEdit.AutoSize = true;
this.lnkEdit.Location = new System.Drawing.Point(38, 298);
this.lnkEdit.Name = "lnkEdit";
this.lnkEdit.Size = new System.Drawing.Size(27, 15);
this.lnkEdit.TabIndex = 10;
this.lnkEdit.TabStop = true;
this.lnkEdit.Text = "Edit";
this.lnkEdit.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkEdit_LinkClicked);
//
// lnkAdd
//
this.lnkAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.lnkAdd.AutoSize = true;
this.lnkAdd.Location = new System.Drawing.Point(3, 298);
this.lnkAdd.Name = "lnkAdd";
this.lnkAdd.Size = new System.Drawing.Size(29, 15);
this.lnkAdd.TabIndex = 11;
this.lnkAdd.TabStop = true;
this.lnkAdd.Text = "Add";
this.lnkAdd.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkEdit_LinkClicked);
//
// lblTitle
//
this.lblTitle.AutoSize = true;
this.lblTitle.Location = new System.Drawing.Point(3, 0);
this.lblTitle.Name = "lblTitle";
this.lblTitle.Size = new System.Drawing.Size(144, 15);
this.lblTitle.TabIndex = 9;
this.lblTitle.Text = "End Points IdentityServer4";
//
// lstEndPoints
//
this.lstEndPoints.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lstEndPoints.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.colName,
this.colIpAddress,
this.colPort,
this.colHttps,
this.colCertType,
this.colCertFileName,
this.colValidity});
this.lstEndPoints.FullRowSelect = true;
this.lstEndPoints.HideSelection = false;
this.lstEndPoints.Location = new System.Drawing.Point(3, 18);
this.lstEndPoints.Name = "lstEndPoints";
this.lstEndPoints.Size = new System.Drawing.Size(615, 277);
this.lstEndPoints.TabIndex = 8;
this.lstEndPoints.UseCompatibleStateImageBehavior = false;
this.lstEndPoints.View = System.Windows.Forms.View.Details;
//
// colName
//
this.colName.Text = "Name";
this.colName.Width = 150;
//
// colIpAddress
//
this.colIpAddress.Text = "Ip Address";
this.colIpAddress.Width = 100;
//
// colPort
//
this.colPort.Text = "Port";
//
// colHttps
//
this.colHttps.Text = "Https";
//
// colCertType
//
this.colCertType.Text = "Cert Type";
this.colCertType.Width = 100;
//
// colCertFileName
//
this.colCertFileName.Text = "Cert Source";
this.colCertFileName.Width = 300;
//
// colValidity
//
this.colValidity.Text = "Validity";
//
// ucEndPointsEditor
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.lnkRemove);
this.Controls.Add(this.lnkEdit);
this.Controls.Add(this.lnkAdd);
this.Controls.Add(this.lblTitle);
this.Controls.Add(this.lstEndPoints);
this.Name = "ucEndPointsEditor";
this.Size = new System.Drawing.Size(621, 313);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.LinkLabel lnkRemove;
private System.Windows.Forms.LinkLabel lnkEdit;
private System.Windows.Forms.LinkLabel lnkAdd;
private System.Windows.Forms.Label lblTitle;
private System.Windows.Forms.ListView lstEndPoints;
private System.Windows.Forms.ColumnHeader colName;
private System.Windows.Forms.ColumnHeader colIpAddress;
private System.Windows.Forms.ColumnHeader colPort;
private System.Windows.Forms.ColumnHeader colHttps;
private System.Windows.Forms.ColumnHeader colCertType;
private System.Windows.Forms.ColumnHeader colCertFileName;
private System.Windows.Forms.ColumnHeader colValidity;
}
}
| 43.214689
| 161
| 0.584129
|
[
"MIT"
] |
elaganahills/IdentityServer4.Admin
|
deployment/ucEndPointsEditor.Designer.cs
| 7,651
|
C#
|
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using LiteDB;
using Microsoft.Extensions.Logging;
namespace Lyra.Features.Config
{
public class PresenterConfigService : IPresenterConfigService
{
private readonly ILogger<PresenterConfig> logger;
private readonly ILiteRepository dbRepository;
private readonly string sessionCollectionName;
public PresenterConfigService(ILogger<PresenterConfig> logger, ILiteRepository dbRepository)
{
this.logger = logger;
this.dbRepository = dbRepository;
sessionCollectionName = this.dbRepository.Database.GetCollection<PresenterConfig>().Name;
}
public IReadOnlyCollection<PresenterScreen> GetScreens()
{
return Screen.AllScreens.Select((s, id) => new PresenterScreen
{
ScreenId = id,
DeviceName = s.DeviceName,
Bounds = s.Bounds,
IsPrimary = s.Primary,
}).ToList();
}
public PresenterScreen GetSelectedPresenterScreen()
{
var config = dbRepository.FirstOrDefault<PresenterConfig>(x => x.Id == PresenterConfig.ConfigId);
var screen = Screen.AllScreens.FirstOrDefault(x => x.DeviceName == config?.SelectedScreen)
?? Screen.AllScreens.First(x => x.Primary);
return new PresenterScreen
{
DeviceName = screen.DeviceName,
Bounds = screen.Bounds,
IsPrimary = screen.Primary,
};
}
public void SelectPresenterScreen(PresenterScreen presenterScreen)
{
var config = dbRepository.FirstOrDefault<PresenterConfig>(x => x.Id == PresenterConfig.ConfigId) ?? new PresenterConfig();
config.SelectedScreen = presenterScreen.DeviceName;
dbRepository.Upsert(config);
}
}
}
| 36.37037
| 134
| 0.625764
|
[
"MIT"
] |
ogirard/lyra
|
src/Lyra/Features/Config/PresenterConfigService.cs
| 1,964
|
C#
|
using Microsoft.Data.SqlClient;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RepoDb.Extensions;
using RepoDb.IntegrationTests.Setup;
using RepoDb.SqlServer.BulkOperations.IntegrationTests.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
namespace RepoDb.SqlServer.BulkOperations.IntegrationTests.Operations
{
[TestClass]
public class MicrosoftSqlConnectionBulkUpdateOperationsTest
{
[TestInitialize]
public void Initialize()
{
Database.Initialize();
Cleanup();
}
[TestCleanup]
public void Cleanup()
{
Database.Cleanup();
}
#region BulkUpdate<TEntity>
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateForEntities()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll(tables);
// Setup
Helper.UpdateBulkOperationIdentityTables(tables);
// Act
var bulkUpdateResult = connection.BulkUpdate(tables);
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateForEntitiesWithQualifiers()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll(tables);
// Setup
Helper.UpdateBulkOperationIdentityTables(tables);
// Act
var bulkUpdateResult = connection.BulkUpdate(tables,
qualifiers: Field.From("RowGuid", "ColumnInt"));
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateForEntitiesWithUsePhysicalPseudoTempTable()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll(tables);
// Setup
Helper.UpdateBulkOperationIdentityTables(tables);
// Act
var bulkUpdateResult = connection.BulkUpdate(tables,
usePhysicalPseudoTempTable: true);
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateForEntitiesWithMappings()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add the mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.Id), nameof(BulkOperationIdentityTable.Id)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.RowGuid), nameof(BulkOperationIdentityTable.RowGuid)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnInt)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll(tables);
// Setup
Helper.UpdateBulkOperationIdentityTables(tables);
// Act
var bulkUpdateResult = connection.BulkUpdate(tables, mappings: mappings);
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateForEntitiesIfTheMappingsAreInvalid()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add invalid mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
// Switched
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnInt)));
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.BulkUpdate(tables, mappings: mappings);
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateForEntitiesDbDataReader()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdate<BulkOperationIdentityTable>((DbDataReader)reader);
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateForEntitiesDbDataReaderWithMappings()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add the mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.Id), nameof(BulkOperationIdentityTable.Id)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.RowGuid), nameof(BulkOperationIdentityTable.RowGuid)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnInt)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdate<BulkOperationIdentityTable>((DbDataReader)reader,
mappings: mappings);
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateForEntitiesDbDataReaderIfTheMappingsAreInvalid()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add invalid mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
// Switched
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnInt)));
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
destinationConnection.BulkUpdate<BulkOperationIdentityTable>((DbDataReader)reader,
mappings: mappings);
}
}
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateForEntitiesDataTable()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
using (var table = new DataTable())
{
table.Load(reader);
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdate<BulkOperationIdentityTable>(table);
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateForEntitiesDataTableWithMappings()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add the mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.Id), nameof(BulkOperationIdentityTable.Id)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.RowGuid), nameof(BulkOperationIdentityTable.RowGuid)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnInt)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
using (var table = new DataTable())
{
table.Load(reader);
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdate<BulkOperationIdentityTable>(table,
mappings: mappings);
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
}
[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateForEntitiesDataTableIfTheMappingsAreInvalid()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add invalid mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
// Switched
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnInt)));
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
using (var table = new DataTable())
{
table.Load(reader);
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
destinationConnection.BulkUpdate<BulkOperationIdentityTable>(table,
mappings: mappings);
}
}
}
}
}
#endregion
#region BulkUpdate<TEntity>(Extra Fields)
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateForEntitiesWithExtraFields()
{
// Setup
var tables = Helper.CreateWithExtraFieldsBulkOperationIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Setup
connection.InsertAll(tables);
// Setup
Helper.UpdateWithExtraFieldsBulkOperationIdentityTables(tables);
// Act
var bulkUpdateResult = connection.BulkUpdate(tables);
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateForEntitiesWithExtraFieldsWithMappings()
{
// Setup
var tables = Helper.CreateWithExtraFieldsBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add the mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnInt)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Setup
connection.InsertAll(tables);
// Setup
Helper.UpdateWithExtraFieldsBulkOperationIdentityTables(tables);
// Act
var bulkUpdateResult = connection.BulkUpdate(tables);
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
#endregion
#region BulkUpdate(TableName)
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateForTableNameDataEntities()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Setup
connection.InsertAll(tables);
// Setup
Helper.UpdateBulkOperationIdentityTables(tables);
// Act
var bulkUpdateResult = connection.BulkUpdate(ClassMappedNameCache.Get<BulkOperationIdentityTable>(), tables);
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateForTableNameDataEntitiesWithQualifiers()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Setup
connection.InsertAll(tables);
// Setup
Helper.UpdateBulkOperationIdentityTables(tables);
// Act
var bulkUpdateResult = connection.BulkUpdate(ClassMappedNameCache.Get<BulkOperationIdentityTable>(),
tables,
qualifiers: Field.From("RowGuid", "ColumnInt"));
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateForTableNameDataEntitiesWithUsePhysicalPseudoTempTable()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Setup
connection.InsertAll(tables);
// Setup
Helper.UpdateBulkOperationIdentityTables(tables);
// Act
var bulkUpdateResult = connection.BulkUpdate(ClassMappedNameCache.Get<BulkOperationIdentityTable>(),
tables,
usePhysicalPseudoTempTable: true);
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateForTableNameDbDataReader()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdate(ClassMappedNameCache.Get<BulkOperationIdentityTable>(),
(DbDataReader)reader);
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateForTableNameDbDataReaderWithMappings()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add the mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.Id), nameof(BulkOperationIdentityTable.Id)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.RowGuid), nameof(BulkOperationIdentityTable.RowGuid)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnInt)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdate(ClassMappedNameCache.Get<BulkOperationIdentityTable>(),
(DbDataReader)reader,
mappings: mappings);
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateForTableNameDbDataReaderIfTheMappingsAreInvalid()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add invalid mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
// Switched
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnInt)));
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdate(ClassMappedNameCache.Get<BulkOperationIdentityTable>(),
(DbDataReader)reader,
mappings: mappings);
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateForTableNameDbDataReaderIfTheTableNameIsNotValid()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
destinationConnection.BulkUpdate("InvalidTable", (DbDataReader)reader);
}
}
}
}
[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateForTableNameDbDataReaderIfTheTableNameIsMissing()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
destinationConnection.BulkUpdate("MissingTable", (DbDataReader)reader);
}
}
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateForTableNameDbDataTable()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
using (var table = new DataTable())
{
table.Load(reader);
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdate(ClassMappedNameCache.Get<BulkOperationIdentityTable>(), table);
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateForTableNameDbDataTableWithMappings()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add the mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.Id), nameof(BulkOperationIdentityTable.Id)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.RowGuid), nameof(BulkOperationIdentityTable.RowGuid)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnInt)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
using (var table = new DataTable())
{
table.Load(reader);
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdate(ClassMappedNameCache.Get<BulkOperationIdentityTable>(),
table,
mappings: mappings);
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
}
[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateForTableNameDbDataTableIfTheMappingsAreInvalid()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add invalid mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
// Switched
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnInt)));
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
using (var table = new DataTable())
{
table.Load(reader);
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdate(ClassMappedNameCache.Get<BulkOperationIdentityTable>(),
table,
mappings: mappings);
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
}
[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateForTableNameDbDataTableIfTheTableNameIsNotValid()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
using (var table = new DataTable())
{
table.Load(reader);
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
destinationConnection.BulkUpdate("InvalidTable",
table);
}
}
}
}
}
[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateForTableNameDbDataTableIfTheTableNameIsMissing()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
using (var table = new DataTable())
{
table.Load(reader);
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
destinationConnection.BulkUpdate("MissingTable",
table);
}
}
}
}
}
#endregion
#region BulkUpdateAsync<TEntity>
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateAsyncForEntities()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll(tables);
// Setup
Helper.UpdateBulkOperationIdentityTables(tables);
// Act
var bulkUpdateResult = connection.BulkUpdateAsync(tables).Result;
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateAsyncForEntitiesWithQualifiers()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll(tables);
// Setup
Helper.UpdateBulkOperationIdentityTables(tables);
// Act
var bulkUpdateResult = connection.BulkUpdateAsync(tables,
qualifiers: Field.From("RowGuid", "ColumnInt")).Result;
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateAsyncForEntitiesWithUsePhysicalPseudoTempTable()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
connection.InsertAll(tables);
// Setup
Helper.UpdateBulkOperationIdentityTables(tables);
// Act
var bulkUpdateResult = connection.BulkUpdateAsync(tables,
usePhysicalPseudoTempTable: true).Result;
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateAsyncForEntitiesWithMappings()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add the mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.Id), nameof(BulkOperationIdentityTable.Id)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.RowGuid), nameof(BulkOperationIdentityTable.RowGuid)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnInt)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Setup
connection.InsertAll(tables);
// Act
var bulkUpdateResult = connection.BulkUpdateAsync(tables, mappings: mappings).Result;
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
[TestMethod, ExpectedException(typeof(AggregateException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateAsyncForEntitiesIfTheMappingsAreInvalid()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add invalid mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
// Switched
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnInt)));
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = connection.BulkUpdateAsync(tables,
mappings: mappings);
// Trigger
var result = bulkUpdateResult.Result;
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateAsyncForEntitiesDbDataReader()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdateAsync<BulkOperationIdentityTable>((DbDataReader)reader).Result;
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateAsyncForEntitiesDbDataReaderWithMappings()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add the mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.Id), nameof(BulkOperationIdentityTable.Id)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.RowGuid), nameof(BulkOperationIdentityTable.RowGuid)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnInt)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdateAsync<BulkOperationIdentityTable>((DbDataReader)reader,
mappings: mappings).Result;
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
[TestMethod, ExpectedException(typeof(AggregateException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateAsyncForEntitiesDbDataReaderIfTheMappingsAreInvalid()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add invalid mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
// Switched
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnInt)));
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdateAsync<BulkOperationIdentityTable>((DbDataReader)reader,
mappings: mappings);
// Trigger
var result = bulkUpdateResult.Result;
}
}
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateAsyncForEntitiesDataTable()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
using (var table = new DataTable())
{
table.Load(reader);
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdateAsync<BulkOperationIdentityTable>(table).Result;
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateAsyncForEntitiesDataTableWithMappings()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add the mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.Id), nameof(BulkOperationIdentityTable.Id)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.RowGuid), nameof(BulkOperationIdentityTable.RowGuid)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnInt)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
using (var table = new DataTable())
{
table.Load(reader);
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdateAsync<BulkOperationIdentityTable>(table,
mappings: mappings).Result;
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
}
[TestMethod, ExpectedException(typeof(AggregateException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateAsyncForEntitiesDataTableIfTheMappingsAreInvalid()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add invalid mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
// Switched
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnInt)));
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
using (var table = new DataTable())
{
table.Load(reader);
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdateAsync<BulkOperationIdentityTable>(table,
mappings: mappings);
// Trigger
var result = bulkUpdateResult.Result;
}
}
}
}
}
#endregion
#region BulkUpdateAsync<TEntity>(Extra Fields)
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateAsyncForEntitiesWithExtraFields()
{
// Setup
var tables = Helper.CreateWithExtraFieldsBulkOperationIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Setup
connection.InsertAll(tables);
// Setup
Helper.UpdateWithExtraFieldsBulkOperationIdentityTables(tables);
// Act
var bulkUpdateResult = connection.BulkUpdateAsync(tables).Result;
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateAsyncForEntitiesWithExtraFieldsWithMappings()
{
// Setup
var tables = Helper.CreateWithExtraFieldsBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add the mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.Id), nameof(BulkOperationIdentityTable.Id)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnInt)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Setup
connection.InsertAll(tables);
// Setup
Helper.UpdateWithExtraFieldsBulkOperationIdentityTables(tables);
// Act
var bulkUpdateResult = connection.BulkUpdateAsync(tables).Result;
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
#endregion
#region BulkUpdateAsync(TableName)
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateAsyncForTableNameDataEntities()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Setup
connection.InsertAll(tables);
// Setup
Helper.UpdateBulkOperationIdentityTables(tables);
// Act
var bulkUpdateResult = connection.BulkUpdateAsync(ClassMappedNameCache.Get<BulkOperationIdentityTable>(), tables).Result;
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateAsyncForTableNameDataEntitiesWithQualifiers()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Setup
connection.InsertAll(tables);
// Setup
Helper.UpdateBulkOperationIdentityTables(tables);
// Act
var bulkUpdateResult = connection.BulkUpdateAsync(ClassMappedNameCache.Get<BulkOperationIdentityTable>(),
tables,
qualifiers: Field.From("RowGuid", "ColumnInt")).Result;
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateAsyncForTableNameDataEntitiesWithUsePhysicalPseudoTempTable()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Setup
connection.InsertAll(tables);
// Setup
Helper.UpdateBulkOperationIdentityTables(tables);
// Act
var bulkUpdateResult = connection.BulkUpdateAsync(ClassMappedNameCache.Get<BulkOperationIdentityTable>(),
tables,
usePhysicalPseudoTempTable: true).Result;
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
// Act
var queryResult = connection.QueryAll<BulkOperationIdentityTable>();
// Assert
Assert.AreEqual(tables.Count, queryResult.Count());
tables.AsList().ForEach(t =>
{
Helper.AssertPropertiesEquality(t, queryResult.ElementAt(tables.IndexOf(t)));
});
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateAsyncForTableNameDbDataReader()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdateAsync(ClassMappedNameCache.Get<BulkOperationIdentityTable>(), (DbDataReader)reader).Result;
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateAsyncForTableNameDbDataReaderWithMappings()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add the mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.Id), nameof(BulkOperationIdentityTable.Id)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.RowGuid), nameof(BulkOperationIdentityTable.RowGuid)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnInt)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdateAsync(ClassMappedNameCache.Get<BulkOperationIdentityTable>(),
(DbDataReader)reader,
mappings: mappings).Result;
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
[TestMethod, ExpectedException(typeof(AggregateException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateAsyncForTableNameDbDataReaderIfTheMappingsAreInvalid()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add invalid mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
// Switched
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnInt)));
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdateAsync(ClassMappedNameCache.Get<BulkOperationIdentityTable>(),
(DbDataReader)reader,
mappings: mappings);
// Trigger
var result = bulkUpdateResult.Result;
}
}
}
}
[TestMethod, ExpectedException(typeof(AggregateException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateAsyncForTableNameDbDataReaderIfTheTableNameIsNotValid()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdateAsync("InvalidTable", (DbDataReader)reader);
// Trigger
var result = bulkUpdateResult.Result;
}
}
}
}
[TestMethod, ExpectedException(typeof(AggregateException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateAsyncForTableNameDbDataReaderIfTheTableNameIsMissing()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdateAsync("MissingTable", (DbDataReader)reader);
// Trigger
var result = bulkUpdateResult.Result;
}
}
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateAsyncForTableNameDataTable()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
using (var table = new DataTable())
{
table.Load(reader);
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdateAsync(ClassMappedNameCache.Get<BulkOperationIdentityTable>(), table).Result;
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
}
[TestMethod]
public void TestMicrosoftSqlConnectionBulkUpdateAsyncForTableNameDataTableWithMappings()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add the mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.Id), nameof(BulkOperationIdentityTable.Id)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.RowGuid), nameof(BulkOperationIdentityTable.RowGuid)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnInt)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
using (var table = new DataTable())
{
table.Load(reader);
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdateAsync(ClassMappedNameCache.Get<BulkOperationIdentityTable>(),
table,
mappings: mappings).Result;
// Assert
Assert.AreEqual(tables.Count, bulkUpdateResult);
}
}
}
}
}
[TestMethod, ExpectedException(typeof(AggregateException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateAsyncForTableNameDataTableIfTheMappingsAreInvalid()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
var mappings = new List<BulkInsertMapItem>();
// Add invalid mappings
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnBit), nameof(BulkOperationIdentityTable.ColumnBit)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime), nameof(BulkOperationIdentityTable.ColumnDateTime)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDateTime2), nameof(BulkOperationIdentityTable.ColumnDateTime2)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnDecimal), nameof(BulkOperationIdentityTable.ColumnDecimal)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnFloat), nameof(BulkOperationIdentityTable.ColumnFloat)));
// Switched
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnInt), nameof(BulkOperationIdentityTable.ColumnNVarChar)));
mappings.Add(new BulkInsertMapItem(nameof(BulkOperationIdentityTable.ColumnNVarChar), nameof(BulkOperationIdentityTable.ColumnInt)));
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
using (var table = new DataTable())
{
table.Load(reader);
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdateAsync(ClassMappedNameCache.Get<BulkOperationIdentityTable>(),
table,
mappings: mappings);
// Trigger
var result = bulkUpdateResult.Result;
}
}
}
}
}
[TestMethod, ExpectedException(typeof(AggregateException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateAsyncForTableNameDataTableIfTheTableNameIsNotValid()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
using (var table = new DataTable())
{
table.Load(reader);
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdateAsync("InvalidTable", table);
// Trigger
var result = bulkUpdateResult.Result;
}
}
}
}
}
[TestMethod, ExpectedException(typeof(AggregateException))]
public void ThrowExceptionOnMicrosoftSqlConnectionBulkUpdateAsyncForTableNameDataTableIfTheTableNameIsMissing()
{
// Setup
var tables = Helper.CreateBulkOperationIdentityTables(10);
// Insert the records first
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
connection.InsertAll(tables);
}
// Open the source connection
using (var sourceConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Read the data from source connection
using (var reader = sourceConnection.ExecuteReader("SELECT * FROM [dbo].[BulkOperationIdentityTable];"))
{
using (var table = new DataTable())
{
table.Load(reader);
// Open the destination connection
using (var destinationConnection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act
var bulkUpdateResult = destinationConnection.BulkUpdateAsync("MissingTable",
table);
// Trigger
var result = bulkUpdateResult.Result;
}
}
}
}
}
#endregion
}
}
| 47.842524
| 170
| 0.611492
|
[
"Apache-2.0"
] |
GeeWee/RepoDb
|
RepoDb.Extensions/RepoDb.SqlServer.BulkOperations/RepoDb.SqlServer.BulkOperations.IntegrationTests/Operations/Microsoft.Data.SqlClient/SqlConnection/BulkUpdate.cs
| 96,309
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
using Zem80.Core.IO;
namespace Zem80.Core.Instructions
{
public class OUTI : IMicrocode
{
public ExecutionResult Execute(Processor cpu, InstructionPackage package)
{
Instruction instruction = package.Instruction;
InstructionData data = package.Data;
Flags flags = cpu.Flags.Clone();
Registers r = cpu.Registers;
Port port = cpu.Ports[r.C];
byte output = cpu.Memory.Timed.ReadByteAt(r.HL);
r.WZ = r.BC;
r.B--;
port.SignalWrite();
port.WriteByte(output, true);
r.HL++;
flags.Zero = (r.B == 0);
flags.Subtract = true;
flags.X = (output & 0x08) > 0; // copy bit 3
flags.Y = (output & 0x20) > 0; // copy bit 5
return new ExecutionResult(package, flags);
}
public OUTI()
{
}
}
}
| 26.236842
| 81
| 0.53661
|
[
"MIT"
] |
neilhewitt/Z80_Emulator
|
src/Zem80_Core/Instructions/Microcode/InputOutput/OUTI.cs
| 997
|
C#
|
using System;
using System.Text;
namespace NsqClient.Frames
{
internal class MessageFrame : Frame
{
private const int TIMESTAMP_LENGTH = 8;
private const int ATTEMPTS_LENGTH = 2;
private const int MESSAGEID_LENGTH = 16;
public long Timestamp { get; set; }
public ushort Attempts { get; set; }
public string MessageId { get; set; }
public byte[] MessageBody { get; set; }
public MessageFrame(byte[] payload)
{
if (BitConverter.IsLittleEndian)
{
Array.Reverse(payload, 0, TIMESTAMP_LENGTH);
Array.Reverse(payload, TIMESTAMP_LENGTH, ATTEMPTS_LENGTH);
}
int offset = 0;
this.Timestamp = BitConverter.ToInt64(payload, offset);
offset += TIMESTAMP_LENGTH;
this.Attempts = BitConverter.ToUInt16(payload, offset);
offset += ATTEMPTS_LENGTH;
this.MessageId = Encoding.ASCII.GetString(payload, offset, MESSAGEID_LENGTH);
offset += MESSAGEID_LENGTH;
byte[] body = new byte[payload.Length - offset];
Array.ConstrainedCopy(payload, offset, body, 0, body.Length);
this.MessageBody = body;
}
}
}
| 28.717391
| 89
| 0.57078
|
[
"MIT"
] |
matteocontrini/NsqClient
|
NsqClient/Frames/MessageFrame.cs
| 1,321
|
C#
|
using log4net.Appender.Azure.Language;
using Microsoft.Azure.Cosmos.Table;
using System;
using System.Collections.Generic;
using System.Dynamic;
namespace log4net.Appender.Azure
{
/// <summary>
/// copied from here:
/// http://pascallaurin42.blogspot.de/2013/03/using-azure-table-storage-with-dynamic.html
/// </summary>
public class ElasticTableEntity : DynamicObject, ITableEntity//, ICustomMemberProvider // For LinqPad's Dump
{
public ElasticTableEntity()
{
Properties = new Dictionary<string, EntityProperty>();
}
public IDictionary<string, EntityProperty> Properties { get; private set; }
public object this[string key]
{
get
{
if (!Properties.ContainsKey(key))
Properties.Add(key, GetEntityProperty(key, null));
return Properties[key];
}
set
{
var property = GetEntityProperty(key, value);
if (Properties.ContainsKey(key))
Properties[key] = property;
else
Properties.Add(key, property);
}
}
#region DynamicObject overrides
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = this[binder.Name];
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
this[binder.Name] = value;
return true;
}
#endregion
#region ITableEntity implementation
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public DateTimeOffset Timestamp { get; set; }
public string ETag { get; set; }
public void ReadEntity(IDictionary<string, EntityProperty> properties, OperationContext operationContext)
{
Properties = properties;
}
public IDictionary<string, EntityProperty> WriteEntity(OperationContext operationContext)
{
return Properties;
}
#endregion
private static EntityProperty GetEntityProperty(string key, object value)
{
if (value == null) return new EntityProperty((string)null);
if (value.GetType() == typeof(byte[])) return new EntityProperty((byte[])value);
if (value is bool) return new EntityProperty((bool)value);
if (value is DateTimeOffset) return new EntityProperty((DateTimeOffset)value);
if (value is DateTime) return new EntityProperty((DateTime)value);
if (value is double) return new EntityProperty((double)value);
if (value is Guid) return new EntityProperty((Guid)value);
if (value is int) return new EntityProperty((int)value);
if (value is long) return new EntityProperty((long)value);
if (value is string) return new EntityProperty((string)value);
throw new Exception(string.Format(Resources.ElasticTableEntity_GetEntityProperty_not_supported__0__for__1_,
value.GetType(),
key));
}
}
}
| 27.907216
| 110
| 0.720724
|
[
"MIT"
] |
irongut/log4net.Appender.Azure
|
log4net.Azure/ElasticTableEntity.cs
| 2,707
|
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ZigBeeNet.CodeGenerator.Zcl;
using Attribute = ZigBeeNet.CodeGenerator.Zcl.Attribute;
namespace ZigBeeNet.CodeGenerator
{
public static class ZclProtocolCodeGenerator
{
private const int _lineLen = 120;
private static string _generatedDate;
private static string _outRootPath;
/**
* The main method for running the code generator.
*/
public static void Generate(string[] args = null)
{
_generatedDate = DateTime.UtcNow.ToShortDateString() + " - " + DateTime.UtcNow.ToShortTimeString();
string definitionFilePathZcl = "./Resources/zcl_definition.md";
if (args != null && args.Length > 0)
{
_outRootPath = args[0];
}
Context contextZcl = new Context();
FileInfo definitionFileZcl = new FileInfo(definitionFilePathZcl);
if (!definitionFileZcl.Exists)
{
Console.WriteLine("Definition file does not exist: " + definitionFilePathZcl);
}
else
{
try
{
contextZcl.Lines = new List<string>(File.ReadAllLines(definitionFilePathZcl, Encoding.UTF8));
GenerateZclCode(contextZcl);
}
catch (IOException e)
{
Console.WriteLine("Reading lines from Zcl definition file failed: " + definitionFileZcl.FullName + "\n" + e.ToString());
}
}
}
private static void GenerateZclCode(Context context)
{
ZclProtocolDefinitionParser.ParseProfiles(context);
try
{
GenerateAttributeEnumeration(context);
}
catch (Exception e)
{
Console.WriteLine("Failed to generate attribute enum classes.");
Console.WriteLine(e.ToString());
return;
}
try
{
GenerateFieldEnumeration(context);
}
catch (Exception e)
{
Console.WriteLine("Failed to generate field enum classes.");
Console.WriteLine(e.ToString());
return;
}
try
{
GenerateZclCommandClasses(context);
}
catch (Exception e)
{
Console.WriteLine("Failed to generate zcl command classes.");
Console.WriteLine(e.ToString());
return;
}
try
{
GenerateZclClusterClasses(context);
}
catch (Exception e)
{
Console.WriteLine("Failed to generate cluster classes.");
Console.WriteLine(e.ToString());
return;
}
}
private static void OutputClassDoc(StringBuilder code, string description)
{
code.AppendLine("/**");
code.AppendLine(" * " + description);
code.AppendLine(" *");
code.AppendLine(" * Code is auto-generated. Modifications may be overwritten!");
code.AppendLine(" *");
code.AppendLine(" */");
}
private static void OutputClassGenerated(StringBuilder builder)
{
builder.AppendLine("/* Autogenerated: " + _generatedDate + " */");
}
private static void GenerateZclCommandClasses(Context context)
{
List<Profile> profiles = new List<Profile>(context.Profiles.Values);
foreach (Profile profile in profiles)
{
List<Cluster> clusters = new List<Cluster>(profile.Clusters.Values);
foreach (Cluster cluster in clusters)
{
List<Command> commands = new List<Command>();
commands.AddRange(cluster.Received.Values);
commands.AddRange(cluster.Generated.Values);
foreach (Command command in commands)
{
string packageRoot = "ZigBeeNet.ZCL." + cluster.ClusterType.Replace("_", "").ToUpper();
string className = command.NameUpperCamelCase;
List<Field> fields = new List<Field>(command.Fields.Values);
var code = new StringBuilder();
CodeGeneratorUtil.OutputLicense(code);
code.AppendLine("using System;");
code.AppendLine("using System.Collections.Generic;");
code.AppendLine("using System.Linq;");
code.AppendLine("using System.Text;");
code.AppendLine("using ZigBeeNet.ZCL.Protocol;");
code.AppendLine("using ZigBeeNet.ZCL.Field;");
code.AppendLine("using ZigBeeNet.ZCL.Clusters." + cluster.ClusterName.Replace("/", "").Replace(" ", "").Replace("(", "").Replace(")", "") + ";");
foreach (Field field in fields)
{
string typeName;
if (field.DataTypeClass.StartsWith("List"))
{
typeName = field.DataTypeClass;
typeName = typeName.Substring(typeName.IndexOf("<") + 1);
typeName = typeName.Substring(0, typeName.IndexOf(">"));
}
else
{
typeName = field.DataTypeClass;
}
switch (typeName)
{
case "int":
case "bool":
case "object":
case "long":
case "string":
case "int[]":
continue;
case "IeeeAddress":
//code.AppendLine("");
continue;
case "ZclStatus":
//code.AppendLine("");
continue;
case "ImageUpgradeStatus":
//code.AppendLine("");
continue;
}
//code.AppendLine("");
}
code.AppendLine();
code.AppendLine("/**");
code.AppendLine(" * " + command.CommandLabel + " value object class.");
code.AppendLine(" *");
code.AppendLine(" * Cluster: " + cluster.ClusterName + ". Command is sent"
+ (cluster.Received.ContainsValue(command) ? "TO" : "FROM") + " the server.");
code.AppendLine(" * This command is " + ((cluster.ClusterType.Equals("GENERAL"))
? "a generic command used across the profile."
: "a specific command used for the " + cluster.ClusterName + " cluster."));
if (command.CommandDescription.Count > 0)
{
code.AppendLine(" *");
OutputWithLinebreak(code, "", command.CommandDescription);
}
code.AppendLine(" *");
code.AppendLine(" * Code is auto-generated. Modifications may be overwritten!");
code.AppendLine(" */");
code.AppendLine();
OutputClassGenerated(code);
code.AppendLine("namespace ZigBeeNet.ZCL.Clusters." + cluster.ClusterName.Replace("/", "").Replace(" ", "").Replace("(", "").Replace(")", ""));
code.AppendLine("{");
code.AppendLine(" public class " + className + " : ZclCommand");
code.AppendLine(" {");
foreach (Field field in fields)
{
code.AppendLine(" /**");
code.AppendLine(" * " + field.FieldLabel + " command message field.");
if (field.Description.Count != 0)
{
code.AppendLine(" *");
OutputWithLinebreak(code, " ", field.Description);
}
code.AppendLine(" */");
code.AppendLine(" public " + field.DataTypeClass + " " + field.NameUpperCamelCase + " { get; set; }");
code.AppendLine();
}
code.AppendLine();
code.AppendLine(" /**");
code.AppendLine(" * Default constructor.");
code.AppendLine(" */");
code.AppendLine(" public " + className + "()");
code.AppendLine(" {");
code.AppendLine(" GenericCommand = " + ((cluster.ClusterType.Equals("GENERAL")) ? "true" : "false") + ";");
if (!cluster.ClusterType.Equals("GENERAL"))
{
code.AppendLine(" ClusterId = " + cluster.ClusterId + ";");
}
code.AppendLine(" CommandId = " + command.CommandId + ";");
code.AppendLine(" CommandDirection = ZclCommandDirection."
+ (cluster.Received.ContainsValue(command) ? "CLIENT_TO_SERVER" : "SERVER_TO_CLIENT")
+ ";");
code.AppendLine(" }");
if (fields.Count > 0)
{
code.AppendLine();
code.AppendLine(" public override void Serialize(ZclFieldSerializer serializer)");
code.AppendLine(" {");
foreach (Field field in fields)
{
// Rules...
// if listSizer == null, then just output the field
// if listSizer != null and contains && then check the param bit
if (field.ListSizer != null)
{
if (field.ListSizer.Equals("statusResponse"))
{
// Special case where a ZclStatus may be sent, or, a list of results.
// This checks for a single response
code.AppendLine(" if (Status == ZclStatus.SUCCESS)");
code.AppendLine(" {");
code.AppendLine(" serializer.Serialize(Status, ZclDataType.Get(DataType.ZCL_STATUS));");
code.AppendLine(" return;");
code.AppendLine(" }");
}
else if (field.ConditionOperator != null)
{
if (field.ConditionOperator == "&&")
{
code.AppendLine(" if ((" + field.ListSizer + " & " + field.Condition + ") != 0) {");
}
else
{
code.AppendLine(" if (" + field.ListSizer + " " + field.ConditionOperator + " " + field.Condition + ")");
code.AppendLine(" {");
}
code.AppendLine(" serializer.Serialize(" + field.NameUpperCamelCase + ", ZclDataType.Get(DataType." + field.DataType + "));");
code.AppendLine(" }");
}
else
{
code.AppendLine(" for (int cnt = 0; cnt < " + field.NameUpperCamelCase + ".Count; cnt++) {");
code.AppendLine(" serializer.Serialize(" + field.NameUpperCamelCase + ".Get(cnt), ZclDataType.Get(DataType." + field.DataType + "));");
code.AppendLine(" }");
}
}
else
{
code.AppendLine(" serializer.Serialize(" + field.NameUpperCamelCase + ", ZclDataType.Get(DataType." + field.DataType + "));");
}
}
code.AppendLine(" }");
code.AppendLine();
code.AppendLine(" public override void Deserialize(ZclFieldDeserializer deserializer)");
code.AppendLine(" {");
foreach (Field field in fields)
{
if (field.ListSizer != null)
{
if (field.ListSizer.Equals("statusResponse"))
{
// Special case where a ZclStatus may be sent, or, a list of results.
// This checks for a single response
code.AppendLine(" if (deserializer.RemainingLength == 1)");
code.AppendLine(" {");
code.AppendLine(" Status = deserializer.Deserialize<ZclStatus>(ZclDataType.Get(DataType.ZCL_STATUS));");
code.AppendLine(" return;");
code.AppendLine(" }");
}
else if (field.ConditionOperator != null)
{
if (field.ConditionOperator == "&&")
{
code.AppendLine(" if ((" + field.ListSizer + " & " + field.Condition + ") != 0)");
code.AppendLine(" {");
}
else
{
code.AppendLine(" if (" + field.ListSizer + " " + field.ConditionOperator + " " + field.Condition + ")");
code.AppendLine(" {");
}
code.AppendLine(" " + field.NameUpperCamelCase + " = deserializer.Deserialize<" + field.DataTypeClass + ">(ZclDataType.Get(DataType." + field.DataType + "));");
code.AppendLine(" }");
}
else
{
code.AppendLine(" for (int cnt = 0; cnt < " + field.NameLowerCamelCase + ".Count; cnt++)");
code.AppendLine(" {");
code.AppendLine(" " + field.NameUpperCamelCase + " = deserializer.Deserialize<" + field.DataTypeClass + ">(ZclDataType.Get(DataType." + field.DataType + "));");
code.AppendLine(" }");
}
}
else
{
code.AppendLine(" " + field.NameUpperCamelCase + " = deserializer.Deserialize<" + field.DataTypeClass + ">(ZclDataType.Get(DataType." + field.DataType + "));");
}
}
code.AppendLine(" }");
}
int fieldLen = 0;
foreach (Field field in fields)
{
fieldLen += field.NameLowerCamelCase.Length + 20;
}
code.AppendLine();
code.AppendLine(" public override string ToString()");
code.AppendLine(" {");
code.AppendLine(" var builder = new StringBuilder();");
code.AppendLine();
code.AppendLine(" builder.Append(\"" + className + " [\");");
code.AppendLine(" builder.Append(base.ToString());");
foreach (Field field in fields)
{
code.AppendLine(" builder.Append(\", " + field.NameUpperCamelCase + "=\");");
code.AppendLine(" builder.Append(" + field.NameUpperCamelCase + ");");
}
code.AppendLine(" builder.Append(\']\');");
code.AppendLine();
code.AppendLine(" return builder.ToString();");
code.AppendLine(" }");
code.AppendLine();
code.AppendLine(" }");
code.AppendLine("}");
Console.WriteLine(code.ToString());
var outputPath = Path.Combine(_outRootPath, cluster.ClusterName.Replace("/", "").Replace(" ", "").Replace("(","").Replace(")", ""));
var commmandClassFile = command.NameUpperCamelCase + ".cs";
var commandFullPath = Path.Combine(outputPath, commmandClassFile.Replace(" ", ""));
Directory.CreateDirectory(outputPath);
File.Delete(commandFullPath);
File.WriteAllText(commandFullPath, code.ToString(), Encoding.UTF8);
}
}
}
}
private static void OutputWithLinebreak(StringBuilder builder, string indent, List<string> lines)
{
foreach (string line in lines)
{
string[] words = line.Split(" ");
if (words.Length == 0)
{
return;
}
builder.Append(indent + " *");
int len = 2;
foreach (string word in words)
{
if (len + word.Length > _lineLen)
{
builder.AppendLine();
builder.Append(indent + " *");
len = 2;
}
builder.Append(" ");
builder.Append(word);
len += word.Length;
}
if (len != 0)
{
Console.WriteLine();
}
}
}
private static void GenerateZclClusterClasses(Context context)
{
LinkedList<Profile> profiles = new LinkedList<Profile>(context.Profiles.Values);
foreach (Profile profile in profiles)
{
List<Cluster> clusters = new List<Cluster>(profile.Clusters.Values);
foreach (Cluster cluster in clusters)
{
string className = "Zcl" + cluster.NameUpperCamelCase + "Cluster";
List<Command> commands = new List<Command>();
commands.AddRange(cluster.Received.Values);
commands.AddRange(cluster.Generated.Values);
var code = new StringBuilder();
CodeGeneratorUtil.OutputLicense(code);
code.AppendLine();
code.AppendLine("using System;");
code.AppendLine("using System.Collections.Concurrent;");
code.AppendLine("using System.Collections.Generic;");
code.AppendLine("using System.Linq;");
code.AppendLine("using System.Text;");
code.AppendLine("using System.Threading;");
code.AppendLine("using System.Threading.Tasks;");
code.AppendLine("using ZigBeeNet.DAO;");
code.AppendLine("using ZigBeeNet.ZCL.Protocol;");
code.AppendLine("using ZigBeeNet.ZCL.Field;");
if (commands.Count > 0)
code.AppendLine("using ZigBeeNet.ZCL.Clusters." + cluster.ClusterName.Replace("/", "").Replace(" ", "").Replace("(", "").Replace(")", "") + ";");
List<string> imports = new List<string>();
bool useList = false;
foreach (Command command in commands)
{
List<Field> fields = new List<Field>(command.Fields.Values);
Console.WriteLine("Checking command " + command.CommandLabel);
foreach (Field field in fields)
{
Console.WriteLine("Checking " + field.DataTypeClass);
string typeName;
if (field.DataTypeClass.StartsWith("List"))
{
useList = true;
typeName = field.DataTypeClass;
typeName = typeName.Substring(typeName.IndexOf("<") + 1);
typeName = typeName.Substring(0, typeName.IndexOf(">"));
}
else
{
typeName = field.DataTypeClass;
}
switch (typeName)
{
case "int":
case "bool":
case "object":
case "long":
case "string":
case "int[]":
continue;
case "IeeeAddress":
//imports.Add(packageRootPrefix + "." + typeName);
Console.WriteLine("Adding " + typeName);
continue;
case "ZclStatus":
//imports.add(packageRootPrefix + packageZcl + ".ZclStatus");
continue;
case "ImageUpgradeStatus":
//imports.add(packageRootPrefix + packageZclField + ".ImageUpgradeStatus");
continue;
}
//imports.Add(packageRootPrefix + packageName + "." + typeName);
}
}
if (useList)
{
// imports.add(packageRootPrefix + packageZclField);
}
bool addAttributeTypes = false;
bool readAttributes = false;
bool writeAttributes = false;
foreach (Attribute attribute in cluster.Attributes.Values)
{
if (attribute.AttributeAccess.ToLower().Contains("write"))
{
addAttributeTypes = true;
writeAttributes = true;
}
if (attribute.AttributeAccess.ToLower().Contains("read"))
{
readAttributes = true;
}
if ("Calendar".Equals(attribute.DataTypeClass))
{
//imports.add("");
}
if ("IeeeAddress".Equals(attribute.DataTypeClass))
{
//imports.add("c");
}
if ("ImageUpgradeStatus".Equals(attribute.DataTypeClass))
{
//imports.add(packageRootPrefix + packageZclField + ".ImageUpgradeStatus");
}
}
if (addAttributeTypes)
{
//imports.add("");
}
//imports.Add(packageRoot + _packageZcl + ".ZclCluster");
if (cluster.Attributes.Count != 0)
{
//imports.Add(packageRoot + _packageZclProtocol + ".ZclDataType");
}
if (commands.Count != 0)
{
//imports.Add(packageRoot + _packageZcl + ".ZclCommand");
}
// imports.Add(packageRoot + packageZcl + ".ZclCommandMessage");
// imports.Add(packageRoot + ".ZigBeeDestination");
// imports.Add(packageRoot + ".ZigBeeEndpoint");
if (cluster.Attributes.Count != 0 || commands.Count != 0)
{
//imports.Add(packageRoot + ".CommandResult");
}
//imports.Add(packageRoot + _packageZcl + ".ZclAttribute");
if (cluster.Attributes.Count != 0 || commands.Count != 0)
{
//imports.Add("");
}
// importsAadd("");
foreach (Attribute attribute in cluster.Attributes.Values)
{
if (attribute.AttributeAccess.ToLower().Contains("read"))
{
// imports.Add("");
}
}
foreach (Command command in commands)
{
//imports.Add(GetZclClusterCommandPackage(packageRoot, cluster));
}
if (cluster.Attributes.Count != 0)
{
//imports.Add(packageRoot + _packageZclProtocol + ".ZclClusterType");
}
List<string> importList = new List<string>();
importList.AddRange(imports);
importList = importList.Distinct().ToList();
importList.Sort();
// NOT USED
foreach (string importClass in importList)
{
code.AppendLine("using " + importClass + ";");
}
code.AppendLine();
code.AppendLine("/**");
code.AppendLine(" *" + cluster.ClusterName + "cluster implementation (Cluster ID 0x" + cluster.ClusterId.ToString("X4") + ").");
if (cluster.ClusterDescription.Count > 0)
{
code.AppendLine(" *");
}
OutputWithLinebreak(code, "", cluster.ClusterDescription);
code.AppendLine(" *");
code.AppendLine(" * Code is auto-generated. Modifications may be overwritten!");
code.AppendLine(" */");
OutputClassGenerated(code);
code.AppendLine("namespace ZigBeeNet.ZCL.Clusters");
code.AppendLine("{");
code.AppendLine(" public class " + className + " : ZclCluster");
code.AppendLine(" {");
code.AppendLine(" /**");
code.AppendLine(" * The ZigBee Cluster Library Cluster ID");
code.AppendLine(" */");
code.AppendLine(" public static ushort CLUSTER_ID = 0x" + cluster.ClusterId.ToString("X4") + ";");
code.AppendLine();
code.AppendLine(" /**");
code.AppendLine(" * The ZigBee Cluster Library Cluster Name");
code.AppendLine(" */");
code.AppendLine(" public static string CLUSTER_NAME = \"" + cluster.ClusterName + "\";");
code.AppendLine();
if (cluster.Attributes.Count != 0)
{
code.AppendLine(" /* Attribute constants */");
foreach (Attribute attribute in cluster.Attributes.Values)
{
code.AppendLine(" /**");
OutputWithLinebreak(code, " ", attribute.AttributeDescription);
code.AppendLine(" */");
code.AppendLine(" public static ushort " + attribute.EnumName + " = 0x" + attribute.AttributeId.ToString("X4") + ";");
code.AppendLine();
}
code.AppendLine();
}
code.AppendLine(" // Attribute initialisation");
code.AppendLine(" protected override Dictionary<ushort, ZclAttribute> InitializeAttributes()");
code.AppendLine(" {");
code.AppendLine(" Dictionary<ushort, ZclAttribute> attributeMap = new Dictionary<ushort, ZclAttribute>(" + cluster.Attributes.Count + ");");
if (cluster.Attributes.Count != 0)
{
code.AppendLine();
code.AppendLine(" ZclClusterType " + cluster.NameLowerCamelCase.Replace("/", "").Replace(" ", "").Replace("(", "").Replace(")", "") + " = ZclClusterType.GetValueById(ClusterType." + cluster.ClusterType + ");");
code.AppendLine();
foreach (Attribute attribute in cluster.Attributes.Values)
{
code.AppendLine(" attributeMap.Add(" + attribute.EnumName
+ ", new ZclAttribute(" + cluster.NameLowerCamelCase.Replace("/", "").Replace(" ", "").Replace("(", "").Replace(")", "") + ", " + attribute.EnumName
+ ", \"" + attribute.AttributeLabel + "\", " + "ZclDataType.Get(DataType." + attribute.DataType + ")"
+ ", " + "mandatory".Equals(attribute.AttributeImplementation.ToLower()).ToString().ToLower() + ", "
+ attribute.AttributeAccess.ToLower().Contains("read").ToString().ToLower() + ", "
+ attribute.AttributeAccess.ToLower().Contains("write").ToString().ToLower() + ", "
+ "mandatory".Equals(attribute.AttributeReporting.ToLower()).ToString().ToLower() + "));");
}
}
code.AppendLine();
code.AppendLine(" return attributeMap;");
code.AppendLine(" }");
code.AppendLine();
code.AppendLine(" /**");
code.AppendLine(" * Default constructor to create a " + cluster.ClusterName + " cluster.");
code.AppendLine(" *");
code.AppendLine(" * @param zigbeeEndpoint the {@link ZigBeeEndpoint}");
code.AppendLine(" */");
code.AppendLine(" public " + className + "(ZigBeeEndpoint zigbeeEndpoint)");
code.AppendLine(" : base(zigbeeEndpoint, CLUSTER_ID, CLUSTER_NAME)");
code.AppendLine(" {");
code.AppendLine(" }");
code.AppendLine();
foreach (Attribute attribute in cluster.Attributes.Values)
{
DataTypeMap zclDataType = ZclDataType.GetDataTypeMapping()[attribute.DataType];
if (attribute.AttributeAccess.ToLower().Contains("write"))
{
OutputAttributeJavaDoc(code, "Set", attribute, zclDataType);
code.AppendLine(" public Task<CommandResult> Set" + attribute.NameUpperCamelCase.Replace("_", "") + "(object value)");
code.AppendLine(" {");
code.AppendLine(" return Write(_attributes[" + attribute.EnumName + "], value);");
code.AppendLine(" }");
code.AppendLine();
}
if (attribute.AttributeAccess.ToLower().Contains("read"))
{
OutputAttributeJavaDoc(code, "Get", attribute, zclDataType);
code.AppendLine(" public Task<CommandResult> Get" + attribute.NameUpperCamelCase.Replace("_", "") + "Async()");
code.AppendLine(" {");
code.AppendLine(" return Read(_attributes[" + attribute.EnumName + "]);");
code.AppendLine(" }");
OutputAttributeJavaDoc(code, "Synchronously Get", attribute, zclDataType);
code.AppendLine(" public " + attribute.DataTypeClass + " Get" + attribute.NameUpperCamelCase.Replace("_", "") + "(long refreshPeriod)");
code.AppendLine(" {");
code.AppendLine(" if (_attributes[" + attribute.EnumName + "].IsLastValueCurrent(refreshPeriod))");
code.AppendLine(" {");
code.AppendLine(" return (" + attribute.DataTypeClass + ")_attributes[" + attribute.EnumName + "].LastValue;");
code.AppendLine(" }");
code.AppendLine();
code.AppendLine(" return (" + attribute.DataTypeClass + ")ReadSync(_attributes[" + attribute.EnumName + "]);");
code.AppendLine(" }");
code.AppendLine();
}
if (attribute.AttributeAccess.ToLower().Contains("read") && attribute.AttributeReporting.ToLower().Equals("mandatory"))
{
OutputAttributeJavaDoc(code, "Set reporting for", attribute, zclDataType);
if (zclDataType.Analogue)
{
code.AppendLine(" public Task<CommandResult> Set" + attribute.NameUpperCamelCase + "Reporting(ushort minInterval, ushort maxInterval, object reportableChange)");
code.AppendLine(" {");
code.AppendLine(" return SetReporting(_attributes[" + attribute.EnumName + "], minInterval, maxInterval, reportableChange);");
}
else
{
code.AppendLine(" public Task<CommandResult> Set" + attribute.NameUpperCamelCase + "Reporting(ushort minInterval, ushort maxInterval)");
code.AppendLine(" {");
code.AppendLine(" return SetReporting(_attributes[" + attribute.EnumName + "], minInterval, maxInterval);");
}
code.AppendLine(" }");
code.AppendLine();
}
}
foreach (Command command in commands)
{
code.AppendLine();
code.AppendLine(" /**");
code.AppendLine(" * The " + command.CommandLabel);
if (command.CommandDescription.Count != 0)
{
code.AppendLine(" *");
OutputWithLinebreak(code, " ", command.CommandDescription);
}
code.AppendLine(" *");
List<Field> fields = new List<Field>(command.Fields.Values);
foreach (Field field in fields)
{
code.AppendLine(" * @param " + field.NameLowerCamelCase + " {@link " + field.DataTypeClass + "} " + field.FieldLabel);
}
code.AppendLine(" * @return the Task<CommandResult> command result Task");
code.AppendLine(" */");
code.Append(" public Task<CommandResult> " + command.NameUpperCamelCase + "(");
bool first = true;
foreach (Field field in fields)
{
if (first == false)
{
code.Append(", ");
}
code.Append(field.DataTypeClass + " " + field.NameLowerCamelCase);
first = false;
}
code.AppendLine(")");
code.AppendLine(" {");
code.AppendLine(" " + command.NameUpperCamelCase + " command = new " + command.NameUpperCamelCase + "();");
if (fields.Count != 0)
{
code.AppendLine();
code.AppendLine(" // Set the fields");
}
foreach (Field field in fields)
{
code.AppendLine(" command." + field.NameUpperCamelCase + " = " + field.NameLowerCamelCase + ";");
}
code.AppendLine();
code.AppendLine(" return Send(command);");
code.AppendLine(" }");
}
if (cluster.Received.Count > 0)
{
code.AppendLine();
code.AppendLine(" public override ZclCommand GetCommandFromId(int commandId)");
code.AppendLine(" {");
code.AppendLine(" switch (commandId)");
code.AppendLine(" {");
foreach (Command command in cluster.Received.Values)
{
code.AppendLine(" case " + command.CommandId + ": // " + command.CommandType);
code.AppendLine(" return new " + command.NameUpperCamelCase + "();");
}
code.AppendLine(" default:");
code.AppendLine(" return null;");
code.AppendLine(" }");
code.AppendLine(" }");
}
if (cluster.Generated.Count > 0)
{
code.AppendLine();
code.AppendLine(" public ZclCommand getResponseFromId(int commandId)");
code.AppendLine(" {");
code.AppendLine(" switch (commandId)");
code.AppendLine(" {");
foreach (Command command in cluster.Generated.Values)
{
code.AppendLine(" case " + command.CommandId + ": // " + command.CommandType);
code.AppendLine(" return new " + command.NameUpperCamelCase + "();");
}
code.AppendLine(" default:");
code.AppendLine(" return null;");
code.AppendLine(" }");
code.AppendLine(" }");
}
code.AppendLine(" }");
code.AppendLine("}");
Console.WriteLine(code.ToString());
var commandClassFile = "Zcl" + cluster.NameUpperCamelCase + "Cluster.cs";
var clusterFullPath = Path.Combine(_outRootPath, commandClassFile);
Directory.CreateDirectory(_outRootPath);
File.Delete(clusterFullPath);
File.WriteAllText(clusterFullPath, code.ToString(), Encoding.UTF8);
}
}
}
private static void GenerateAttributeEnumeration(Context context)
{
List<Profile> profiles = new List<Profile>(context.Profiles.Values);
foreach (Profile profile in profiles)
{
List<Cluster> clusters = new List<Cluster>(profile.Clusters.Values);
foreach (Cluster cluster in clusters)
{
if (cluster.Attributes.Count != 0)
{
foreach (Attribute attribute in cluster.Attributes.Values)
{
if (attribute.ValueMap.Count == 0)
{
continue;
}
string packageRoot = "ZigBeeNet.ZCL.Clusters.";
string className = attribute.NameUpperCamelCase;
OutputEnum(packageRoot, className, attribute.ValueMap, cluster.ClusterName, attribute.AttributeLabel);
}
}
}
}
}
private static void GenerateFieldEnumeration(Context context)
{
List<Profile> profiles = new List<Profile>(context.Profiles.Values);
foreach (Profile profile in profiles)
{
List<Cluster> clusters = new List<Cluster>(profile.Clusters.Values);
foreach (Cluster cluster in clusters)
{
List<Command> commands = new List<Command>();
commands.AddRange(cluster.Received.Values);
commands.AddRange(cluster.Generated.Values);
if (commands.Count != 0)
{
foreach (Command command in commands)
{
foreach (Field field in command.Fields.Values)
{
if (field.ValueMap.Count == 0)
{
continue;
}
string packageRoot = "ZigBeeNet.ZCL.Clusters.";
string className = field.NameUpperCamelCase;
OutputEnum(packageRoot, className, field.ValueMap, cluster.ClusterName, field.FieldLabel);
}
}
}
}
}
}
private static void OutputEnum(string packageRoot, string className, SortedDictionary<int, string> valueMap, string parentName, string label)
{
var code = new StringBuilder();
CodeGeneratorUtil.OutputLicense(code);
parentName = parentName.Replace(" ", "").Replace("/", "").Replace(" ", "").Replace("(", "").Replace(")", "");
code.AppendLine();
code.AppendLine("using System;");
code.AppendLine("using System.Collections.Generic;");
code.AppendLine("using System.Text;");
code.AppendLine();
OutputClassDoc(code, "Enumeration of " + parentName + " attribute " + label + " options.");
code.AppendLine();
OutputClassGenerated(code);
code.AppendLine("namespace " + packageRoot + parentName);
code.AppendLine("{");
code.AppendLine(" public enum " + className.Replace("/", "").Replace(" ", "").Replace("(", "").Replace(")", ""));
code.AppendLine(" {");
bool first = true;
foreach (int key in valueMap.Keys)
{
string value = valueMap[key];
if (!first)
{
code.AppendLine(",");
}
first = false;
code.Append(" " + CodeGeneratorUtil.LabelToEnumerationValue(value) + " = 0x" + key.ToString("X4"));
}
code.AppendLine();
code.AppendLine(" }");
code.AppendLine("}");
var outputPath = Path.Combine(_outRootPath, parentName);
var enumFile = className + ".cs";
var enumFileFullPath = Path.Combine(outputPath, enumFile.Replace(" ", ""));
Directory.CreateDirectory(outputPath);
File.Delete(enumFileFullPath);
File.WriteAllText(enumFileFullPath, code.ToString(), Encoding.UTF8);
}
private static void OutputAttributeJavaDoc(StringBuilder builder, string type, Attribute attribute, DataTypeMap zclDataType)
{
//Console.WriteLine();
//Console.WriteLine(" /**");
//Console.WriteLine(" * " + type + " the <i>" + attribute.attributeLabel + "</i> attribute [attribute ID <b>"
// + attribute.attributeId + "</b>].");
//if (attribute.attributeDescription.size() != 0)
//{
// Console.WriteLine(" * <p>");
// outputWithLinebreak(out, " ", attribute.attributeDescription);
//}
//if ("Synchronously get".equals(type))
//{
// Console.WriteLine(" * <p>");
// Console.WriteLine(" * This method can return cached data if the attribute has already been received.");
// Console.WriteLine(
// " * The parameter <i>refreshPeriod</i> is used to control this. If the attribute has been received");
// Console.WriteLine(
// " * within <i>refreshPeriod</i> milliseconds, then the method will immediately return the last value");
// Console.WriteLine(
// " * received. If <i>refreshPeriod</i> is set to 0, then the attribute will always be updated.");
// Console.WriteLine(" * <p>");
// Console.WriteLine(
// " * This method will block until the response is received or a timeout occurs unless the current value is returned.");
//}
//Console.WriteLine(" * <p>");
//Console.WriteLine(" * The attribute is of type {@link " + attribute.dataTypeClass + "}.");
//Console.WriteLine(" * <p>");
//Console.WriteLine(" * The implementation of this attribute by a device is "
// + attribute.attributeImplementation.toUpperCase());
//Console.WriteLine(" *");
//if ("Set reporting for".equals(type))
//{
// Console.WriteLine(" * @param minInterval {@link int} minimum reporting period");
// Console.WriteLine(" * @param maxInterval {@link int} maximum reporting period");
// if (zclDataType.analogue)
// {
// Console.WriteLine(" * @param reportableChange {@link Object} delta required to trigger report");
// }
//}
//else if ("Set".equals(type))
//{
// Console.WriteLine(" * @param " + attribute.nameLowerCamelCase + " the {@link " + attribute.dataTypeClass
// + "} attribute value to be set");
//}
//if ("Synchronously get".equals(type))
//{
// Console.WriteLine(
// " * @param refreshPeriod the maximum age of the data (in milliseconds) before an update is needed");
// Console.WriteLine(" * @return the {@link " + attribute.dataTypeClass + "} attribute value, or null on error");
//}
//else
//{
// Console.WriteLine(" * @return the {@link Future<CommandResult>} command result future");
//}
//Console.WriteLine(" */");
}
//private static string getFieldType(Field field)
//{
// if (field.listSizer != null)
// {
// return "List<" + field.dataTypeClass + ">";
// }
// else
// {
// return field.dataTypeClass;
// }
//}
}
}
| 48.04507
| 244
| 0.414087
|
[
"MIT"
] |
lehn85/ZigbeeNet
|
src/ZigBeeNet.CodeGenerator/ZclProtocolCodeGenerator.cs
| 51,170
|
C#
|
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;
using ZendeskApi.Client.Exceptions;
using ZendeskApi.Client.Models;
using ZendeskApi.Client.Resources;
using ZendeskApi.Client.Tests.ResourcesSampleSites;
#pragma warning disable 618
namespace ZendeskApi.Client.Tests.Resources
{
public class RequestsResourceTests
{
private readonly IZendeskApiClient _client;
private readonly RequestsResource _resource;
public RequestsResourceTests()
{
_client = new DisposableZendeskApiClient<Request>((resource) => new RequestsResourceSampleSite(resource));
_resource = new RequestsResource(_client, NullLogger.Instance);
}
[Fact]
public async Task GetAllAsync_WhenCalled_ShouldGetAll()
{
var results = await _resource.GetAllAsync();
Assert.Equal(100, results.Count);
for (var i = 1; i <= 100; i++)
{
var item = results.ElementAt(i - 1);
Assert.Equal(i, item.Id);
Assert.Equal($"subject.{i}", item.Subject);
Assert.Equal($"description.{i}", item.Description);
}
}
[Fact]
public async Task GetAllAsync_WhenCalledWithOffsetPagination_ShouldGetAll()
{
var results = await _resource.GetAllAsync(new PagerParameters
{
Page = 2,
PageSize = 1
});
var item = results.First();
Assert.Equal(2, item.Id);
Assert.Equal("subject.2", item.Subject);
Assert.Equal("description.2", item.Description);
}
[Fact]
public async Task GetAllAsync_WhenServiceUnavailable_ShouldThrow()
{
await Assert.ThrowsAsync<ZendeskRequestException>(async () => await _resource.GetAllAsync(new PagerParameters
{
Page = int.MaxValue,
PageSize = int.MaxValue
}));
}
[Fact]
public async Task GetAsync_WhenCalled_ShouldGetOrganization()
{
var item = await _resource.GetAsync(1);
Assert.Equal(1, item.Id);
Assert.Equal("subject.1", item.Subject);
Assert.Equal("description.1", item.Description);
}
[Fact]
public async Task GetAsync_WhenNotFound_ShouldReturnNull()
{
var results = await _resource.GetAsync(int.MaxValue);
Assert.Null(results);
}
[Fact]
public async Task GetAsync_WhenServiceUnavailable_ShouldThrow()
{
await Assert.ThrowsAsync<ZendeskRequestException>(async () => await _resource.GetAsync(int.MinValue));
}
[Fact]
public async Task GetAllComments_WhenCalled_ShouldGetAll()
{
var results = await _resource.GetAllComments(1);
Assert.Equal(100, results.Count);
for (var i = 1; i <= 100; i++)
{
var item = results.ElementAt(i - 1);
Assert.Equal(i, item.Id);
Assert.Equal($"body.{i}", item.Body);
}
}
[Fact]
public async Task GetAllComments_WhenCalledWithOffsetPagination_ShouldGetAll()
{
var results = await _resource.GetAllComments(1, new PagerParameters
{
Page = 2,
PageSize = 1
});
var item = results.First();
Assert.Equal(2, item.Id);
Assert.Equal("body.2", item.Body);
}
[Fact]
public async Task GetAllComments_WhenServiceUnavailable_ShouldThrow()
{
await Assert.ThrowsAsync<ZendeskRequestException>(async () => await _resource.GetAllComments(1, new PagerParameters
{
Page = int.MaxValue,
PageSize = int.MaxValue
}));
}
[Fact]
public async Task GetTicketCommentAsync_WhenCalled_ShouldGetOrganization()
{
var item = await _resource.GetTicketCommentAsync(1, 1);
Assert.Equal(1, item.Id);
Assert.Equal("body.1", item.Body);
}
[Fact]
public async Task GetTicketCommentAsync_WhenNotFound_ShouldReturnNull()
{
var results = await _resource.GetTicketCommentAsync(int.MaxValue, int.MaxValue);
Assert.Null(results);
}
[Fact]
public async Task GetTicketCommentAsync_WhenServiceUnavailable_ShouldThrow()
{
await Assert.ThrowsAsync<ZendeskRequestException>(async () => await _resource.GetTicketCommentAsync(int.MinValue, int.MinValue));
}
[Fact]
public async Task CreateAsync_WhenCalled_ShouldCreate()
{
var item = await _resource.CreateAsync(new Request
{
Id = 101,
Subject = "subject.101",
Description = "description.101"
});
Assert.Equal(101, item.Id);
Assert.Equal("subject.101", item.Subject);
Assert.Equal("description.101", item.Description);
}
[Fact]
public async Task CreateAsync_WhenUnexpectedHttpCode_ShouldThrow()
{
await Assert.ThrowsAsync<ZendeskRequestException>(async () => await _resource.CreateAsync(new Request
{
Id = int.MinValue
}));
}
[Fact]
public async Task UpdateAsync_WhenCalled_ShouldUpdate()
{
var item = await _resource.UpdateAsync(new Request
{
Id = 1,
Subject = "subject.1.new",
Description = "description.1.new"
});
Assert.Equal(1, item.Id);
Assert.Equal("subject.1.new", item.Subject);
Assert.Equal("description.1.new", item.Description);
}
[Fact]
public async Task UpdateAsync_WhenNotFound_ShouldReturnNull()
{
var org = await _resource.UpdateAsync(new Request
{
Id = int.MaxValue
});
Assert.Null(org);
}
[Fact]
public async Task UpdateAsync_WhenUnexpectedHttpCode_ShouldThrow()
{
await Assert.ThrowsAsync<ZendeskRequestException>(async () => await _resource.UpdateAsync(new Request
{
Id = int.MinValue
}));
}
}
}
| 30.534884
| 141
| 0.56527
|
[
"Apache-2.0"
] |
cserkaran/ZendeskApiClient
|
test/ZendeskApi.Client.Tests/Resources/RequestsResourceTests.cs
| 6,565
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DemonAsPrestige")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DemonAsPrestige")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7f9911a9-5209-420f-827d-de8f6178300b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.783784
| 84
| 0.748927
|
[
"MIT"
] |
RealityMachina/DemonAsPrestige
|
DemonAsPrestige/Properties/AssemblyInfo.cs
| 1,401
|
C#
|
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v4/enums/feed_status.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Ads.GoogleAds.V4.Enums {
/// <summary>Holder for reflection information generated from google/ads/googleads/v4/enums/feed_status.proto</summary>
public static partial class FeedStatusReflection {
#region Descriptor
/// <summary>File descriptor for google/ads/googleads/v4/enums/feed_status.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static FeedStatusReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ci9nb29nbGUvYWRzL2dvb2dsZWFkcy92NC9lbnVtcy9mZWVkX3N0YXR1cy5w",
"cm90bxIdZ29vZ2xlLmFkcy5nb29nbGVhZHMudjQuZW51bXMaHGdvb2dsZS9h",
"cGkvYW5ub3RhdGlvbnMucHJvdG8iVgoORmVlZFN0YXR1c0VudW0iRAoKRmVl",
"ZFN0YXR1cxIPCgtVTlNQRUNJRklFRBAAEgsKB1VOS05PV04QARILCgdFTkFC",
"TEVEEAISCwoHUkVNT1ZFRBADQuQBCiFjb20uZ29vZ2xlLmFkcy5nb29nbGVh",
"ZHMudjQuZW51bXNCD0ZlZWRTdGF0dXNQcm90b1ABWkJnb29nbGUuZ29sYW5n",
"Lm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2Fkcy9nb29nbGVhZHMvdjQvZW51",
"bXM7ZW51bXOiAgNHQUGqAh1Hb29nbGUuQWRzLkdvb2dsZUFkcy5WNC5FbnVt",
"c8oCHUdvb2dsZVxBZHNcR29vZ2xlQWRzXFY0XEVudW1z6gIhR29vZ2xlOjpB",
"ZHM6Okdvb2dsZUFkczo6VjQ6OkVudW1zYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V4.Enums.FeedStatusEnum), global::Google.Ads.GoogleAds.V4.Enums.FeedStatusEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V4.Enums.FeedStatusEnum.Types.FeedStatus) }, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Container for enum describing possible statuses of a feed.
/// </summary>
public sealed partial class FeedStatusEnum : pb::IMessage<FeedStatusEnum>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<FeedStatusEnum> _parser = new pb::MessageParser<FeedStatusEnum>(() => new FeedStatusEnum());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<FeedStatusEnum> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Ads.GoogleAds.V4.Enums.FeedStatusReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FeedStatusEnum() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FeedStatusEnum(FeedStatusEnum other) : this() {
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FeedStatusEnum Clone() {
return new FeedStatusEnum(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as FeedStatusEnum);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(FeedStatusEnum other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(FeedStatusEnum other) {
if (other == null) {
return;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the FeedStatusEnum message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Possible statuses of a feed.
/// </summary>
public enum FeedStatus {
/// <summary>
/// Not specified.
/// </summary>
[pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// Used for return value only. Represents value unknown in this version.
/// </summary>
[pbr::OriginalName("UNKNOWN")] Unknown = 1,
/// <summary>
/// Feed is enabled.
/// </summary>
[pbr::OriginalName("ENABLED")] Enabled = 2,
/// <summary>
/// Feed has been removed.
/// </summary>
[pbr::OriginalName("REMOVED")] Removed = 3,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| 35.25
| 276
| 0.688201
|
[
"Apache-2.0"
] |
GraphikaPS/google-ads-dotnet
|
src/V4/Types/FeedStatus.cs
| 7,755
|
C#
|
// <auto-generated />
using System;
using Groundforce.Services.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Groundforce.Services.Data.Migrations
{
[DbContext(typeof(AppDbContext))]
partial class AppDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.8");
modelBuilder.Entity("Groundforce.Services.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<int>("AccessFailedCount")
.HasColumnType("INTEGER");
b.Property<string>("AvatarUrl")
.HasColumnType("TEXT");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("DOB")
.IsRequired()
.HasColumnType("TEXT")
.HasMaxLength(10);
b.Property<string>("Email")
.HasColumnType("TEXT")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("INTEGER");
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("TEXT")
.HasMaxLength(50);
b.Property<string>("Gender")
.HasColumnType("TEXT")
.HasMaxLength(1);
b.Property<bool>("IsActive")
.HasColumnType("INTEGER");
b.Property<bool>("IsVerified")
.HasColumnType("INTEGER");
b.Property<string>("LastName")
.IsRequired()
.HasColumnType("TEXT")
.HasMaxLength(50);
b.Property<bool>("LockoutEnabled")
.HasColumnType("INTEGER");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("TEXT");
b.Property<string>("NormalizedEmail")
.HasColumnType("TEXT")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("TEXT")
.HasMaxLength(256);
b.Property<string>("PasswordHash")
.HasColumnType("TEXT");
b.Property<string>("PhoneNumber")
.HasColumnType("TEXT");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("INTEGER");
b.Property<string>("PublicId")
.HasColumnType("TEXT");
b.Property<string>("SecurityStamp")
.HasColumnType("TEXT");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("INTEGER");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.Property<string>("UserName")
.HasColumnType("TEXT")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Groundforce.Services.Models.BuildingType", b =>
{
b.Property<string>("TypeId")
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("TypeName")
.IsRequired()
.HasColumnType("TEXT")
.HasMaxLength(35);
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("TypeId");
b.ToTable("BuildingTypes");
});
modelBuilder.Entity("Groundforce.Services.Models.EmailVerification", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<string>("EmailAddress")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("IsVerified")
.HasColumnType("INTEGER");
b.Property<string>("VerificationCode")
.IsRequired()
.HasColumnType("TEXT")
.HasMaxLength(4);
b.HasKey("Id");
b.ToTable("EmailVerifications");
});
modelBuilder.Entity("Groundforce.Services.Models.FieldAgent", b =>
{
b.Property<string>("ApplicationUserId")
.HasColumnType("TEXT");
b.Property<string>("AccountName")
.HasColumnType("TEXT")
.HasMaxLength(100);
b.Property<string>("AccountNumber")
.HasColumnType("TEXT")
.HasMaxLength(10);
b.Property<string>("AdditionalPhoneNumber")
.HasColumnType("TEXT")
.HasMaxLength(14);
b.Property<string>("BankName")
.HasColumnType("TEXT")
.HasMaxLength(100);
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<bool>("IsLocationVerified")
.HasColumnType("INTEGER");
b.Property<string>("LGA")
.IsRequired()
.HasColumnType("TEXT")
.HasMaxLength(150);
b.Property<string>("Latitude")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Longitude")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ResidentialAddress")
.HasColumnType("TEXT")
.HasMaxLength(200);
b.Property<string>("State")
.IsRequired()
.HasColumnType("TEXT")
.HasMaxLength(150);
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.Property<string>("ZipCode")
.IsRequired()
.HasColumnType("TEXT")
.HasMaxLength(10);
b.HasKey("ApplicationUserId");
b.ToTable("FieldAgents");
});
modelBuilder.Entity("Groundforce.Services.Models.Mission", b =>
{
b.Property<string>("MissionId")
.HasColumnType("TEXT");
b.Property<string>("AddedBy")
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("FieldAgentId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<string>("VerificationItemId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("VerificationStatus")
.HasColumnType("TEXT");
b.HasKey("MissionId");
b.HasIndex("FieldAgentId");
b.HasIndex("VerificationItemId")
.IsUnique();
b.ToTable("Missions");
});
modelBuilder.Entity("Groundforce.Services.Models.MissionVerified", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<bool>("AddressExists")
.HasColumnType("INTEGER");
b.Property<string>("BuildingColor")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("BuildingTypeId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("BusStop")
.IsRequired()
.HasColumnType("TEXT")
.HasMaxLength(150);
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("Landmark")
.IsRequired()
.HasColumnType("TEXT")
.HasMaxLength(150);
b.Property<string>("Latitude")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Longitude")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("MissionId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("TypeOfStructure")
.IsRequired()
.HasColumnType("TEXT")
.HasMaxLength(35);
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("BuildingTypeId");
b.HasIndex("MissionId")
.IsUnique();
b.ToTable("MissionsVerified");
});
modelBuilder.Entity("Groundforce.Services.Models.Notification", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<string>("AddedBy")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTime>("DateCreated")
.HasColumnType("TEXT");
b.Property<DateTime>("DateUpdated")
.HasColumnType("TEXT");
b.Property<string>("Notifications")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<string>("UpdatedBy")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Notifications");
});
modelBuilder.Entity("Groundforce.Services.Models.NotificationUser", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ApplicationUserId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("NotificationId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("ApplicationUserId");
b.HasIndex("NotificationId");
b.ToTable("NotificationUsers");
});
modelBuilder.Entity("Groundforce.Services.Models.PasswordVerification", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<string>("EmailAddress")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("IsVerified")
.HasColumnType("INTEGER");
b.Property<string>("Token")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("PasswordVerifications");
});
modelBuilder.Entity("Groundforce.Services.Models.Point", b =>
{
b.Property<string>("PointId")
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<decimal>("PointNumber")
.HasColumnType("decimal(18,4)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("PointId");
b.ToTable("Points");
});
modelBuilder.Entity("Groundforce.Services.Models.PointAllocated", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<string>("AddedBy")
.HasColumnType("TEXT");
b.Property<string>("FieldAgentId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("PointId")
.HasColumnType("TEXT");
b.Property<string>("PointsId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("FieldAgentId");
b.HasIndex("PointId");
b.ToTable("PointAllocated");
});
modelBuilder.Entity("Groundforce.Services.Models.QuestionOption", b =>
{
b.Property<string>("QuestionOptionId")
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("Option")
.HasColumnType("TEXT");
b.Property<string>("SurveyQuestionId")
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("QuestionOptionId");
b.HasIndex("SurveyQuestionId");
b.ToTable("QuestionOptions");
});
modelBuilder.Entity("Groundforce.Services.Models.Request", b =>
{
b.Property<string>("RequestId")
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("RequestAttempt")
.HasColumnType("INTEGER");
b.Property<string>("Status")
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("RequestId");
b.ToTable("Request");
});
modelBuilder.Entity("Groundforce.Services.Models.Response", b =>
{
b.Property<string>("ResponseId")
.HasColumnType("TEXT");
b.Property<string>("ApplicationUserId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("QuestionOptionId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("SurveyId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("SurveyQuestionId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("UserSurveyApplicationUserId")
.HasColumnType("TEXT");
b.Property<string>("UserSurveySurveyId")
.HasColumnType("TEXT");
b.HasKey("ResponseId");
b.HasIndex("ApplicationUserId");
b.HasIndex("QuestionOptionId");
b.HasIndex("SurveyId");
b.HasIndex("SurveyQuestionId");
b.HasIndex("UserSurveyApplicationUserId", "UserSurveySurveyId");
b.ToTable("Responses");
});
modelBuilder.Entity("Groundforce.Services.Models.Survey", b =>
{
b.Property<string>("SurveyId")
.HasColumnType("TEXT");
b.Property<string>("AddedBy")
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("SurveyTypeId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Topic")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.HasKey("SurveyId");
b.HasIndex("SurveyTypeId");
b.ToTable("Surveys");
});
modelBuilder.Entity("Groundforce.Services.Models.SurveyQuestion", b =>
{
b.Property<string>("SurveyQuestionId")
.HasColumnType("TEXT");
b.Property<string>("AddedBy")
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("Question")
.HasColumnType("TEXT");
b.Property<string>("SurveyId")
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.HasKey("SurveyQuestionId");
b.HasIndex("SurveyId");
b.ToTable("SurveyQuestions");
});
modelBuilder.Entity("Groundforce.Services.Models.SurveyType", b =>
{
b.Property<string>("SurveyTypeId")
.HasColumnType("TEXT");
b.Property<string>("AddedBy")
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.HasKey("SurveyTypeId");
b.ToTable("SurveyTypes");
});
modelBuilder.Entity("Groundforce.Services.Models.Transaction", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<decimal>("ActualAmount")
.HasColumnType("decimal(18,4)");
b.Property<string>("AddedBy")
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("FieldAgentId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("PaidAmount")
.HasColumnType("INTEGER");
b.Property<DateTime>("PaidAt")
.HasColumnType("TEXT");
b.Property<string>("Reference")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("FieldAgentId");
b.ToTable("Transactions");
});
modelBuilder.Entity("Groundforce.Services.Models.UserSurvey", b =>
{
b.Property<string>("ApplicationUserId")
.HasColumnType("TEXT");
b.Property<string>("SurveyId")
.HasColumnType("TEXT");
b.Property<string>("AddedBy")
.HasColumnType("TEXT");
b.Property<string>("Status")
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.HasKey("ApplicationUserId", "SurveyId");
b.HasIndex("SurveyId");
b.ToTable("UserSurveys");
});
modelBuilder.Entity("Groundforce.Services.Models.VerificationItem", b =>
{
b.Property<string>("ItemId")
.HasColumnType("TEXT");
b.Property<string>("ApplicationUserId")
.IsRequired()
.HasColumnName("AddedBy")
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("TEXT")
.HasMaxLength(250);
b.Property<string>("Title")
.IsRequired()
.HasColumnType("TEXT")
.HasMaxLength(20);
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.HasKey("ItemId");
b.HasIndex("ApplicationUserId");
b.ToTable("VerificationItems");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("TEXT")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClaimType")
.HasColumnType("TEXT");
b.Property<string>("ClaimValue")
.HasColumnType("TEXT");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClaimType")
.HasColumnType("TEXT");
b.Property<string>("ClaimValue")
.HasColumnType("TEXT");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("TEXT");
b.Property<string>("ProviderKey")
.HasColumnType("TEXT");
b.Property<string>("ProviderDisplayName")
.HasColumnType("TEXT");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("TEXT");
b.Property<string>("RoleId")
.HasColumnType("TEXT");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("TEXT");
b.Property<string>("LoginProvider")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<string>("Value")
.HasColumnType("TEXT");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Groundforce.Services.Models.FieldAgent", b =>
{
b.HasOne("Groundforce.Services.Models.ApplicationUser", "ApplicationUser")
.WithOne("FieldAgent")
.HasForeignKey("Groundforce.Services.Models.FieldAgent", "ApplicationUserId")
.OnDelete(DeleteBehavior.NoAction)
.IsRequired();
});
modelBuilder.Entity("Groundforce.Services.Models.Mission", b =>
{
b.HasOne("Groundforce.Services.Models.FieldAgent", "FieldAgent")
.WithMany("Missions")
.HasForeignKey("FieldAgentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Groundforce.Services.Models.VerificationItem", "VerificationItem")
.WithOne("Mission")
.HasForeignKey("Groundforce.Services.Models.Mission", "VerificationItemId")
.OnDelete(DeleteBehavior.NoAction)
.IsRequired();
});
modelBuilder.Entity("Groundforce.Services.Models.MissionVerified", b =>
{
b.HasOne("Groundforce.Services.Models.BuildingType", "BuildingType")
.WithMany("MissionsVerified")
.HasForeignKey("BuildingTypeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Groundforce.Services.Models.Mission", "Mission")
.WithOne("MissionVerified")
.HasForeignKey("Groundforce.Services.Models.MissionVerified", "MissionId")
.OnDelete(DeleteBehavior.NoAction)
.IsRequired();
});
modelBuilder.Entity("Groundforce.Services.Models.NotificationUser", b =>
{
b.HasOne("Groundforce.Services.Models.ApplicationUser", "ApplicationUser")
.WithMany("NotificationUsers")
.HasForeignKey("ApplicationUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Groundforce.Services.Models.Notification", "Notification")
.WithMany()
.HasForeignKey("NotificationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Groundforce.Services.Models.PointAllocated", b =>
{
b.HasOne("Groundforce.Services.Models.FieldAgent", "FieldAgent")
.WithMany("PointsAllocated")
.HasForeignKey("FieldAgentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Groundforce.Services.Models.Point", "Point")
.WithMany("PointsAllocated")
.HasForeignKey("PointId");
});
modelBuilder.Entity("Groundforce.Services.Models.QuestionOption", b =>
{
b.HasOne("Groundforce.Services.Models.SurveyQuestion", "SurveyQuestion")
.WithMany("QuestionOptions")
.HasForeignKey("SurveyQuestionId");
});
modelBuilder.Entity("Groundforce.Services.Models.Response", b =>
{
b.HasOne("Groundforce.Services.Models.ApplicationUser", "ApplicationUser")
.WithMany()
.HasForeignKey("ApplicationUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Groundforce.Services.Models.QuestionOption", "QuestionOption")
.WithMany()
.HasForeignKey("QuestionOptionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Groundforce.Services.Models.Survey", "Survey")
.WithMany()
.HasForeignKey("SurveyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Groundforce.Services.Models.SurveyQuestion", "SurveyQuestion")
.WithMany()
.HasForeignKey("SurveyQuestionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Groundforce.Services.Models.UserSurvey", "UserSurvey")
.WithMany("Responses")
.HasForeignKey("UserSurveyApplicationUserId", "UserSurveySurveyId");
});
modelBuilder.Entity("Groundforce.Services.Models.Survey", b =>
{
b.HasOne("Groundforce.Services.Models.SurveyType", "SurveyType")
.WithMany("Surveys")
.HasForeignKey("SurveyTypeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Groundforce.Services.Models.SurveyQuestion", b =>
{
b.HasOne("Groundforce.Services.Models.Survey", "Survey")
.WithMany("Questions")
.HasForeignKey("SurveyId");
});
modelBuilder.Entity("Groundforce.Services.Models.Transaction", b =>
{
b.HasOne("Groundforce.Services.Models.FieldAgent", "FieldAgent")
.WithMany("Transactions")
.HasForeignKey("FieldAgentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Groundforce.Services.Models.UserSurvey", b =>
{
b.HasOne("Groundforce.Services.Models.ApplicationUser", "ApplicationUser")
.WithMany()
.HasForeignKey("ApplicationUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Groundforce.Services.Models.Survey", "Survey")
.WithMany("UserSurveys")
.HasForeignKey("SurveyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Groundforce.Services.Models.VerificationItem", b =>
{
b.HasOne("Groundforce.Services.Models.ApplicationUser", "ApplicationUser")
.WithMany("VerificationItems")
.HasForeignKey("ApplicationUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Groundforce.Services.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Groundforce.Services.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Groundforce.Services.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Groundforce.Services.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 36.828491
| 102
| 0.418719
|
[
"MIT"
] |
bolamiju/GroundForce-BE
|
Groundforce.Services/Groundforce.Services.Data/Migrations/AppDbContextModelSnapshot.cs
| 39,298
|
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.ML.Core.Data;
using Microsoft.ML.Runtime.CommandLine;
using Microsoft.ML.Runtime.Data;
using Microsoft.ML.Runtime.EntryPoints;
using Microsoft.ML.Runtime.Internal.Utilities;
using Microsoft.ML.Runtime.Numeric;
using Microsoft.ML.Runtime.Training;
using Microsoft.ML.Runtime.Internal.Internallearn;
namespace Microsoft.ML.Runtime.Learners
{
public abstract class LbfgsTrainerBase<TArgs, TTransformer, TModel> : TrainerEstimatorBase<TTransformer, TModel>
where TTransformer : ISingleFeaturePredictionTransformer<TModel>
where TModel : IPredictor
where TArgs : LbfgsTrainerBase<TArgs, TTransformer, TModel>.ArgumentsBase, new ()
{
public abstract class ArgumentsBase : LearnerInputBaseWithWeight
{
[Argument(ArgumentType.AtMostOnce, HelpText = "L2 regularization weight", ShortName = "l2", SortOrder = 50)]
[TGUI(Label = "L2 Weight", Description = "Weight of L2 regularizer term", SuggestedSweeps = "0,0.1,1")]
[TlcModule.SweepableFloatParamAttribute(0.0f, 1.0f, numSteps: 4)]
public float L2Weight = Defaults.L2Weight;
[Argument(ArgumentType.AtMostOnce, HelpText = "L1 regularization weight", ShortName = "l1", SortOrder = 50)]
[TGUI(Label = "L1 Weight", Description = "Weight of L1 regularizer term", SuggestedSweeps = "0,0.1,1")]
[TlcModule.SweepableFloatParamAttribute(0.0f, 1.0f, numSteps: 4)]
public float L1Weight = Defaults.L1Weight;
[Argument(ArgumentType.AtMostOnce, HelpText = "Tolerance parameter for optimization convergence. Low = slower, more accurate",
ShortName = "ot", SortOrder = 50)]
[TGUI(Label = "Optimization Tolerance", Description = "Threshold for optimizer convergence", SuggestedSweeps = "1e-4,1e-7")]
[TlcModule.SweepableDiscreteParamAttribute(new object[] { 1e-4f, 1e-7f })]
public float OptTol = Defaults.OptTol;
[Argument(ArgumentType.AtMostOnce, HelpText = "Memory size for L-BFGS. Low=faster, less accurate",
ShortName = "m", SortOrder = 50)]
[TGUI(Description = "Memory size for L-BFGS", SuggestedSweeps = "5,20,50")]
[TlcModule.SweepableDiscreteParamAttribute("MemorySize", new object[] { 5, 20, 50 })]
public int MemorySize = Defaults.MemorySize;
[Argument(ArgumentType.AtMostOnce, HelpText = "Maximum iterations.", ShortName = "maxiter")]
[TGUI(Label = "Max Number of Iterations")]
[TlcModule.SweepableLongParamAttribute("MaxIterations", 1, int.MaxValue)]
public int MaxIterations = Defaults.MaxIterations;
[Argument(ArgumentType.AtMostOnce, HelpText = "Run SGD to initialize LR weights, converging to this tolerance",
ShortName = "sgd")]
public float SgdInitializationTolerance = 0;
/// <summary>
/// Features must occur in at least this many instances to be included
/// </summary>
/// <remarks>If greater than 1, forces an initialization pass over the data</remarks>
//AP removed from now. This requires data transformatio. Perhaps we should handle it as seprate (non-learner) dependant
//Similarly how normalization is done
//public int CountThreshold { get { return _countThreshold; } set { _countThreshold = value; } }
[Argument(ArgumentType.AtMostOnce, HelpText = "If set to true, produce no output during training.",
ShortName = "q")]
public bool Quiet = false;
/// <summary>
/// Init Weights Diameter
/// </summary>
[Argument(ArgumentType.LastOccurenceWins, HelpText = "Init weights diameter", ShortName = "initwts", SortOrder = 140)]
[TGUI(Label = "Initial Weights Scale", SuggestedSweeps = "0,0.1,0.5,1")]
[TlcModule.SweepableFloatParamAttribute("InitWtsDiameter", 0.0f, 1.0f, numSteps: 5)]
public float InitWtsDiameter = 0;
// Deprecated
[Argument(ArgumentType.AtMostOnce, HelpText = "Whether or not to use threads. Default is true",
ShortName = "t", Hide = true)]
public bool UseThreads = true;
/// <summary>
/// Number of threads. Null means use the number of processors.
/// </summary>
[Argument(ArgumentType.AtMostOnce, HelpText = "Number of threads", ShortName = "nt")]
public int? NumThreads;
[Argument(ArgumentType.AtMostOnce, HelpText = "Force densification of the internal optimization vectors", ShortName = "do")]
[TlcModule.SweepableDiscreteParamAttribute("DenseOptimizer", new object[] { false, true })]
public bool DenseOptimizer = false;
[Argument(ArgumentType.AtMostOnce, HelpText = "Enforce non-negative weights", ShortName = "nn", SortOrder = 90)]
public bool EnforceNonNegativity = Defaults.EnforceNonNegativity;
internal static class Defaults
{
internal const float L2Weight = 1;
internal const float L1Weight = 1;
internal const float OptTol = 1e-7f;
internal const int MemorySize = 20;
internal const int MaxIterations = int.MaxValue;
internal const bool EnforceNonNegativity = false;
}
}
private const string RegisterName = nameof(LbfgsTrainerBase<TArgs, TTransformer, TModel>);
protected int NumFeatures;
protected VBuffer<float> CurrentWeights;
protected long NumGoodRows;
protected Double WeightSum;
protected bool ShowTrainingStats;
private TModel _srcPredictor;
protected readonly TArgs Args;
protected readonly float L2Weight;
protected readonly float L1Weight;
protected readonly float OptTol;
protected readonly int MemorySize;
protected readonly int MaxIterations;
protected readonly float SgdInitializationTolerance;
protected readonly bool Quiet;
protected readonly float InitWtsDiameter;
protected readonly bool UseThreads;
protected readonly int? NumThreads;
protected readonly bool DenseOptimizer;
protected readonly long MaxNormalizationExamples;
protected readonly bool EnforceNonNegativity;
// The training data, when NOT using multiple threads.
private RoleMappedData _data;
private FloatLabelCursor.Factory _cursorFactory;
// Used for the multi-threading case, null otherwise. These three arrays are parallel. _weights may be null.
private VBuffer<float>[] _features;
private float[] _labels;
private float[] _weights;
// Stores the bounds of the chunk to be used by each thread. The 0th slot is 0. The length
// is one more than the number of threads to use.
private int _numChunks;
private int[] _ranges;
// Working buffers allocated lazily.
private VBuffer<float>[] _localGradients;
private float[] _localLosses;
// REVIEW: It's pointless to request caching when we're going to load everything into
// memory, that is, when using multiple threads. So should caching not be requested?
private static readonly TrainerInfo _info = new TrainerInfo(caching: true, supportIncrementalTrain: true);
public override TrainerInfo Info => _info;
internal LbfgsTrainerBase(IHostEnvironment env,
string featureColumn,
SchemaShape.Column labelColumn,
string weightColumn,
Action<TArgs> advancedSettings,
float l1Weight,
float l2Weight,
float optimizationTolerance,
int memorySize,
bool enforceNoNegativity)
: this(env, new TArgs
{
FeatureColumn = featureColumn,
LabelColumn = labelColumn.Name,
WeightColumn = weightColumn ?? Optional<string>.Explicit(weightColumn),
L1Weight = l1Weight,
L2Weight = l2Weight,
OptTol = optimizationTolerance,
MemorySize = memorySize,
EnforceNonNegativity = enforceNoNegativity
},
labelColumn, advancedSettings)
{
}
internal LbfgsTrainerBase(IHostEnvironment env,
TArgs args,
SchemaShape.Column labelColumn,
Action<TArgs> advancedSettings = null)
: base(Contracts.CheckRef(env, nameof(env)).Register(RegisterName), TrainerUtils.MakeR4VecFeature(args.FeatureColumn),
labelColumn, TrainerUtils.MakeR4ScalarWeightColumn(args.WeightColumn, args.WeightColumn.IsExplicit))
{
Host.CheckValue(args, nameof(args));
Args = args;
// Apply the advanced args, if the user supplied any.
advancedSettings?.Invoke(args);
args.FeatureColumn = FeatureColumn.Name;
args.LabelColumn = LabelColumn.Name;
args.WeightColumn = WeightColumn.Name;
Host.CheckUserArg(!Args.UseThreads || Args.NumThreads > 0 || Args.NumThreads == null,
nameof(Args.NumThreads), "numThreads must be positive (or empty for default)");
Host.CheckUserArg(Args.L2Weight >= 0, nameof(Args.L2Weight), "Must be non-negative");
Host.CheckUserArg(Args.L1Weight >= 0, nameof(Args.L1Weight), "Must be non-negative");
Host.CheckUserArg(Args.OptTol > 0, nameof(Args.OptTol), "Must be positive");
Host.CheckUserArg(Args.MemorySize > 0, nameof(Args.MemorySize), "Must be positive");
Host.CheckUserArg(Args.MaxIterations > 0, nameof(Args.MaxIterations), "Must be positive");
Host.CheckUserArg(Args.SgdInitializationTolerance >= 0, nameof(Args.SgdInitializationTolerance), "Must be non-negative");
Host.CheckUserArg(Args.NumThreads == null || Args.NumThreads.Value >= 0, nameof(Args.NumThreads), "Must be non-negative");
Host.CheckParam(!(Args.L2Weight < 0), nameof(Args.L2Weight), "Must be non-negative, if provided.");
Host.CheckParam(!(Args.L1Weight < 0), nameof(Args.L1Weight), "Must be non-negative, if provided");
Host.CheckParam(!(Args.OptTol <= 0), nameof(Args.OptTol), "Must be positive, if provided.");
Host.CheckParam(!(Args.MemorySize <= 0), nameof(Args.MemorySize), "Must be positive, if provided.");
L2Weight = Args.L2Weight;
L1Weight = Args.L1Weight;
OptTol = Args.OptTol;
MemorySize =Args.MemorySize;
MaxIterations = Args.MaxIterations;
SgdInitializationTolerance = Args.SgdInitializationTolerance;
Quiet = Args.Quiet;
InitWtsDiameter = Args.InitWtsDiameter;
UseThreads = Args.UseThreads;
NumThreads = Args.NumThreads;
DenseOptimizer = Args.DenseOptimizer;
EnforceNonNegativity = Args.EnforceNonNegativity;
if (EnforceNonNegativity && ShowTrainingStats)
{
ShowTrainingStats = false;
using (var ch = Host.Start("Initialization"))
{
ch.Warning("The training statistics cannot be computed with non-negativity constraint.");
}
}
ShowTrainingStats = false;
_srcPredictor = default;
}
private static TArgs ArgsInit(string featureColumn, SchemaShape.Column labelColumn,
string weightColumn,
float l1Weight,
float l2Weight,
float optimizationTolerance,
int memorySize,
bool enforceNoNegativity)
{
var args = new TArgs
{
FeatureColumn = featureColumn,
LabelColumn = labelColumn.Name,
WeightColumn = weightColumn ?? Optional<string>.Explicit(weightColumn),
L1Weight = l1Weight,
L2Weight = l2Weight,
OptTol = optimizationTolerance,
MemorySize = memorySize,
EnforceNonNegativity = enforceNoNegativity
};
args.WeightColumn = weightColumn;
return args;
}
protected virtual int ClassCount => 1;
protected int BiasCount => ClassCount;
protected int WeightCount => ClassCount * NumFeatures;
private protected virtual Optimizer InitializeOptimizer(IChannel ch, FloatLabelCursor.Factory cursorFactory,
out VBuffer<float> init, out ITerminationCriterion terminationCriterion)
{
// MeanRelativeImprovementCriterion:
// Stops optimization when the average objective improvement over the last
// n iterations, normalized by the function value, is small enough.
terminationCriterion = new MeanRelativeImprovementCriterion(OptTol, 5, MaxIterations);
Optimizer opt = (L1Weight > 0)
? new L1Optimizer(Host, BiasCount, L1Weight / NumGoodRows, MemorySize, DenseOptimizer, null, EnforceNonNegativity)
: new Optimizer(Host, MemorySize, DenseOptimizer, null, EnforceNonNegativity);
opt.Quiet = Quiet;
if (_srcPredictor != null)
init = InitializeWeightsFromPredictor(_srcPredictor);
else if (InitWtsDiameter > 0)
{
float[] initWeights = new float[BiasCount + WeightCount];
for (int j = 0; j < initWeights.Length; j++)
initWeights[j] = InitWtsDiameter * (Host.Rand.NextSingle() - 0.5f);
init = new VBuffer<float>(initWeights.Length, initWeights);
}
else if (SgdInitializationTolerance > 0)
init = InitializeWeightsSgd(ch, cursorFactory);
else
init = VBufferUtils.CreateEmpty<float>(BiasCount + WeightCount);
return opt;
}
/// <summary>
/// Initialize weights by running SGD up to specified tolerance.
/// </summary>
private protected virtual VBuffer<float> InitializeWeightsSgd(IChannel ch, FloatLabelCursor.Factory cursorFactory)
{
if (!Quiet)
ch.Info("Running SGD initialization with tolerance {0}", SgdInitializationTolerance);
int numExamples = 0;
var oldWeights = VBufferUtils.CreateEmpty<float>(BiasCount + WeightCount);
DTerminate terminateSgd =
(in VBuffer<float> x) =>
{
if (++numExamples % 1000 != 0)
return false;
VectorUtils.AddMult(in x, -1, ref oldWeights);
float normDiff = VectorUtils.Norm(oldWeights);
x.CopyTo(ref oldWeights);
// #if OLD_TRACING // REVIEW: How should this be ported?
if (!Quiet)
{
Console.Write(".");
if (numExamples % 50000 == 0)
Console.WriteLine("\t{0}\t{1}", numExamples, normDiff);
}
// #endif
return normDiff < SgdInitializationTolerance;
};
VBuffer<float> result = default(VBuffer<float>);
FloatLabelCursor cursor = null;
try
{
float[] scratch = null;
SgdOptimizer.DStochasticGradient lossSgd =
(in VBuffer<float> x, ref VBuffer<float> grad) =>
{
// Zero out the gradient by sparsifying.
VBufferUtils.Resize(ref grad, grad.Length, 0);
EnsureBiases(ref grad);
if (cursor == null || !cursor.MoveNext())
{
if (cursor != null)
cursor.Dispose();
cursor = cursorFactory.Create();
if (!cursor.MoveNext())
return;
}
AccumulateOneGradient(in cursor.Features, cursor.Label, cursor.Weight, in x, ref grad, ref scratch);
};
VBuffer<float> sgdWeights;
if (DenseOptimizer)
sgdWeights = VBufferUtils.CreateDense<float>(BiasCount + WeightCount);
else
sgdWeights = VBufferUtils.CreateEmpty<float>(BiasCount + WeightCount);
SgdOptimizer sgdo = new SgdOptimizer(terminateSgd);
sgdo.Minimize(lossSgd, ref sgdWeights, ref result);
// #if OLD_TRACING // REVIEW: How should this be ported?
if (!Quiet)
Console.WriteLine();
// #endif
ch.Info("SGD initialization done in {0} rounds", numExamples);
}
finally
{
if (cursor != null)
cursor.Dispose();
}
return result;
}
protected abstract VBuffer<float> InitializeWeightsFromPredictor(TModel srcPredictor);
private protected abstract void CheckLabel(RoleMappedData data);
protected virtual void PreTrainingProcessInstance(float label, in VBuffer<float> feat, float weight)
{
}
protected abstract TModel CreatePredictor();
/// <summary>
/// The basic training calls the optimizer
/// </summary>
private protected override TModel TrainModelCore(TrainContext context)
{
Contracts.CheckValue(context, nameof(context));
Host.CheckParam(context.InitialPredictor == null || context.InitialPredictor is TModel, nameof(context.InitialPredictor));
if (context.InitialPredictor != null)
_srcPredictor = (TModel)context.InitialPredictor;
var data = context.TrainingSet;
data.CheckFeatureFloatVector(out NumFeatures);
CheckLabel(data);
data.CheckOptFloatWeight();
if (NumFeatures >= Utils.ArrayMaxSize / ClassCount)
{
throw Contracts.ExceptParam(nameof(data),
"The number of model parameters which is equal to ('# of features' + 1) * '# of classes' should be less than or equal to {0}.", Utils.ArrayMaxSize);
}
using (var ch = Host.Start("Training"))
{
TrainCore(ch, data);
return CreatePredictor();
}
}
private protected virtual void TrainCore(IChannel ch, RoleMappedData data)
{
Host.AssertValue(ch);
ch.AssertValue(data);
// Compute the number of threads to use. The ctor should have verified that this will
// produce a positive value.
int numThreads = !UseThreads ? 1 : (NumThreads ?? Environment.ProcessorCount);
if (Host.ConcurrencyFactor > 0 && numThreads > Host.ConcurrencyFactor)
{
numThreads = Host.ConcurrencyFactor;
ch.Warning("The number of threads specified in trainer arguments is larger than the concurrency factor "
+ "setting of the environment. Using {0} training threads instead.", numThreads);
}
ch.Assert(numThreads > 0);
NumGoodRows = 0;
WeightSum = 0;
_features = null;
_labels = null;
_weights = null;
if (numThreads > 1)
{
ch.Info("LBFGS multi-threading will attempt to load dataset into memory. In case of out-of-memory " +
"issues, add 'numThreads=1' to the trainer arguments and 'cache=-' to the command line " +
"arguments to turn off multi-threading.");
_features = new VBuffer<float>[1000];
_labels = new float[1000];
if (data.Schema.Weight != null)
_weights = new float[1000];
}
var cursorFactory = new FloatLabelCursor.Factory(data, CursOpt.Features | CursOpt.Label | CursOpt.Weight);
long numBad;
// REVIEW: This pass seems overly expensive for the benefit when multi-threading is off....
using (var cursor = cursorFactory.Create())
using (var pch = Host.StartProgressChannel("LBFGS data prep"))
{
// REVIEW: maybe it makes sense for the factory to capture the good row count after
// the first successful cursoring?
Double totalCount = data.Data.GetRowCount() ?? Double.NaN;
long exCount = 0;
pch.SetHeader(new ProgressHeader(null, new[] { "examples" }),
e => e.SetProgress(0, exCount, totalCount));
while (cursor.MoveNext())
{
WeightSum += cursor.Weight;
if (ShowTrainingStats)
ProcessPriorDistribution(cursor.Label, cursor.Weight);
PreTrainingProcessInstance(cursor.Label, in cursor.Features, cursor.Weight);
exCount++;
if (_features != null)
{
ch.Assert(cursor.KeptRowCount <= int.MaxValue);
int index = (int)cursor.KeptRowCount - 1;
Utils.EnsureSize(ref _features, index + 1);
Utils.EnsureSize(ref _labels, index + 1);
if (_weights != null)
{
Utils.EnsureSize(ref _weights, index + 1);
_weights[index] = cursor.Weight;
}
Utils.Swap(ref _features[index], ref cursor.Features);
_labels[index] = cursor.Label;
if (cursor.KeptRowCount >= int.MaxValue)
{
ch.Warning("Limiting data size for multi-threading");
break;
}
}
}
NumGoodRows = cursor.KeptRowCount;
numBad = cursor.SkippedRowCount;
}
ch.Check(NumGoodRows > 0, NoTrainingInstancesMessage);
if (numBad > 0)
ch.Warning("Skipped {0} instances with missing features/label/weight during training", numBad);
if (_features != null)
{
ch.Assert(numThreads > 1);
// If there are so many threads that each only gets a small number (less than 10) of instances, trim
// the number of threads so each gets a more reasonable number (100 or so). These numbers are pretty arbitrary,
// but avoid the possibility of having no instances on some threads.
if (numThreads > 1 && NumGoodRows / numThreads < 10)
{
int numNew = Math.Max(1, (int)NumGoodRows / 100);
ch.Warning("Too few instances to use {0} threads, decreasing to {1} thread(s)", numThreads, numNew);
numThreads = numNew;
}
ch.Assert(numThreads > 0);
// Divide up the instances among the threads.
_numChunks = numThreads;
_ranges = new int[_numChunks + 1];
int cinstTot = (int)NumGoodRows;
for (int ichk = 0, iinstMin = 0; ichk < numThreads; ichk++)
{
int cchkLeft = numThreads - ichk; // Number of chunks left to fill.
ch.Assert(0 < cchkLeft && cchkLeft <= numThreads);
int cinstThis = (cinstTot - iinstMin + cchkLeft - 1) / cchkLeft; // Size of this chunk.
ch.Assert(0 < cinstThis && cinstThis <= cinstTot - iinstMin);
iinstMin += cinstThis;
_ranges[ichk + 1] = iinstMin;
}
_localLosses = new float[numThreads];
_localGradients = new VBuffer<float>[numThreads - 1];
int size = BiasCount + WeightCount;
for (int i = 0; i < _localGradients.Length; i++)
_localGradients[i] = VBufferUtils.CreateEmpty<float>(size);
ch.Assert(_numChunks > 0 && _data == null);
}
else
{
// Streaming, single-threaded case.
_data = data;
_cursorFactory = cursorFactory;
ch.Assert(_numChunks == 0 && _data != null);
}
VBuffer<float> initWeights;
ITerminationCriterion terminationCriterion;
Optimizer opt = InitializeOptimizer(ch, cursorFactory, out initWeights, out terminationCriterion);
opt.Quiet = Quiet;
float loss;
try
{
opt.Minimize(DifferentiableFunction, ref initWeights, terminationCriterion, ref CurrentWeights, out loss);
}
catch (Optimizer.PrematureConvergenceException e)
{
if (!Quiet)
ch.Warning("Premature convergence occurred. The OptimizationTolerance may be set too small. {0}", e.Message);
CurrentWeights = e.State.X;
loss = e.State.Value;
}
ch.Assert(CurrentWeights.Length == BiasCount + WeightCount);
int numParams = BiasCount;
if ((L1Weight > 0 && !Quiet) || ShowTrainingStats)
{
VBufferUtils.ForEachDefined(in CurrentWeights, (index, value) => { if (index >= BiasCount && value != 0) numParams++; });
if (L1Weight > 0 && !Quiet)
ch.Info("L1 regularization selected {0} of {1} weights.", numParams, BiasCount + WeightCount);
}
if (ShowTrainingStats)
ComputeTrainingStatistics(ch, cursorFactory, loss, numParams);
}
// Ensure that the bias portion of vec is represented in vec.
// REVIEW: Is this really necessary?
protected void EnsureBiases(ref VBuffer<float> vec)
{
// REVIEW: Consider promoting this "densify first n entries" to a general purpose utility,
// if we ever encounter other situations where this becomes useful.
Contracts.Assert(vec.Length == BiasCount + WeightCount);
VBufferUtils.DensifyFirst(ref vec, BiasCount);
}
protected abstract float AccumulateOneGradient(in VBuffer<float> feat, float label, float weight,
in VBuffer<float> xDense, ref VBuffer<float> grad, ref float[] scratch);
private protected abstract void ComputeTrainingStatistics(IChannel ch, FloatLabelCursor.Factory cursorFactory, float loss, int numParams);
protected abstract void ProcessPriorDistribution(float label, float weight);
/// <summary>
/// The gradient being used by the optimizer
/// </summary>
protected virtual float DifferentiableFunction(in VBuffer<float> x, ref VBuffer<float> gradient,
IProgressChannelProvider progress)
{
Contracts.Assert((_numChunks == 0) != (_data == null));
Contracts.Assert((_cursorFactory == null) == (_data == null));
Contracts.Assert(x.Length == BiasCount + WeightCount);
Contracts.Assert(gradient.Length == BiasCount + WeightCount);
// REVIEW: if/when LBFGS test code is removed, the progress provider needs to become required.
Contracts.AssertValueOrNull(progress);
float scaleFactor = 1 / (float)WeightSum;
VBuffer<float> xDense = default;
if (x.IsDense)
xDense = x;
else
{
VBuffer<float> xDenseTemp = default;
x.CopyToDense(ref xDenseTemp);
xDense = xDenseTemp;
}
IProgressChannel pch = progress != null ? progress.StartProgressChannel("Gradient") : null;
float loss;
using (pch)
{
loss = _data == null
? DifferentiableFunctionMultithreaded(in xDense, ref gradient, pch)
: DifferentiableFunctionStream(_cursorFactory, in xDense, ref gradient, pch);
}
float regLoss = 0;
if (L2Weight > 0)
{
Contracts.Assert(xDense.IsDense);
var values = xDense.GetValues();
Double r = 0;
for (int i = BiasCount; i < values.Length; i++)
{
var xx = values[i];
r += xx * xx;
}
regLoss = (float)(r * L2Weight * 0.5);
// Here we probably want to use sparse x
VBufferUtils.ApplyWithEitherDefined(in x, ref gradient,
(int ind, float v1, ref float v2) => { if (ind >= BiasCount) v2 += L2Weight * v1; });
}
VectorUtils.ScaleBy(ref gradient, scaleFactor);
// REVIEW: The regularization component of the loss is being scaled as well,
// but it's unclear that it should be scaled.
return (loss + regLoss) * scaleFactor;
}
/// <summary>
/// Batch-parallel optimizer
/// </summary>
/// <remarks>
/// REVIEW: consider getting rid of multithread-targeted members
/// Using TPL, the distinction between Multithreaded and Sequential implementations is unnecessary
/// </remarks>
protected virtual float DifferentiableFunctionMultithreaded(in VBuffer<float> xDense, ref VBuffer<float> gradient, IProgressChannel pch)
{
Contracts.Assert(_data == null);
Contracts.Assert(_cursorFactory == null);
Contracts.Assert(_numChunks > 0);
Contracts.Assert(Utils.Size(_ranges) == _numChunks + 1);
Contracts.Assert(Utils.Size(_localLosses) == _numChunks);
Contracts.Assert(Utils.Size(_localGradients) + 1 == _numChunks);
Contracts.AssertValueOrNull(pch);
// Declare a local variable, since the lambda cannot capture the xDense. The gradient
// calculation will modify the local gradients, but not this xx value.
var xx = xDense;
var gg = gradient;
Parallel.For(0, _numChunks,
ichk =>
{
if (ichk == 0)
_localLosses[ichk] = DifferentiableFunctionComputeChunk(ichk, in xx, ref gg, pch);
else
_localLosses[ichk] = DifferentiableFunctionComputeChunk(ichk, in xx, ref _localGradients[ichk - 1], null);
});
gradient = gg;
float loss = _localLosses[0];
for (int i = 1; i < _numChunks; i++)
{
VectorUtils.Add(in _localGradients[i - 1], ref gradient);
loss += _localLosses[i];
}
return loss;
}
protected float DifferentiableFunctionComputeChunk(int ichk, in VBuffer<float> xDense, ref VBuffer<float> grad, IProgressChannel pch)
{
Contracts.Assert(0 <= ichk && ichk < _numChunks);
Contracts.AssertValueOrNull(pch);
VBufferUtils.Clear(ref grad);
VBufferUtils.Densify(ref grad);
float[] scratch = null;
double loss = 0;
int ivMin = _ranges[ichk];
int ivLim = _ranges[ichk + 1];
int iv = ivMin;
if (pch != null)
pch.SetHeader(new ProgressHeader(null, new[] { "examples" }), e => e.SetProgress(0, iv - ivMin, ivLim - ivMin));
for (iv = ivMin; iv < ivLim; iv++)
{
float weight = _weights != null ? _weights[iv] : 1;
loss += AccumulateOneGradient(in _features[iv], _labels[iv], weight, in xDense, ref grad, ref scratch);
}
// we need use double type to accumulate loss to avoid roundoff error
// please see http://mathworld.wolfram.com/RoundoffError.html for roundoff error definition
// finally we need to convert double type to float for function definition
return (float)loss;
}
private protected float DifferentiableFunctionStream(FloatLabelCursor.Factory cursorFactory, in VBuffer<float> xDense, ref VBuffer<float> grad, IProgressChannel pch)
{
Contracts.AssertValue(cursorFactory);
VBufferUtils.Clear(ref grad);
VBufferUtils.Densify(ref grad);
float[] scratch = null;
double loss = 0;
long count = 0;
if (pch != null)
pch.SetHeader(new ProgressHeader(null, new[] { "examples" }), e => e.SetProgress(0, count));
using (var cursor = cursorFactory.Create())
{
while (cursor.MoveNext())
{
loss += AccumulateOneGradient(in cursor.Features, cursor.Label, cursor.Weight,
in xDense, ref grad, ref scratch);
count++;
}
}
// we need use double type to accumulate loss to avoid roundoff error
// please see http://mathworld.wolfram.com/RoundoffError.html for roundoff error definition
// finally we need to convert double type to float for function definition
return (float)loss;
}
protected VBuffer<float> InitializeWeights(IEnumerable<float> weights, IEnumerable<float> biases)
{
Contracts.AssertValue(biases);
Contracts.AssertValue(weights);
// REVIEW: Support initializing the weights of a superset of features
var initWeights = new float[BiasCount + WeightCount];
int i = 0;
const string classError = "The initialization predictor has different number of classes than the training data.";
foreach (var bias in biases)
{
Contracts.Check(i < BiasCount, classError);
initWeights[i++] = bias;
}
Contracts.Check(i == BiasCount, classError);
const string featError = "The initialization predictor has different number of features than the training data.";
foreach (var weight in weights)
{
Contracts.Check(i < initWeights.Length, featError);
initWeights[i++] = weight;
}
Contracts.Check(i == initWeights.Length, featError);
return new VBuffer<float>(initWeights.Length, initWeights);
}
}
}
| 46.809711
| 173
| 0.574168
|
[
"MIT"
] |
Zruty0/machinelearning
|
src/Microsoft.ML.StandardLearners/Standard/LogisticRegression/LbfgsPredictorBase.cs
| 35,669
|
C#
|
/*************************************************************
* Project: NetCoreCMS *
* Web: http://dotnetcorecms.org *
* Author: OnnoRokom Software Ltd. *
* Website: www.onnorokomsoftware.com *
* Email: info@onnorokomsoftware.com *
* Copyright: OnnoRokom Software Ltd. *
* License: BSD-3-Clause *
*************************************************************/
using Microsoft.Extensions.Logging;
using NetCoreCMS.Framework.Core.Messages;
using NetCoreCMS.Framework.Core.Network;
using NetCoreCMS.Framework.Utility;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MimeKit;
using MailKit.Security;
using MimeKit.Text;
using System.Net;
namespace NetCoreCMS.Framework.Core.Services.Auth
{
// This class is used by the application to send Email and SMS
// when you turn on two-factor authentication in ASP.NET Identity.
// For more details see this link https://go.microsoft.com/fwlink/?LinkID=532713
public class AuthMessageSender : IEmailSender, ISmsSender
{
ILogger _logger;
INccSettingsService _nccSettingsService;
public AuthMessageSender(INccSettingsService settingsService, ILoggerFactory factory)
{
_nccSettingsService = settingsService;
_logger = factory.CreateLogger<AuthMessageSender>();
}
public Task SendSmsAsync(string number, string message)
{
// Plug in your SMS service here to send a text message.
return Task.FromResult(0);
}
public Task SendEmailAsync(string email, string subject, string message)
{
var smtpSettings = _nccSettingsService.GetByKey<SmtpSettings>();
if (smtpSettings == null)
{
_logger.LogError("SMTP Settings not found");
GlobalMessageRegistry.RegisterMessage(
new GlobalMessage()
{
For = GlobalMessage.MessageFor.Both,
Registrater = nameof(AuthMessageSender),
Type = GlobalMessage.MessageType.Error,
Text = "Email Send Failed. SMTP Settings not set yet."
},
new System.TimeSpan(0, 1, 0)
);
}
else
{
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress(smtpSettings.FromName, smtpSettings.FromEmail));
emailMessage.To.Add(new MailboxAddress("User", email));
emailMessage.Subject = subject;
emailMessage.Body = new TextPart(TextFormat.Html) { Text = message };
using (var client = new SmtpClient())
{
client.LocalDomain = smtpSettings.Host;
client.ConnectAsync(smtpSettings.Host, smtpSettings.Port, smtpSettings.UseSSL).Wait();
client.Authenticate(new NetworkCredential(smtpSettings.UserName, smtpSettings.Password));
client.SendAsync(emailMessage).Wait();
client.DisconnectAsync(true).Wait();
}
}
return Task.FromResult(0);
}
public Task SendEmailConfirmationAsync(string email, string callbackUrl)
{
SendEmailAsync(email, "NetCoreCMS new signup", "Thank you for your registration. Please confirm your registration <a href='" + callbackUrl + "'>Verify</a>");
return Task.FromResult(0);
}
}
}
| 41.395604
| 169
| 0.553225
|
[
"BSD-3-Clause"
] |
NormanVu/NetCoreCMS
|
NetCoreCMS.Framework/Core/Services/Auth/MessageServices.cs
| 3,769
|
C#
|
namespace Orchard.JobsQueue.Extensions {
public static class StringExtensions {
public static string TrimSafe(this string value) {
return value != null ? value.Trim() : null;
}
}
}
| 31
| 58
| 0.631336
|
[
"BSD-3-Clause"
] |
1996dylanriley/Orchard
|
src/Orchard.Web/Modules/Orchard.JobsQueue/Extensions/StringExtensions.cs
| 219
|
C#
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the wafv2-2019-07-29.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.WAFV2.Model
{
/// <summary>
/// <note>
/// <para>
/// This is the latest version of <b>AWS WAF</b>, named AWS WAFV2, released in November,
/// 2019. For information, including how to migrate your AWS WAF resources from the prior
/// release, see the <a href="https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html">AWS
/// WAF Developer Guide</a>.
/// </para>
/// </note>
/// <para>
/// High-level information about a <a>RegexPatternSet</a>, returned by operations like
/// create and list. This provides information like the ID, that you can use to retrieve
/// and manage a <code>RegexPatternSet</code>, and the ARN, that you provide to the <a>RegexPatternSetReferenceStatement</a>
/// to use the pattern set in a <a>Rule</a>.
/// </para>
/// </summary>
public partial class RegexPatternSetSummary
{
private string _arn;
private string _description;
private string _id;
private string _lockToken;
private string _name;
/// <summary>
/// Gets and sets the property ARN.
/// <para>
/// The Amazon Resource Name (ARN) of the entity.
/// </para>
/// </summary>
[AWSProperty(Min=20, Max=2048)]
public string ARN
{
get { return this._arn; }
set { this._arn = value; }
}
// Check to see if ARN property is set
internal bool IsSetARN()
{
return this._arn != null;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// A description of the set that helps with identification. You cannot change the description
/// of a set after you create it.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=256)]
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property Id.
/// <para>
/// A unique identifier for the set. This ID is returned in the responses to create and
/// list commands. You provide it to operations like update and delete.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=36)]
public string Id
{
get { return this._id; }
set { this._id = value; }
}
// Check to see if Id property is set
internal bool IsSetId()
{
return this._id != null;
}
/// <summary>
/// Gets and sets the property LockToken.
/// <para>
/// A token used for optimistic locking. AWS WAF returns a token to your get and list
/// requests, to mark the state of the entity at the time of the request. To make changes
/// to the entity associated with the token, you provide the token to operations like
/// update and delete. AWS WAF uses the token to ensure that no changes have been made
/// to the entity since you last retrieved it. If a change has been made, the update fails
/// with a <code>WAFOptimisticLockException</code>. If this happens, perform another get,
/// and use the new token returned by that operation.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=36)]
public string LockToken
{
get { return this._lockToken; }
set { this._lockToken = value; }
}
// Check to see if LockToken property is set
internal bool IsSetLockToken()
{
return this._lockToken != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of the data type instance. You cannot change the name after you create the
/// instance.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=128)]
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
}
}
| 34.3875
| 129
| 0.567794
|
[
"Apache-2.0"
] |
philasmar/aws-sdk-net
|
sdk/src/Services/WAFV2/Generated/Model/RegexPatternSetSummary.cs
| 5,502
|
C#
|
using System;
namespace RedMonkey.SchemaAnalysis
{
[Serializable]
public enum TriggerEvent
{
Delete,
Update,
Insert
}
[Serializable]
public enum TriggerActionTime
{
Before,
After
}
[Serializable]
public class Trigger : BaseObject<Trigger>
{
public Trigger(string _Name, Table _Table, Database _Database, string _Definition, TriggerActionTime _ActionTime, TriggerEvent _Event) : base(_Name)
{
Table = _Table;
Definition = _Definition;
ActionTime = _ActionTime;
Event = _Event;
Database = _Database;
}
public string Definition { get; set; }
public TriggerActionTime ActionTime { get; set; }
public TriggerEvent Event { get; set; }
public Table Table { get; set; }
public Database Database { get; set; }
public override bool IsEmpty()
{
return string.IsNullOrEmpty(Definition) ||
Table == null;
}
public override Trigger Complement(Trigger obj)
{
if (Name != obj.Name)
return this;
return null;
}
public override Trigger Union(Trigger obj)
{
return this;
}
public override bool IsEqual(Trigger obj)
{
return Name == obj.Name &&
Definition == obj.Definition &&
ActionTime == obj.ActionTime &&
Event == obj.Event &&
Table == obj.Table;
}
}
}
| 24.984615
| 156
| 0.527094
|
[
"Apache-2.0"
] |
rwood/RedMonkey
|
RedMonkey/RedMonkey.SchemaAnalysis/Trigger.cs
| 1,626
|
C#
|
using Microsoft.Extensions.DependencyInjection;
namespace Hookr.Web.Backend.Utilities
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddUtilities(this IServiceCollection services)
=> services
.AddScoped<IUserContextAccessor, UserContextAccessor>();
}
}
| 30.818182
| 87
| 0.731563
|
[
"Apache-2.0"
] |
mrlldd/hookr-rent-service
|
Hookr/Web/Hookr.Web.Backend/Utilities/ServiceCollectionExtensions.cs
| 339
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mono.Data.Sqlite;
namespace MultiplayerARPG.MMO
{
public partial class SQLiteDatabase
{
private bool ReadCharacterHotkey(SQLiteRowsReader reader, out CharacterHotkey result, bool resetReader = true)
{
if (resetReader)
reader.ResetReader();
if (reader.Read())
{
result = new CharacterHotkey();
result.hotkeyId = reader.GetString("hotkeyId");
result.type = (HotkeyType)reader.GetSByte("type");
result.dataId = reader.GetInt32("dataId");
return true;
}
result = CharacterHotkey.Empty;
return false;
}
public void CreateCharacterHotkey(string characterId, CharacterHotkey characterHotkey)
{
ExecuteNonQuery("INSERT INTO characterhotkey (id, characterId, hotkeyId, type, dataId) VALUES (@id, @characterId, @hotkeyId, @type, @dataId)",
new SqliteParameter("@id", characterId + "_" + characterHotkey.hotkeyId),
new SqliteParameter("@characterId", characterId),
new SqliteParameter("@hotkeyId", characterHotkey.hotkeyId),
new SqliteParameter("@type", characterHotkey.type),
new SqliteParameter("@dataId", characterHotkey.dataId));
}
public List<CharacterHotkey> ReadCharacterHotkeys(string characterId)
{
var result = new List<CharacterHotkey>();
var reader = ExecuteReader("SELECT * FROM characterhotkey WHERE characterId=@characterId",
new SqliteParameter("@characterId", characterId));
CharacterHotkey tempHotkey;
while (ReadCharacterHotkey(reader, out tempHotkey, false))
{
result.Add(tempHotkey);
}
return result;
}
public void DeleteCharacterHotkeys(string characterId)
{
ExecuteNonQuery("DELETE FROM characterhotkey WHERE characterId=@characterId", new SqliteParameter("@characterId", characterId));
}
}
}
| 39.142857
| 154
| 0.612682
|
[
"MIT"
] |
Limeless04/UnityMultiplayerARPG_MMO
|
Scripts/MMOGame/Database/SQLite/SQLiteDatabase_CharacterHotkey.cs
| 2,194
|
C#
|
using System;
using Aop.Api.Domain;
using System.Collections.Generic;
using Aop.Api.Response;
namespace Aop.Api.Request
{
/// <summary>
/// AOP API: koubei.marketing.campaign.merchant.activity.batchquery
/// </summary>
public class KoubeiMarketingCampaignMerchantActivityBatchqueryRequest : IAopRequest<KoubeiMarketingCampaignMerchantActivityBatchqueryResponse>
{
/// <summary>
/// 场景化商家运营活动批量查询
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
private Dictionary<string, string> udfParams; //add user-defined text parameters
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return this.returnUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "koubei.marketing.campaign.merchant.activity.batchquery";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public void PutOtherTextParam(string key, string value)
{
if(this.udfParams == null)
{
this.udfParams = new Dictionary<string, string>();
}
this.udfParams.Add(key, value);
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
if(udfParams != null)
{
parameters.AddAll(this.udfParams);
}
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 26.508065
| 147
| 0.575297
|
[
"Apache-2.0"
] |
554393109/alipay-sdk-net-all
|
AlipaySDKNet.Standard/Request/KoubeiMarketingCampaignMerchantActivityBatchqueryRequest.cs
| 3,313
|
C#
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Cse_Department.Assets
{
public partial class Assets_Details : Form
{
public Assets_Details()
{
InitializeComponent();
}
private void button5_Click(object sender, EventArgs e)
{
using (Asset ast = new Asset())
{
ast.lbl = "Add Information Here!";
ast.ShowDialog();
}
}
private void button2_Click(object sender, EventArgs e)
{
using (Asset ast = new Asset())
{
ast.lbl = "Update Information Here!";
ast.ShowDialog();
}
}
}
}
| 23.615385
| 63
| 0.533116
|
[
"MIT"
] |
mahinjust/Cse_Department_Management_System
|
Assets_Details.cs
| 923
|
C#
|
using AspNetCore.IQueryable.Extensions;
using AspNetCore.IQueryable.Extensions.Filter;
using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using RESTFul.Api.Commands;
using RESTFul.Api.Models;
using RESTFul.Api.Notification;
using RESTFul.Api.Service.Interfaces;
using RESTFul.Api.ViewModels;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace RESTFul.Api.Controllers
{
[Route("companies")]
[ApiConventionType(typeof(DefaultApiConventions))]
public class CompanyController : ApiBaseController
{
private readonly IDummyUserService _dummyUserService;
private readonly IMapper _mapper;
public CompanyController(
INotificationHandler<DomainNotification> notifications,
IDomainNotificationMediatorService mediator,
IDummyUserService dummyUserService,
IMapper mapper) : base(notifications, mediator)
{
_dummyUserService = dummyUserService;
_mapper = mapper;
}
/// <summary>
/// Get all companies.
/// </summary>
/// <returns>List of <see cref="Applicant"/></returns>
[HttpGet("")]
public async Task<ActionResult<List<Company>>> Get()
{
var result = await _dummyUserService.GetCompanies();
return ResponseGet(result);
}
/// <summary>
/// Get details of a company
/// </summary>
[HttpGet("{company}")]
public async Task<ActionResult<Company>> GetCompany(string company)
{
var result = await _dummyUserService.FindCompany(company);
return ResponseGet(result);
}
/// <summary>
/// Get all aplicants from a company
/// </summary>
[HttpGet("{company}/applicants")]
public async Task<ActionResult<List<ApplicantViewModel>>> GetCompanyApplicants(string company)
{
var result = await _dummyUserService.GetCompanyUsers(company);
return ResponseGet(_mapper.Map<List<ApplicantViewModel>>(result));
}
}
}
| 32.117647
| 102
| 0.656136
|
[
"MIT"
] |
brunohbrito/RESTFul.API-Example
|
src/RESTFul.Api/Controllers/CompanyController.cs
| 2,186
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
using XRTK.Definitions.Utilities;
namespace XRTK.Utilities
{
public static class PlatformUtility
{
public static bool IsPlatformSupported(this RuntimePlatform runtimePlatform, SupportedPlatforms platforms)
{
SupportedPlatforms target = GetSupportedPlatformMask(runtimePlatform);
return IsPlatformSupported(target, platforms);
}
private static SupportedPlatforms GetSupportedPlatformMask(RuntimePlatform runtimePlatform)
{
SupportedPlatforms supportedPlatforms = 0;
switch (runtimePlatform)
{
case RuntimePlatform.WindowsPlayer:
case RuntimePlatform.WindowsEditor:
supportedPlatforms |= SupportedPlatforms.WindowsStandalone;
break;
case RuntimePlatform.WSAPlayerARM:
case RuntimePlatform.WSAPlayerX86:
case RuntimePlatform.WSAPlayerX64:
case RuntimePlatform.XboxOne:
supportedPlatforms |= SupportedPlatforms.WindowsUniversal;
break;
case RuntimePlatform.OSXPlayer:
case RuntimePlatform.OSXEditor:
supportedPlatforms |= SupportedPlatforms.MacStandalone;
break;
case RuntimePlatform.LinuxPlayer:
case RuntimePlatform.LinuxEditor:
supportedPlatforms |= SupportedPlatforms.LinuxStandalone;
break;
}
return supportedPlatforms;
}
private static bool IsPlatformSupported(SupportedPlatforms target, SupportedPlatforms supported)
{
return ((target & supported) == target);
}
#if UNITY_EDITOR
public static bool IsPlatformSupported(this UnityEditor.BuildTarget editorBuildTarget, SupportedPlatforms platforms)
{
SupportedPlatforms target = GetSupportedPlatformMask(editorBuildTarget);
return IsPlatformSupported(target, platforms);
}
private static SupportedPlatforms GetSupportedPlatformMask(UnityEditor.BuildTarget editorBuildTarget)
{
SupportedPlatforms supportedPlatforms = 0;
switch (editorBuildTarget)
{
case UnityEditor.BuildTarget.StandaloneWindows:
case UnityEditor.BuildTarget.StandaloneWindows64:
supportedPlatforms |= SupportedPlatforms.WindowsStandalone;
break;
case UnityEditor.BuildTarget.WSAPlayer:
case UnityEditor.BuildTarget.XboxOne:
supportedPlatforms |= SupportedPlatforms.WindowsUniversal;
break;
case UnityEditor.BuildTarget.StandaloneOSX:
supportedPlatforms |= SupportedPlatforms.MacStandalone;
break;
case UnityEditor.BuildTarget.StandaloneLinux:
case UnityEditor.BuildTarget.StandaloneLinux64:
case UnityEditor.BuildTarget.StandaloneLinuxUniversal:
supportedPlatforms |= SupportedPlatforms.LinuxStandalone;
break;
}
return supportedPlatforms;
}
#endif
}
}
| 40.383721
| 124
| 0.628851
|
[
"MIT"
] |
hridpath/XRTK-Core
|
XRTK-Core/Assets/XRTK/Utilities/PlatformUtility.cs
| 3,475
|
C#
|
using UnityEngine;
using UnityEngine.SceneManagement;
public class StartButtonScript : MonoBehaviour {
void OnMouseDown() {
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
| 22.666667
| 71
| 0.789216
|
[
"MIT"
] |
HilHi-Technology/Contrast
|
Assets/Scripts/ButtonScripts/StartButtonScript.cs
| 206
|
C#
|
// The MIT License(MIT)
//
// Copyright(c) 2021 Alberto Rodriguez Orozco & LiveCharts Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using SkiaSharp;
using System;
namespace LiveChartsCore.SkiaSharpView.Painting
{
/// <inheritdoc cref="SolidColorPaint"/>
[Obsolete("Renamed to SolidColorPaint")]
public class SolidColorPaintTask : SolidColorPaint
{
/// <summary>
/// Initializes a new instance of the <see cref="SolidColorPaint"/> class.
/// </summary>
public SolidColorPaintTask()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SolidColorPaint"/> class.
/// </summary>
/// <param name="color">The color.</param>
public SolidColorPaintTask(SKColor color)
: base(color)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SolidColorPaint"/> class.
/// </summary>
/// <param name="color">The color.</param>
/// <param name="strokeWidth">Width of the stroke.</param>
public SolidColorPaintTask(SKColor color, float strokeWidth)
: base(color, strokeWidth)
{
}
}
}
| 38.186441
| 82
| 0.6751
|
[
"MIT"
] |
LabuzzMichal/LiveCharts2
|
src/skiasharp/LiveChartsCore.SkiaSharp/Painting/SolidColorPaintTask.cs
| 2,255
|
C#
|
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace MoBot.GUI.Controls
{
internal class ClosableTab : TabItem
{
private readonly CloseableHeader header = new CloseableHeader();
public ClosableTab()
{
Header = header;
header.ButtonClose.MouseEnter += ButtonCloseOnMouseEnter;
header.ButtonClose.MouseLeave += ButtonCloseOnMouseLeave;
header.ButtonClose.Click += ButtonCloseOnClick;
header.LabelTabTitle.SizeChanged += LabelTabTitleOnSizeChanged;
}
private void LabelTabTitleOnSizeChanged(object sender, SizeChangedEventArgs sizeChangedEventArgs)
{
header.ButtonClose.Margin = new Thickness(header.LabelTabTitle.ActualWidth + 5,3,4,0);
}
private void ButtonCloseOnClick(object sender, RoutedEventArgs routedEventArgs)
{
((TabControl)Parent).Items.Remove(this);
}
private void ButtonCloseOnMouseLeave(object sender, MouseEventArgs mouseEventArgs)
{
header.ButtonClose.Foreground = Brushes.Black;
}
private void ButtonCloseOnMouseEnter(object sender, MouseEventArgs mouseEventArgs)
{
header.ButtonClose.Foreground = Brushes.Red;
}
public string Title
{
set => header.LabelTabTitle.Content = value;
}
protected override void OnSelected(RoutedEventArgs e)
{
base.OnSelected(e);
header.LabelTabTitle.Visibility = Visibility.Visible;
}
protected override void OnUnselected(RoutedEventArgs e)
{
base.OnUnselected(e);
header.ButtonClose.Visibility = Visibility.Hidden;
}
protected override void OnMouseEnter(MouseEventArgs e)
{
base.OnMouseEnter(e);
header.ButtonClose.Visibility = Visibility.Visible;
}
protected override void OnMouseLeave(MouseEventArgs e)
{
base.OnMouseLeave(e);
if (!IsSelected)
header.ButtonClose.Visibility = Visibility.Hidden;
}
}
}
| 30.986111
| 105
| 0.635141
|
[
"MIT"
] |
ReezeBL/MoBotRemastered
|
MoBot/GUI/Controls/ClosableTab.cs
| 2,233
|
C#
|
using System;
using System.Runtime.InteropServices;
namespace Tesseract
{
/// <summary>
/// Represents an object that can iterate over tesseract's page structure.
/// </summary>
/// <remarks>
/// The iterator points to tesseract's internal page structure and is only valid while the Engine instance that created it exists
/// and has not been subjected to a call to Recognize since the iterator was created.
/// </remarks>
public class PageIterator : DisposableBase
{
protected readonly Page page;
protected readonly HandleRef handle;
internal PageIterator(Page page, IntPtr handle)
{
this.page = page;
this.handle = new HandleRef(this, handle);
}
/// <summary>
/// Moves the iterator to the start of the page.
/// </summary>
public void Begin()
{
VerifyNotDisposed();
if (handle.Handle != IntPtr.Zero)
{
Interop.TessApi.Native.PageIteratorBegin(handle);
}
}
/// <summary>
/// Moves to the start of the next element at the given level.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <param name="level"></param>
/// <returns></returns>
public bool Next(PageIteratorLevel level)
{
VerifyNotDisposed();
return handle.Handle != IntPtr.Zero && Interop.TessApi.Native.PageIteratorNext(handle, level) != 0;
}
/// <summary>
/// Moves the iterator to the next <paramref name="element"/> iff the iterator is not currently pointing to the last <paramref name="element"/> in the specified <paramref name="level"/> (i.e. the last word in the paragraph).
/// </summary>
/// <param name="level">The iterator level.</param>
/// <param name="element">The page level.</param>
/// <returns><c>True</c> iff there is another <paramref name="element"/> to advance too and the current element is not the last element at the given level; otherwise returns <c>False</c>.</returns>
public bool Next(PageIteratorLevel level, PageIteratorLevel element)
{
VerifyNotDisposed();
bool isAtFinalElement = IsAtFinalOf(level, element);
return !isAtFinalElement && Next(element);
}
/// <summary>
/// Returns <c>True</c> if the iterator is at the first element at the given level.
/// </summary>
/// <remarks>
/// A possible use is to determin if a call to next(word) moved to the start of a new paragraph.
/// </remarks>
/// <param name="level"></param>
/// <returns></returns>
public bool IsAtBeginningOf(PageIteratorLevel level)
{
VerifyNotDisposed();
return handle.Handle != IntPtr.Zero && Interop.TessApi.Native.PageIteratorIsAtBeginningOf(handle, level) != 0;
}
/// <summary>
/// Returns <c>True</c> if the iterator is positioned at the last element at the given level.
/// </summary>
/// <param name="level"></param>
/// <param name="element"></param>
/// <returns></returns>
public bool IsAtFinalOf(PageIteratorLevel level, PageIteratorLevel element)
{
VerifyNotDisposed();
return handle.Handle != IntPtr.Zero && Interop.TessApi.Native.PageIteratorIsAtFinalElement(handle, level, element) != 0;
}
public PolyBlockType BlockType
{
get
{
VerifyNotDisposed();
return handle.Handle == IntPtr.Zero ? PolyBlockType.Unknown : Interop.TessApi.Native.PageIteratorBlockType(handle);
}
}
public Pix GetBinaryImage(PageIteratorLevel level)
{
VerifyNotDisposed();
return handle.Handle == IntPtr.Zero ? null : Pix.Create(Interop.TessApi.Native.PageIteratorGetBinaryImage(handle, level));
}
public Pix GetImage(PageIteratorLevel level, int padding, out int x, out int y)
{
VerifyNotDisposed();
if (handle.Handle == IntPtr.Zero)
{
x = 0;
y = 0;
return null;
}
return Pix.Create(Interop.TessApi.Native.PageIteratorGetImage(handle, level, padding, page.Image.Handle, out x, out y));
}
/// <summary>
/// Gets the bounding rectangle of the current element at the given level.
/// </summary>
/// <param name="level"></param>
/// <param name="bounds"></param>
/// <returns></returns>
public bool TryGetBoundingBox(PageIteratorLevel level, out Rect bounds)
{
VerifyNotDisposed();
if (handle.Handle != IntPtr.Zero && Interop.TessApi.Native.PageIteratorBoundingBox(handle, level, out int x1, out int y1, out int x2, out int y2) != 0)
{
bounds = Rect.FromCoords(x1, y1, x2, y2);
return true;
}
else
{
bounds = Rect.Empty;
return false;
}
}
/// <summary>
/// Gets the baseline of the current element at the given level.
/// </summary>
/// <remarks>
/// The baseline is the line that passes through (x1, y1) and (x2, y2).
/// WARNING: with vertical text, baselines may be vertical! Returns false if there is no baseline at the current position.</remarks>
/// <param name="level"></param>
/// <param name="bounds"></param>
/// <returns></returns>
public bool TryGetBaseline(PageIteratorLevel level, out Rect bounds)
{
VerifyNotDisposed();
if (handle.Handle != IntPtr.Zero && Interop.TessApi.Native.PageIteratorBaseline(handle, level, out int x1, out int y1, out int x2, out int y2) != 0)
{
bounds = Rect.FromCoords(x1, y1, x2, y2);
return true;
}
else
{
bounds = Rect.Empty;
return false;
}
}
/// <summary>
/// Gets the element orientation information that the iterator currently points too.
/// </summary>
public ElementProperties GetProperties()
{
VerifyNotDisposed();
if (handle.Handle == IntPtr.Zero)
{
return new ElementProperties(Orientation.PageUp, TextLineOrder.TopToBottom, WritingDirection.LeftToRight, 0f);
}
Interop.TessApi.Native.PageIteratorOrientation(handle, out Orientation orientation, out WritingDirection writing_direction, out TextLineOrder textLineOrder, out float deskew_angle);
return new ElementProperties(orientation, textLineOrder, writing_direction, deskew_angle);
}
protected override void Dispose(bool disposing)
{
if (handle.Handle != IntPtr.Zero)
{
Interop.TessApi.Native.PageIteratorDelete(handle);
}
}
}
}
| 37.336788
| 232
| 0.571191
|
[
"Apache-2.0"
] |
F1schk0pp/tesseract
|
src/Tesseract/PageIterator.cs
| 7,208
|
C#
|
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.ApiManagement.V20180601Preview
{
/// <summary>
/// Certificate details.
/// </summary>
[AzureNextGenResourceType("azure-nextgen:apimanagement/v20180601preview:Certificate")]
public partial class Certificate : Pulumi.CustomResource
{
/// <summary>
/// Expiration date of the certificate. The date conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ` as specified by the ISO 8601 standard.
/// </summary>
[Output("expirationDate")]
public Output<string> ExpirationDate { get; private set; } = null!;
/// <summary>
/// Resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Subject attribute of the certificate.
/// </summary>
[Output("subject")]
public Output<string> Subject { get; private set; } = null!;
/// <summary>
/// Thumbprint of the certificate.
/// </summary>
[Output("thumbprint")]
public Output<string> Thumbprint { get; private set; } = null!;
/// <summary>
/// Resource type for API Management resource.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a Certificate resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public Certificate(string name, CertificateArgs args, CustomResourceOptions? options = null)
: base("azure-nextgen:apimanagement/v20180601preview:Certificate", name, args ?? new CertificateArgs(), MakeResourceOptions(options, ""))
{
}
private Certificate(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-nextgen:apimanagement/v20180601preview:Certificate", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:apimanagement:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/latest:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20160707:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20161010:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20170301:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20180101:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20190101:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20191201:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20191201preview:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20200601preview:Certificate"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing Certificate resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static Certificate Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new Certificate(name, id, options);
}
}
public sealed class CertificateArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Identifier of the certificate entity. Must be unique in the current API Management service instance.
/// </summary>
[Input("certificateId")]
public Input<string>? CertificateId { get; set; }
/// <summary>
/// Base 64 encoded certificate using the application/x-pkcs12 representation.
/// </summary>
[Input("data", required: true)]
public Input<string> Data { get; set; } = null!;
/// <summary>
/// Password for the Certificate
/// </summary>
[Input("password", required: true)]
public Input<string> Password { get; set; } = null!;
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The name of the API Management service.
/// </summary>
[Input("serviceName", required: true)]
public Input<string> ServiceName { get; set; } = null!;
public CertificateArgs()
{
}
}
}
| 42.780142
| 152
| 0.605769
|
[
"Apache-2.0"
] |
pulumi/pulumi-azure-nextgen
|
sdk/dotnet/ApiManagement/V20180601Preview/Certificate.cs
| 6,032
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Scantegra.Core.Entities
{
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9154")]
public enum msdyn_upgraderun_StatusCode
{
[System.Runtime.Serialization.EnumMemberAttribute()]
Active = 1,
[System.Runtime.Serialization.EnumMemberAttribute()]
Inactive = 2,
}
}
| 30.52
| 80
| 0.571429
|
[
"MIT"
] |
scantegra/scantegra
|
src/Scantegra.Core/Entities/OptionSets/msdyn_upgraderun_StatusCode.cs
| 763
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace GetHardwareInfo.Services.Win32
{
class GetNetworkcardInfo
{
//https://ourcodeworld.com/articles/read/294/how-to-retrieve-basic-and-advanced-hardware-and-software-information-gpu-hard-drive-processor-os-printers-in-winforms-with-c-sharp
}
}
| 28.25
| 183
| 0.766962
|
[
"Unlicense"
] |
j-mano/HardwareCheck-.net-core
|
Services/Win32/GetNetworkcardInfo.cs
| 341
|
C#
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json;
namespace Adyen.Model.Checkout
{
/// <summary>
/// Address
/// </summary>
[DataContract]
public partial class Address : IEquatable<Address>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="Address" /> class.
/// </summary>
[JsonConstructor]
protected Address() { }
/// <summary>
/// Initializes a new instance of the <see cref="Address" /> class.
/// </summary>
/// <param name="City">The name of the city. >Required if either houseNumberOrName, street, postalCode, or stateOrProvince are provided..</param>
/// <param name="Country">The two-character country code of the address >The permitted country codes are defined in ISO-3166-1 alpha-2 (e.g. 'NL'). (required).</param>
/// <param name="HouseNumberOrName">The number or name of the house..</param>
/// <param name="PostalCode">The postal code. >A maximum of five (5) digits for an address in the USA, or a maximum of ten (10) characters for an address in all other countries. >Required if either houseNumberOrName, street, city, or stateOrProvince are provided..</param>
/// <param name="StateOrProvince">The abbreviation of the state or province. >Two (2) characters for an address in the USA or Canada, or a maximum of three (3) characters for an address in all other countries. >Required for an address in the USA or Canada if either houseNumberOrName, street, city, or postalCode are provided..</param>
/// <param name="Street">The name of the street. >The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. >Required if either houseNumberOrName, city, postalCode, or stateOrProvince are provided..</param>
public Address(string City = default(string), string Country = default(string), string HouseNumberOrName = default(string), string PostalCode = default(string), string StateOrProvince = default(string), string Street = default(string))
{
// to ensure "Country" is required (not null)
if (Country == null)
{
throw new InvalidDataException("Country is a required property for Address and cannot be null");
}
else
{
this.Country = Country;
}
this.City = City;
this.HouseNumberOrName = HouseNumberOrName;
this.PostalCode = PostalCode;
this.StateOrProvince = StateOrProvince;
this.Street = Street;
}
/// <summary>
/// The name of the city. >Required if either houseNumberOrName, street, postalCode, or stateOrProvince are provided.
/// </summary>
/// <value>The name of the city. >Required if either houseNumberOrName, street, postalCode, or stateOrProvince are provided.</value>
[DataMember(Name="city", EmitDefaultValue=false)]
public string City { get; set; }
/// <summary>
/// The two-character country code of the address >The permitted country codes are defined in ISO-3166-1 alpha-2 (e.g. 'NL').
/// </summary>
/// <value>The two-character country code of the address >The permitted country codes are defined in ISO-3166-1 alpha-2 (e.g. 'NL').</value>
[DataMember(Name="country", EmitDefaultValue=false)]
public string Country { get; set; }
/// <summary>
/// The number or name of the house.
/// </summary>
/// <value>The number or name of the house.</value>
[DataMember(Name="houseNumberOrName", EmitDefaultValue=false)]
public string HouseNumberOrName { get; set; }
/// <summary>
/// The postal code. >A maximum of five (5) digits for an address in the USA, or a maximum of ten (10) characters for an address in all other countries. >Required if either houseNumberOrName, street, city, or stateOrProvince are provided.
/// </summary>
/// <value>The postal code. >A maximum of five (5) digits for an address in the USA, or a maximum of ten (10) characters for an address in all other countries. >Required if either houseNumberOrName, street, city, or stateOrProvince are provided.</value>
[DataMember(Name="postalCode", EmitDefaultValue=false)]
public string PostalCode { get; set; }
/// <summary>
/// The abbreviation of the state or province. >Two (2) characters for an address in the USA or Canada, or a maximum of three (3) characters for an address in all other countries. >Required for an address in the USA or Canada if either houseNumberOrName, street, city, or postalCode are provided.
/// </summary>
/// <value>The abbreviation of the state or province. >Two (2) characters for an address in the USA or Canada, or a maximum of three (3) characters for an address in all other countries. >Required for an address in the USA or Canada if either houseNumberOrName, street, city, or postalCode are provided.</value>
[DataMember(Name="stateOrProvince", EmitDefaultValue=false)]
public string StateOrProvince { get; set; }
/// <summary>
/// The name of the street. >The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. >Required if either houseNumberOrName, city, postalCode, or stateOrProvince are provided.
/// </summary>
/// <value>The name of the street. >The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. >Required if either houseNumberOrName, city, postalCode, or stateOrProvince are provided.</value>
[DataMember(Name="street", EmitDefaultValue=false)]
public string Street { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Address {\n");
sb.Append(" City: ").Append(City).Append("\n");
sb.Append(" Country: ").Append(Country).Append("\n");
sb.Append(" HouseNumberOrName: ").Append(HouseNumberOrName).Append("\n");
sb.Append(" PostalCode: ").Append(PostalCode).Append("\n");
sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n");
sb.Append(" Street: ").Append(Street).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as Address);
}
/// <summary>
/// Returns true if Address instances are equal
/// </summary>
/// <param name="input">Instance of Address to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Address input)
{
if (input == null)
return false;
return
(
this.City == input.City ||
(this.City != null &&
this.City.Equals(input.City))
) &&
(
this.Country == input.Country ||
(this.Country != null &&
this.Country.Equals(input.Country))
) &&
(
this.HouseNumberOrName == input.HouseNumberOrName ||
(this.HouseNumberOrName != null &&
this.HouseNumberOrName.Equals(input.HouseNumberOrName))
) &&
(
this.PostalCode == input.PostalCode ||
(this.PostalCode != null &&
this.PostalCode.Equals(input.PostalCode))
) &&
(
this.StateOrProvince == input.StateOrProvince ||
(this.StateOrProvince != null &&
this.StateOrProvince.Equals(input.StateOrProvince))
) &&
(
this.Street == input.Street ||
(this.Street != null &&
this.Street.Equals(input.Street))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.City != null)
hashCode = hashCode * 59 + this.City.GetHashCode();
if (this.Country != null)
hashCode = hashCode * 59 + this.Country.GetHashCode();
if (this.HouseNumberOrName != null)
hashCode = hashCode * 59 + this.HouseNumberOrName.GetHashCode();
if (this.PostalCode != null)
hashCode = hashCode * 59 + this.PostalCode.GetHashCode();
if (this.StateOrProvince != null)
hashCode = hashCode * 59 + this.StateOrProvince.GetHashCode();
if (this.Street != null)
hashCode = hashCode * 59 + this.Street.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 51.269231
| 349
| 0.593773
|
[
"MIT"
] |
Ganesh-Chavan/adyen-dotnet-api-library
|
Adyen/Model/Checkout/Address.cs
| 10,664
|
C#
|
namespace rcsir.net.vk.community.Dialogs
{
partial class FindGroupsDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.isGroupcheckBox = new System.Windows.Forms.CheckBox();
this.label1 = new System.Windows.Forms.Label();
this.groupIdNumeric = new System.Windows.Forms.NumericUpDown();
this.CancelSearchButton = new System.Windows.Forms.Button();
this.OKButton = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.groupIdNumeric)).BeginInit();
this.SuspendLayout();
//
// isGroupcheckBox
//
this.isGroupcheckBox.AutoSize = true;
this.isGroupcheckBox.Checked = true;
this.isGroupcheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.isGroupcheckBox.Location = new System.Drawing.Point(101, 56);
this.isGroupcheckBox.Name = "isGroupcheckBox";
this.isGroupcheckBox.Size = new System.Drawing.Size(65, 17);
this.isGroupcheckBox.TabIndex = 13;
this.isGroupcheckBox.Text = "is Group";
this.isGroupcheckBox.UseVisualStyleBackColor = true;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(15, 22);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 13);
this.label1.TabIndex = 12;
this.label1.Text = "Group/User ID:";
//
// groupIdNumeric
//
this.groupIdNumeric.Location = new System.Drawing.Point(101, 20);
this.groupIdNumeric.Maximum = new decimal(new int[] {
1000000000,
0,
0,
0});
this.groupIdNumeric.Name = "groupIdNumeric";
this.groupIdNumeric.Size = new System.Drawing.Size(219, 20);
this.groupIdNumeric.TabIndex = 11;
//
// CancelSearchButton
//
this.CancelSearchButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CancelSearchButton.Location = new System.Drawing.Point(164, 257);
this.CancelSearchButton.Name = "CancelSearchButton";
this.CancelSearchButton.Size = new System.Drawing.Size(75, 23);
this.CancelSearchButton.TabIndex = 10;
this.CancelSearchButton.Text = "Cancel";
this.CancelSearchButton.UseVisualStyleBackColor = true;
//
// OKButton
//
this.OKButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.OKButton.Location = new System.Drawing.Point(245, 257);
this.OKButton.Name = "OKButton";
this.OKButton.Size = new System.Drawing.Size(75, 23);
this.OKButton.TabIndex = 9;
this.OKButton.Text = "OK";
this.OKButton.UseVisualStyleBackColor = true;
this.OKButton.Click += new System.EventHandler(this.OKButton_Click);
//
// FindGroupsDialog
//
this.AcceptButton = this.OKButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(336, 292);
this.Controls.Add(this.isGroupcheckBox);
this.Controls.Add(this.label1);
this.Controls.Add(this.groupIdNumeric);
this.Controls.Add(this.CancelSearchButton);
this.Controls.Add(this.OKButton);
this.Name = "FindGroupsDialog";
this.Text = "FindGroupsDialog";
((System.ComponentModel.ISupportInitialize)(this.groupIdNumeric)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.CheckBox isGroupcheckBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.NumericUpDown groupIdNumeric;
private System.Windows.Forms.Button CancelSearchButton;
private System.Windows.Forms.Button OKButton;
}
}
| 43.558333
| 108
| 0.576813
|
[
"Unlicense"
] |
rcsir/RuNetImporter
|
RuNetImporter/VKCommunityAnalyzer/Dialogs/FindGroupsDialog.Designer.cs
| 5,229
|
C#
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Microsoft.EntityFrameworkCore.Update;
using Microsoft.EntityFrameworkCore.Update.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.EntityFrameworkCore.Migrations.Internal
{
/// <summary>
/// <para>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </para>
/// <para>
/// The service lifetime is <see cref="ServiceLifetime.Scoped" />. This means that each
/// <see cref="DbContext" /> instance will use its own instance of this service.
/// The implementation may depend on other services registered with any lifetime.
/// The implementation does not need to be thread-safe.
/// </para>
/// </summary>
public class MigrationsModelDiffer : IMigrationsModelDiffer
{
private static readonly Type[] _dropOperationTypes =
{
typeof(DropIndexOperation),
typeof(DropPrimaryKeyOperation),
typeof(DropSequenceOperation),
typeof(DropUniqueConstraintOperation),
typeof(DropCheckConstraintOperation)
};
private static readonly Type[] _alterOperationTypes =
{
typeof(AddPrimaryKeyOperation), typeof(AddUniqueConstraintOperation), typeof(AlterSequenceOperation)
};
private static readonly Type[] _renameOperationTypes =
{
typeof(RenameColumnOperation), typeof(RenameIndexOperation), typeof(RenameSequenceOperation)
};
private static readonly Type[] _columnOperationTypes = { typeof(AddColumnOperation), typeof(AlterColumnOperation) };
private static readonly Type[] _constraintOperationTypes =
{
typeof(AddForeignKeyOperation),
typeof(CreateIndexOperation),
typeof(CreateCheckConstraintOperation)
};
private IUpdateAdapter _sourceUpdateAdapter;
private IUpdateAdapter _targetUpdateAdapter;
private readonly Dictionary<ITable, SharedIdentityMap> _sourceSharedIdentityEntryMaps =
new Dictionary<ITable, SharedIdentityMap>();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public MigrationsModelDiffer(
[NotNull] IRelationalTypeMappingSource typeMappingSource,
[NotNull] IMigrationsAnnotationProvider migrationsAnnotations,
[NotNull] IChangeDetector changeDetector,
[NotNull] IUpdateAdapterFactory updateAdapterFactory,
[NotNull] CommandBatchPreparerDependencies commandBatchPreparerDependencies)
{
Check.NotNull(typeMappingSource, nameof(typeMappingSource));
Check.NotNull(migrationsAnnotations, nameof(migrationsAnnotations));
Check.NotNull(changeDetector, nameof(changeDetector));
Check.NotNull(updateAdapterFactory, nameof(updateAdapterFactory));
Check.NotNull(commandBatchPreparerDependencies, nameof(commandBatchPreparerDependencies));
TypeMappingSource = typeMappingSource;
MigrationsAnnotations = migrationsAnnotations;
ChangeDetector = changeDetector;
UpdateAdapterFactory = updateAdapterFactory;
CommandBatchPreparerDependencies = commandBatchPreparerDependencies;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IRelationalTypeMappingSource TypeMappingSource { get; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IMigrationsAnnotationProvider MigrationsAnnotations { get; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IUpdateAdapterFactory UpdateAdapterFactory { get; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual CommandBatchPreparerDependencies CommandBatchPreparerDependencies { get; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IChangeDetector ChangeDetector { get; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual bool HasDifferences(IRelationalModel source, IRelationalModel target)
=> Diff(source, target, new DiffContext()).Any();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual IReadOnlyList<MigrationOperation> GetDifferences(IRelationalModel source, IRelationalModel target)
{
var diffContext = new DiffContext();
return Sort(Diff(source, target, diffContext), diffContext);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IReadOnlyList<MigrationOperation> Sort(
[NotNull] IEnumerable<MigrationOperation> operations,
[NotNull] DiffContext diffContext)
{
Check.NotNull(operations, nameof(operations));
var dropForeignKeyOperations = new List<MigrationOperation>();
var dropOperations = new List<MigrationOperation>();
var dropColumnOperations = new List<MigrationOperation>();
var dropTableOperations = new List<DropTableOperation>();
var ensureSchemaOperations = new List<MigrationOperation>();
var createSequenceOperations = new List<MigrationOperation>();
var createTableOperations = new List<CreateTableOperation>();
var alterDatabaseOperations = new List<MigrationOperation>();
var alterTableOperations = new List<MigrationOperation>();
var columnOperations = new List<MigrationOperation>();
var computedColumnOperations = new List<MigrationOperation>();
var alterOperations = new List<MigrationOperation>();
var restartSequenceOperations = new List<MigrationOperation>();
var constraintOperations = new List<MigrationOperation>();
var renameOperations = new List<MigrationOperation>();
var renameTableOperations = new List<MigrationOperation>();
var sourceDataOperations = new List<MigrationOperation>();
var targetDataOperations = new List<MigrationOperation>();
var leftovers = new List<MigrationOperation>();
foreach (var operation in operations)
{
var type = operation.GetType();
if (type == typeof(DropForeignKeyOperation))
{
dropForeignKeyOperations.Add(operation);
}
else if (_dropOperationTypes.Contains(type))
{
dropOperations.Add(operation);
}
else if (type == typeof(DropColumnOperation))
{
dropColumnOperations.Add(operation);
}
else if (type == typeof(DropTableOperation))
{
dropTableOperations.Add((DropTableOperation)operation);
}
else if (type == typeof(EnsureSchemaOperation))
{
ensureSchemaOperations.Add(operation);
}
else if (type == typeof(CreateSequenceOperation))
{
createSequenceOperations.Add(operation);
}
else if (type == typeof(CreateTableOperation))
{
createTableOperations.Add((CreateTableOperation)operation);
}
else if (type == typeof(AlterDatabaseOperation))
{
alterDatabaseOperations.Add(operation);
}
else if (type == typeof(AlterTableOperation))
{
alterTableOperations.Add(operation);
}
else if (_columnOperationTypes.Contains(type))
{
if (string.IsNullOrWhiteSpace(((ColumnOperation)operation).ComputedColumnSql))
{
columnOperations.Add(operation);
}
else
{
computedColumnOperations.Add(operation);
}
}
else if (_alterOperationTypes.Contains(type))
{
alterOperations.Add(operation);
}
else if (type == typeof(RestartSequenceOperation))
{
restartSequenceOperations.Add(operation);
}
else if (_constraintOperationTypes.Contains(type))
{
constraintOperations.Add(operation);
}
else if (_renameOperationTypes.Contains(type))
{
renameOperations.Add(operation);
}
else if (type == typeof(RenameTableOperation))
{
renameTableOperations.Add(operation);
}
else if (type == typeof(DeleteDataOperation))
{
sourceDataOperations.Add(operation);
}
else if (type == typeof(InsertDataOperation)
|| type == typeof(UpdateDataOperation))
{
targetDataOperations.Add(operation);
}
else
{
leftovers.Add(operation);
Check.DebugAssert(false, "Unexpected operation type: " + operation.GetType());
}
}
var createTableGraph = new Multigraph<CreateTableOperation, AddForeignKeyOperation>();
createTableGraph.AddVertices(createTableOperations);
foreach (var createTableOperation in createTableOperations)
{
foreach (var addForeignKeyOperation in createTableOperation.ForeignKeys)
{
if (addForeignKeyOperation.Table == addForeignKeyOperation.PrincipalTable
&& addForeignKeyOperation.Schema == addForeignKeyOperation.PrincipalSchema)
{
continue;
}
var principalCreateTableOperation = createTableOperations.FirstOrDefault(
o => o.Name == addForeignKeyOperation.PrincipalTable
&& o.Schema == addForeignKeyOperation.PrincipalSchema);
if (principalCreateTableOperation != null)
{
createTableGraph.AddEdge(principalCreateTableOperation, createTableOperation, addForeignKeyOperation);
}
}
}
createTableOperations = createTableGraph.TopologicalSort(
(principalCreateTableOperation, createTableOperation, cyclicAddForeignKeyOperations) =>
{
foreach (var cyclicAddForeignKeyOperation in cyclicAddForeignKeyOperations)
{
createTableOperation.ForeignKeys.Remove(cyclicAddForeignKeyOperation);
constraintOperations.Add(cyclicAddForeignKeyOperation);
}
return true;
}).ToList();
var dropTableGraph = new Multigraph<DropTableOperation, IForeignKeyConstraint>();
dropTableGraph.AddVertices(dropTableOperations);
foreach (var dropTableOperation in dropTableOperations)
{
var table = diffContext.FindTable(dropTableOperation);
foreach (var foreignKey in table.ForeignKeyConstraints)
{
var principalDropTableOperation = diffContext.FindDrop(foreignKey.PrincipalTable);
if (principalDropTableOperation != null
&& principalDropTableOperation != dropTableOperation)
{
dropTableGraph.AddEdge(dropTableOperation, principalDropTableOperation, foreignKey);
}
}
}
var newDiffContext = new DiffContext();
dropTableOperations = dropTableGraph.TopologicalSort(
(dropTableOperation, principalDropTableOperation, foreignKeys) =>
{
dropForeignKeyOperations.AddRange(foreignKeys.SelectMany(c => Remove(c, newDiffContext)));
return true;
}).ToList();
return dropForeignKeyOperations
.Concat(dropTableOperations)
.Concat(dropOperations)
.Concat(sourceDataOperations)
.Concat(dropColumnOperations)
.Concat(ensureSchemaOperations)
.Concat(renameTableOperations)
.Concat(renameOperations)
.Concat(alterDatabaseOperations)
.Concat(createSequenceOperations)
.Concat(alterTableOperations)
.Concat(columnOperations)
.Concat(computedColumnOperations)
.Concat(alterOperations)
.Concat(restartSequenceOperations)
.Concat(createTableOperations)
.Concat(targetDataOperations)
.Concat(constraintOperations)
.Concat(leftovers)
.ToList();
}
#region IModel
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Diff(
[CanBeNull] IRelationalModel source,
[CanBeNull] IRelationalModel target,
[NotNull] DiffContext diffContext)
{
var operations = Enumerable.Empty<MigrationOperation>();
if (source != null && target != null)
{
var sourceMigrationsAnnotations = source.GetAnnotations();
var targetMigrationsAnnotations = target.GetAnnotations();
if (source.Collation != target.Collation
|| HasDifferences(sourceMigrationsAnnotations, targetMigrationsAnnotations))
{
var alterDatabaseOperation = new AlterDatabaseOperation
{
Collation = target.Collation,
OldDatabase = { Collation = source.Collation }
};
alterDatabaseOperation.AddAnnotations(targetMigrationsAnnotations);
alterDatabaseOperation.OldDatabase.AddAnnotations(sourceMigrationsAnnotations);
operations = new[] { alterDatabaseOperation };
}
operations = operations
.Concat(Diff(GetSchemas(source), GetSchemas(target), diffContext))
.Concat(Diff(source.Tables, target.Tables, diffContext))
.Concat(Diff(source.Sequences, target.Sequences, diffContext))
.Concat(
Diff(
source.Tables.SelectMany(s => s.ForeignKeyConstraints),
target.Tables.SelectMany(t => t.ForeignKeyConstraints),
diffContext));
}
else
{
operations = target != null
? Add(target, diffContext)
: source != null
? Remove(source, diffContext)
: Enumerable.Empty<MigrationOperation>();
}
return operations.Concat(GetDataOperations(source, target, diffContext));
}
private IEnumerable<MigrationOperation> DiffAnnotations(
IRelationalModel source,
IRelationalModel target)
{
var sourceMigrationsAnnotations = source?.GetAnnotations().ToList();
var targetMigrationsAnnotations = target?.GetAnnotations().ToList();
if (source == null)
{
if (targetMigrationsAnnotations?.Count > 0)
{
var alterDatabaseOperation = new AlterDatabaseOperation();
alterDatabaseOperation.AddAnnotations(targetMigrationsAnnotations);
yield return alterDatabaseOperation;
}
yield break;
}
if (target == null)
{
sourceMigrationsAnnotations = MigrationsAnnotations.ForRemove(source).ToList();
if (sourceMigrationsAnnotations.Count > 0)
{
var alterDatabaseOperation = new AlterDatabaseOperation();
alterDatabaseOperation.OldDatabase.AddAnnotations(sourceMigrationsAnnotations);
yield return alterDatabaseOperation;
}
yield break;
}
if (HasDifferences(sourceMigrationsAnnotations, targetMigrationsAnnotations))
{
var alterDatabaseOperation = new AlterDatabaseOperation();
alterDatabaseOperation.AddAnnotations(targetMigrationsAnnotations);
alterDatabaseOperation.OldDatabase.AddAnnotations(sourceMigrationsAnnotations);
yield return alterDatabaseOperation;
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Add([NotNull] IRelationalModel target, [NotNull] DiffContext diffContext)
=> DiffAnnotations(null, target)
.Concat(GetSchemas(target).SelectMany(t => Add(t, diffContext)))
.Concat(target.Tables.SelectMany(t => Add(t, diffContext)))
.Concat(target.Sequences.SelectMany(t => Add(t, diffContext)))
.Concat(target.Tables.SelectMany(t => t.ForeignKeyConstraints).SelectMany(k => Add(k, diffContext)));
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Remove([NotNull] IRelationalModel source, [NotNull] DiffContext diffContext)
=> DiffAnnotations(source, null)
.Concat(source.Tables.SelectMany(t => Remove(t, diffContext)))
.Concat(source.Sequences.SelectMany(t => Remove(t, diffContext)));
#endregion
#region Schema
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Diff(
[NotNull] IEnumerable<string> source, [NotNull] IEnumerable<string> target, [NotNull] DiffContext diffContext)
=> DiffCollection(
source,
target,
diffContext,
Diff,
Add,
Remove,
(s, t, c) => s == t);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Diff(
[NotNull] string source, [NotNull] string target, [NotNull] DiffContext diffContext)
=> Enumerable.Empty<MigrationOperation>();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Add([NotNull] string target, [NotNull] DiffContext diffContext)
{
yield return new EnsureSchemaOperation { Name = target };
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Remove([NotNull] string source, [NotNull] DiffContext diffContext)
=> Enumerable.Empty<MigrationOperation>();
#endregion
#region IEntityType
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Diff(
[NotNull] IEnumerable<ITable> source,
[NotNull] IEnumerable<ITable> target,
[NotNull] DiffContext diffContext)
=> DiffCollection(
source,
target,
diffContext,
Diff,
Add,
Remove,
(s, t, c) => string.Equals(
s.Schema,
t.Schema,
StringComparison.OrdinalIgnoreCase)
&& string.Equals(
s.Name,
t.Name,
StringComparison.OrdinalIgnoreCase),
(s, t, c) => string.Equals(
s.Name,
t.Name,
StringComparison.OrdinalIgnoreCase),
(s, t, c) => string.Equals(GetMainType(s).Name, GetMainType(t).Name, StringComparison.OrdinalIgnoreCase),
(s, t, c) => s.EntityTypeMappings.Any(
se => t.EntityTypeMappings.Any(
te => string.Equals(se.EntityType.Name, te.EntityType.Name, StringComparison.OrdinalIgnoreCase))));
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Diff(
[NotNull] ITable source,
[NotNull] ITable target,
[NotNull] DiffContext diffContext)
{
if (source.IsExcludedFromMigrations
&& target.IsExcludedFromMigrations)
{
yield break;
}
if (source.Schema != target.Schema
|| source.Name != target.Name)
{
yield return new RenameTableOperation
{
Schema = source.Schema,
Name = source.Name,
NewSchema = target.Schema,
NewName = target.Name
};
}
var sourceMigrationsAnnotations = source.GetAnnotations();
var targetMigrationsAnnotations = target.GetAnnotations();
if (source.Comment != target.Comment
|| HasDifferences(sourceMigrationsAnnotations, targetMigrationsAnnotations))
{
var alterTableOperation = new AlterTableOperation
{
Name = target.Name,
Schema = target.Schema,
Comment = target.Comment,
OldTable = { Comment = source.Comment }
};
alterTableOperation.AddAnnotations(targetMigrationsAnnotations);
alterTableOperation.OldTable.AddAnnotations(sourceMigrationsAnnotations);
yield return alterTableOperation;
}
var operations = Diff(source.Columns, target.Columns, diffContext)
.Concat(Diff(source.UniqueConstraints, target.UniqueConstraints, diffContext))
.Concat(Diff(source.Indexes, target.Indexes, diffContext))
.Concat(Diff(source.CheckConstraints, target.CheckConstraints, diffContext));
foreach (var operation in operations)
{
yield return operation;
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Add(
[NotNull] ITable target, [NotNull] DiffContext diffContext)
{
if (target.IsExcludedFromMigrations)
{
yield break;
}
var createTableOperation = new CreateTableOperation
{
Schema = target.Schema,
Name = target.Name,
Comment = target.Comment
};
createTableOperation.AddAnnotations(target.GetAnnotations());
createTableOperation.Columns.AddRange(
GetSortedColumns(target).SelectMany(p => Add(p, diffContext, inline: true)).Cast<AddColumnOperation>());
var primaryKey = target.PrimaryKey;
if (primaryKey != null)
{
createTableOperation.PrimaryKey = Add(primaryKey, diffContext).Cast<AddPrimaryKeyOperation>().Single();
}
createTableOperation.UniqueConstraints.AddRange(
target.UniqueConstraints.Where(c => !c.GetIsPrimaryKey()).SelectMany(c => Add(c, diffContext))
.Cast<AddUniqueConstraintOperation>());
createTableOperation.CheckConstraints.AddRange(
target.CheckConstraints.SelectMany(c => Add(c, diffContext))
.Cast<CreateCheckConstraintOperation>());
diffContext.AddCreate(target, createTableOperation);
yield return createTableOperation;
foreach (var operation in target.Indexes.SelectMany(i => Add(i, diffContext)))
{
yield return operation;
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Remove(
[NotNull] ITable source, [NotNull] DiffContext diffContext)
{
if (source.IsExcludedFromMigrations)
{
yield break;
}
var operation = new DropTableOperation { Schema = source.Schema, Name = source.Name };
operation.AddAnnotations(MigrationsAnnotations.ForRemove(source));
diffContext.AddDrop(source, operation);
yield return operation;
}
private static IEnumerable<IColumn> GetSortedColumns(ITable table)
{
var columns = table.Columns.ToHashSet();
var sortedColumns = new List<IColumn>(columns.Count);
foreach (var property in GetSortedProperties(GetMainType(table).GetRootType(), table))
{
var column = property.GetTableColumnMappings().FirstOrDefault(m => m.TableMapping.Table == table)?.Column;
if (columns.Remove(column))
{
sortedColumns.Add(column);
}
}
return sortedColumns;
}
private static IEnumerable<IProperty> GetSortedProperties(IEntityType entityType, ITable table)
{
var leastPriorityProperties = new List<IProperty>();
var leastPriorityPrimaryKeyProperties = new List<IProperty>();
var primaryKeyPropertyGroups = new Dictionary<PropertyInfo, IProperty>();
var groups = new Dictionary<PropertyInfo, List<IProperty>>();
var unorderedGroups = new Dictionary<PropertyInfo, SortedDictionary<int, IProperty>>();
var types = new Dictionary<Type, SortedDictionary<int, PropertyInfo>>();
foreach (var property in entityType.GetDeclaredProperties())
{
var clrProperty = property.PropertyInfo;
if (clrProperty == null
|| clrProperty.IsIndexerProperty())
{
if (property.IsPrimaryKey())
{
leastPriorityPrimaryKeyProperties.Add(property);
continue;
}
var foreignKey = property.GetContainingForeignKeys()
.FirstOrDefault(fk => fk.DependentToPrincipal?.PropertyInfo != null);
if (foreignKey == null)
{
leastPriorityProperties.Add(property);
continue;
}
clrProperty = foreignKey.DependentToPrincipal.PropertyInfo;
var groupIndex = foreignKey.Properties.IndexOf(property);
unorderedGroups.GetOrAddNew(clrProperty).Add(groupIndex, property);
}
else
{
if (property.IsPrimaryKey())
{
primaryKeyPropertyGroups.Add(clrProperty, property);
}
groups.Add(
clrProperty, new List<IProperty> { property });
}
var clrType = clrProperty.DeclaringType;
var index = clrType.GetTypeInfo().DeclaredProperties
.IndexOf(clrProperty, PropertyInfoEqualityComparer.Instance);
Check.DebugAssert(clrType != null, "clrType is null");
types.GetOrAddNew(clrType)[index] = clrProperty;
}
foreach (var group in unorderedGroups)
{
groups.Add(group.Key, group.Value.Values.ToList());
}
foreach (var linkingForeignKey in table.GetReferencingRowInternalForeignKeys(entityType))
{
var linkingNavigationProperty = linkingForeignKey.PrincipalToDependent?.PropertyInfo;
var properties = GetSortedProperties(linkingForeignKey.DeclaringEntityType, table).ToList();
if (linkingNavigationProperty == null)
{
leastPriorityProperties.AddRange(properties);
continue;
}
groups.Add(linkingNavigationProperty, properties);
var clrType = linkingNavigationProperty.DeclaringType;
var index = clrType.GetTypeInfo().DeclaredProperties
.IndexOf(linkingNavigationProperty, PropertyInfoEqualityComparer.Instance);
Check.DebugAssert(clrType != null, "clrType is null");
types.GetOrAddNew(clrType)[index] = linkingNavigationProperty;
}
var graph = new Multigraph<Type, object>();
graph.AddVertices(types.Keys);
foreach (var left in types.Keys)
{
var found = false;
foreach (var baseType in left.GetBaseTypes())
{
foreach (var right in types.Keys)
{
if (right == baseType)
{
graph.AddEdge(right, left, null);
found = true;
break;
}
}
if (found)
{
break;
}
}
}
var sortedPropertyInfos = graph.TopologicalSort().SelectMany(e => types[e].Values).ToList();
return sortedPropertyInfos
.Select(pi => primaryKeyPropertyGroups.ContainsKey(pi) ? primaryKeyPropertyGroups[pi] : null)
.Where(e => e != null)
.Concat(leastPriorityPrimaryKeyProperties)
.Concat(sortedPropertyInfos.Where(pi => !primaryKeyPropertyGroups.ContainsKey(pi)).SelectMany(p => groups[p]))
.Concat(leastPriorityProperties)
.Concat(entityType.GetDirectlyDerivedTypes().SelectMany(et => GetSortedProperties(et, table)));
}
private sealed class PropertyInfoEqualityComparer : IEqualityComparer<PropertyInfo>
{
private PropertyInfoEqualityComparer()
{
}
public static readonly PropertyInfoEqualityComparer Instance = new PropertyInfoEqualityComparer();
public bool Equals(PropertyInfo x, PropertyInfo y)
=> x.IsSameAs(y);
public int GetHashCode(PropertyInfo obj)
=> throw new NotImplementedException();
}
#endregion
#region IProperty
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Diff(
[NotNull] IEnumerable<IColumn> source,
[NotNull] IEnumerable<IColumn> target,
[NotNull] DiffContext diffContext)
=> DiffCollection(
source,
target,
diffContext,
Diff,
(t, c) => Add(t, c),
Remove,
(s, t, c) => string.Equals(s.Name, t.Name, StringComparison.OrdinalIgnoreCase),
(s, t, c) => s.PropertyMappings.Any(sm =>
t.PropertyMappings.Any(tm =>
string.Equals(sm.Property.Name, tm.Property.Name, StringComparison.OrdinalIgnoreCase)
&& EntityTypePathEquals(sm.Property.DeclaringEntityType, tm.Property.DeclaringEntityType, c))),
(s, t, c) => s.PropertyMappings.Any(sm =>
t.PropertyMappings.Any(tm =>
string.Equals(sm.Property.Name, tm.Property.Name, StringComparison.OrdinalIgnoreCase))),
(s, t, c) => ColumnStructureEquals(s, t)
&& s.PropertyMappings.Any(sm =>
t.PropertyMappings.Any(tm =>
string.Equals(sm.Property.Name, tm.Property.Name, StringComparison.OrdinalIgnoreCase)
&& EntityTypePathEquals(sm.Property.DeclaringEntityType, tm.Property.DeclaringEntityType, c))),
(s, t, c) => ColumnStructureEquals(s, t));
private bool ColumnStructureEquals(IColumn source, IColumn target)
=> source.StoreType == target.StoreType
&& source.IsRowVersion == target.IsRowVersion
&& source.IsNullable == target.IsNullable
&& source.Precision == target.Precision
&& source.Scale == target.Scale
&& source.IsUnicode == target.IsUnicode
&& source.MaxLength == target.MaxLength
&& source.IsFixedLength == target.IsFixedLength
&& source.Collation == target.Collation
&& source.Comment == target.Comment
&& source.IsStored == target.IsStored
&& source.ComputedColumnSql == target.ComputedColumnSql
&& Equals(source.DefaultValue, target.DefaultValue)
&& source.DefaultValueSql == target.DefaultValueSql;
private static bool EntityTypePathEquals(IEntityType source, IEntityType target, DiffContext diffContext)
{
var sourceTable = diffContext.GetTable(source);
var targetTable = diffContext.GetTable(target);
if (sourceTable.EntityTypeMappings.Count() == 1
&& targetTable.EntityTypeMappings.Count() == 1)
{
return true;
}
if (!string.Equals(source.Name, target.Name))
{
return false;
}
if (!string.Equals(
GetDefiningNavigationName(source),
GetDefiningNavigationName(target)))
{
return false;
}
var nextSource = source.DefiningEntityType;
var nextTarget = target.DefiningEntityType;
return (nextSource == null && nextTarget == null)
|| (nextSource != null && nextTarget != null
&& EntityTypePathEquals(nextSource, nextTarget, diffContext));
}
private static string GetDefiningNavigationName(IEntityType entityType)
{
if (entityType.DefiningNavigationName != null)
{
return entityType.DefiningNavigationName;
}
var primaryKey = entityType.BaseType == null ? entityType.FindPrimaryKey() : null;
if (primaryKey != null)
{
var definingForeignKey = entityType
.FindForeignKeys(primaryKey.Properties)
.FirstOrDefault(fk => fk.PrincipalEntityType.GetTableName() == entityType.GetTableName());
if (definingForeignKey?.DependentToPrincipal != null)
{
return definingForeignKey.DependentToPrincipal.Name;
}
}
return entityType.Name;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Diff(
[NotNull] IColumn source, [NotNull] IColumn target, [NotNull] DiffContext diffContext)
{
var sourceMapping = source.PropertyMappings.First();
var targetMapping = target.PropertyMappings.First();
var table = target.Table;
if (source.Name != target.Name)
{
yield return new RenameColumnOperation
{
Schema = table.Schema,
Table = table.Name,
Name = source.Name,
NewName = target.Name
};
}
var sourceTypeMapping = sourceMapping.TypeMapping;
var targetTypeMapping = targetMapping.TypeMapping;
var sourceColumnType = source.StoreType ?? sourceTypeMapping.StoreType;
var targetColumnType = target.StoreType ?? targetTypeMapping.StoreType;
var sourceMigrationsAnnotations = source.GetAnnotations();
var targetMigrationsAnnotations = target.GetAnnotations();
var isNullableChanged = source.IsNullable != target.IsNullable;
var columnTypeChanged = sourceColumnType != targetColumnType;
if (isNullableChanged
|| columnTypeChanged
|| source.DefaultValueSql != target.DefaultValueSql
|| source.ComputedColumnSql != target.ComputedColumnSql
|| source.IsStored != target.IsStored
|| !Equals(source.DefaultValue, target.DefaultValue)
|| source.Comment != target.Comment
|| source.Collation != target.Collation
|| HasDifferences(sourceMigrationsAnnotations, targetMigrationsAnnotations))
{
var isDestructiveChange = isNullableChanged && source.IsNullable
// TODO: Detect type narrowing
|| columnTypeChanged;
var alterColumnOperation = new AlterColumnOperation
{
Schema = table.Schema,
Table = table.Name,
Name = target.Name,
IsDestructiveChange = isDestructiveChange
};
Initialize(
alterColumnOperation, target, targetTypeMapping,
target.IsNullable, targetMigrationsAnnotations, inline: true);
Initialize(
alterColumnOperation.OldColumn, source, sourceTypeMapping,
source.IsNullable, sourceMigrationsAnnotations, inline: true);
yield return alterColumnOperation;
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Add(
[NotNull] IColumn target,
[NotNull] DiffContext diffContext,
bool inline = false)
{
var table = target.Table;
var operation = new AddColumnOperation
{
Schema = table.Schema,
Table = table.Name,
Name = target.Name
};
var targetMapping = target.PropertyMappings.First();
var targetTypeMapping = targetMapping.TypeMapping;
Initialize(
operation, target, targetTypeMapping, target.IsNullable,
target.GetAnnotations(), inline);
yield return operation;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Remove([NotNull] IColumn source, [NotNull] DiffContext diffContext)
{
var table = source.Table;
var operation = new DropColumnOperation
{
Schema = table.Schema,
Table = table.Name,
Name = source.Name
};
operation.AddAnnotations(MigrationsAnnotations.ForRemove(source));
yield return operation;
}
private void Initialize(
ColumnOperation columnOperation,
IColumn column,
RelationalTypeMapping typeMapping,
bool isNullable,
IEnumerable<IAnnotation> migrationsAnnotations,
bool inline = false)
{
var property = column.PropertyMappings.First().Property;
var valueConverter = GetValueConverter(property, typeMapping);
columnOperation.ClrType
= (valueConverter?.ProviderClrType
?? typeMapping.ClrType).UnwrapNullableType();
columnOperation.ColumnType = column.StoreType;
columnOperation.MaxLength = column.MaxLength;
columnOperation.Precision = column.Precision;
columnOperation.Scale = column.Scale;
columnOperation.IsUnicode = column.IsUnicode;
columnOperation.IsFixedLength = column.IsFixedLength;
columnOperation.IsRowVersion = column.IsRowVersion;
columnOperation.IsNullable = isNullable;
var defaultValue = column.DefaultValue;
columnOperation.DefaultValue = (defaultValue == DBNull.Value ? null : defaultValue)
?? (inline || isNullable
? null
: GetDefaultValue(columnOperation.ClrType));
columnOperation.DefaultValueSql = column.DefaultValueSql;
columnOperation.ComputedColumnSql = column.ComputedColumnSql;
columnOperation.IsStored = column.IsStored;
columnOperation.Comment = column.Comment;
columnOperation.Collation = column.Collation;
columnOperation.AddAnnotations(migrationsAnnotations);
}
#endregion
#region IKey
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Diff(
[NotNull] IEnumerable<IUniqueConstraint> source,
[NotNull] IEnumerable<IUniqueConstraint> target,
[NotNull] DiffContext diffContext)
=> DiffCollection(
source,
target,
diffContext,
Diff,
Add,
Remove,
(s, t, c) => s.Name == t.Name
&& s.Columns.Select(p => p.Name).SequenceEqual(
t.Columns.Select(p => c.FindSource(p)?.Name))
&& s.GetIsPrimaryKey() == t.GetIsPrimaryKey()
&& !HasDifferences(s.GetAnnotations(), t.GetAnnotations()));
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Diff(
[NotNull] IUniqueConstraint source,
[NotNull] IUniqueConstraint target,
[NotNull] DiffContext diffContext)
=> Enumerable.Empty<MigrationOperation>();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Add([NotNull] IUniqueConstraint target, [NotNull] DiffContext diffContext)
{
var targetTable = target.Table;
var columns = target.Columns;
MigrationOperation operation;
if (target.GetIsPrimaryKey())
{
operation = new AddPrimaryKeyOperation
{
Schema = targetTable.Schema,
Table = targetTable.Name,
Name = target.Name,
Columns = columns.Select(c => c.Name).ToArray()
};
}
else
{
operation = new AddUniqueConstraintOperation
{
Schema = targetTable.Schema,
Table = targetTable.Name,
Name = target.Name,
Columns = columns.Select(c => c.Name).ToArray()
};
}
operation.AddAnnotations(target.GetAnnotations());
yield return operation;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Remove(
[NotNull] IUniqueConstraint source,
[NotNull] DiffContext diffContext)
{
var table = source.Table;
MigrationOperation operation;
if (source.GetIsPrimaryKey())
{
operation = new DropPrimaryKeyOperation
{
Schema = table.Schema,
Table = table.Name,
Name = source.Name
};
}
else
{
operation = new DropUniqueConstraintOperation
{
Schema = table.Schema,
Table = table.Name,
Name = source.Name
};
}
operation.AddAnnotations(MigrationsAnnotations.ForRemove(source));
yield return operation;
}
#endregion
#region IForeignKey
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Diff(
[NotNull] IEnumerable<IForeignKeyConstraint> source,
[NotNull] IEnumerable<IForeignKeyConstraint> target,
[NotNull] DiffContext diffContext)
=> DiffCollection(
source,
target,
diffContext,
Diff,
Add,
Remove,
(s, t, context) => s.Name == t.Name
&& s.Columns.Select(c => c.Name).SequenceEqual(
t.Columns.Select(c => context.FindSource(c)?.Name))
&& s.PrincipalTable == context.FindSource(t.PrincipalTable)
&& s.PrincipalColumns.Select(c => c.Name).SequenceEqual(
t.PrincipalColumns.Select(c => context.FindSource(c)?.Name))
&& s.OnDeleteAction == t.OnDeleteAction
&& !HasDifferences(s.GetAnnotations(), t.GetAnnotations()));
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Diff(
[NotNull] IForeignKeyConstraint source, [NotNull] IForeignKeyConstraint target, [NotNull] DiffContext diffContext)
=> Enumerable.Empty<MigrationOperation>();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Add([NotNull] IForeignKeyConstraint target, [NotNull] DiffContext diffContext)
{
var targetTable = target.Table;
if (targetTable.IsExcludedFromMigrations)
{
yield break;
}
var targetPrincipleTable = target.PrincipalTable;
var operation = new AddForeignKeyOperation
{
Schema = targetTable.Schema,
Table = targetTable.Name,
Name = target.Name,
Columns = target.Columns.Select(c => c.Name).ToArray(),
PrincipalSchema = targetPrincipleTable.Schema,
PrincipalTable = targetPrincipleTable.Name,
PrincipalColumns = target.PrincipalColumns.Select(c => c.Name).ToArray(),
OnDelete = target.OnDeleteAction
};
operation.AddAnnotations(target.GetAnnotations());
var createTableOperation = diffContext.FindCreate(targetTable);
if (createTableOperation != null)
{
createTableOperation.ForeignKeys.Add(operation);
}
else
{
yield return operation;
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Remove([NotNull] IForeignKeyConstraint source, [NotNull] DiffContext diffContext)
{
var sourceTable = source.Table;
var dropTableOperation = diffContext.FindDrop(sourceTable);
if (dropTableOperation == null)
{
var operation = new DropForeignKeyOperation
{
Schema = sourceTable.Schema,
Table = sourceTable.Name,
Name = source.Name
};
operation.AddAnnotations(MigrationsAnnotations.ForRemove(source));
yield return operation;
}
}
#endregion
#region IIndex
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Diff(
[NotNull] IEnumerable<ITableIndex> source,
[NotNull] IEnumerable<ITableIndex> target,
[NotNull] DiffContext diffContext)
=> DiffCollection(
source,
target,
diffContext,
Diff,
Add,
Remove,
(s, t, c) => string.Equals(s.Name, t.Name, StringComparison.OrdinalIgnoreCase)
&& IndexStructureEquals(s, t, c),
(s, t, c) => IndexStructureEquals(s, t, c));
private bool IndexStructureEquals(ITableIndex source, ITableIndex target, DiffContext diffContext)
=> source.IsUnique == target.IsUnique
&& source.Filter == target.Filter
&& !HasDifferences(source.GetAnnotations(), target.GetAnnotations())
&& source.Columns.Select(p => p.Name).SequenceEqual(
target.Columns.Select(p => diffContext.FindSource(p)?.Name));
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Diff(
[NotNull] ITableIndex source,
[NotNull] ITableIndex target,
[NotNull] DiffContext diffContext)
{
var targetTable = target.Table;
var sourceName = source.Name;
var targetName = target.Name;
if (sourceName != targetName)
{
yield return new RenameIndexOperation
{
Schema = targetTable.Schema,
Table = targetTable.Name,
Name = sourceName,
NewName = targetName
};
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Add(
[NotNull] ITableIndex target,
[NotNull] DiffContext diffContext)
{
var targetTable = target.Table;
var operation = new CreateIndexOperation
{
Name = target.Name,
Schema = targetTable.Schema,
Table = targetTable.Name,
Columns = target.Columns.Select(c => c.Name).ToArray(),
IsUnique = target.IsUnique,
Filter = target.Filter
};
operation.AddAnnotations(target.GetAnnotations());
yield return operation;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Remove([NotNull] ITableIndex source, [NotNull] DiffContext diffContext)
{
var sourceTable = source.Table;
var operation = new DropIndexOperation
{
Name = source.Name,
Schema = sourceTable.Schema,
Table = sourceTable.Name
};
operation.AddAnnotations(MigrationsAnnotations.ForRemove(source));
yield return operation;
}
#endregion
#region ICheckConstraint
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Diff(
[NotNull] IEnumerable<ICheckConstraint> source,
[NotNull] IEnumerable<ICheckConstraint> target,
[NotNull] DiffContext diffContext)
=> DiffCollection(
source,
target,
diffContext,
Diff,
Add,
Remove,
(s, t, c) => c.GetTable(s.EntityType) == c.FindSource(c.GetTable(t.EntityType))
&& string.Equals(s.Name, t.Name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(s.Sql, t.Sql, StringComparison.OrdinalIgnoreCase));
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Diff(
[NotNull] ICheckConstraint source, [NotNull] ICheckConstraint target, [NotNull] DiffContext diffContext)
=> Enumerable.Empty<MigrationOperation>();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Add([NotNull] ICheckConstraint target, [NotNull] DiffContext diffContext)
{
var targetEntityType = target.EntityType;
var operation = new CreateCheckConstraintOperation
{
Name = target.Name,
Sql = target.Sql,
Schema = targetEntityType.GetSchema(),
Table = targetEntityType.GetTableName()
};
operation.Sql = target.Sql;
operation.AddAnnotations(target.GetAnnotations());
yield return operation;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Remove([NotNull] ICheckConstraint source, [NotNull] DiffContext diffContext)
{
var sourceEntityType = source.EntityType;
var operation = new DropCheckConstraintOperation
{
Name = source.Name,
Schema = sourceEntityType.GetSchema(),
Table = sourceEntityType.GetTableName()
};
operation.AddAnnotations(MigrationsAnnotations.ForRemove(source));
yield return operation;
}
#endregion
#region ISequence
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Diff(
[NotNull] IEnumerable<ISequence> source,
[NotNull] IEnumerable<ISequence> target,
[NotNull] DiffContext diffContext)
=> DiffCollection(
source,
target,
diffContext,
Diff,
Add,
Remove,
(s, t, c) => string.Equals(s.Schema, t.Schema, StringComparison.OrdinalIgnoreCase)
&& string.Equals(s.Name, t.Name, StringComparison.OrdinalIgnoreCase)
&& s.ClrType == t.ClrType,
(s, t, c) => string.Equals(s.Name, t.Name, StringComparison.OrdinalIgnoreCase)
&& s.ClrType == t.ClrType);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Diff(
[NotNull] ISequence source, [NotNull] ISequence target, [NotNull] DiffContext diffContext)
{
if (source.Schema != target.Schema
|| source.Name != target.Name)
{
yield return new RenameSequenceOperation
{
Schema = source.Schema,
Name = source.Name,
NewSchema = target.Schema,
NewName = target.Name
};
}
if (source.StartValue != target.StartValue)
{
yield return new RestartSequenceOperation
{
Schema = target.Schema,
Name = target.Name,
StartValue = target.StartValue
};
}
var sourceMigrationsAnnotations = source.GetAnnotations();
var targetMigrationsAnnotations = target.GetAnnotations();
if (source.IncrementBy != target.IncrementBy
|| source.MaxValue != target.MaxValue
|| source.MinValue != target.MinValue
|| source.IsCyclic != target.IsCyclic
|| HasDifferences(sourceMigrationsAnnotations, targetMigrationsAnnotations))
{
var alterSequenceOperation = new AlterSequenceOperation { Schema = target.Schema, Name = target.Name };
Initialize(alterSequenceOperation, target, targetMigrationsAnnotations);
Initialize(alterSequenceOperation.OldSequence, source, sourceMigrationsAnnotations);
yield return alterSequenceOperation;
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Add([NotNull] ISequence target, [NotNull] DiffContext diffContext)
{
var operation = new CreateSequenceOperation
{
Schema = target.Schema,
Name = target.Name,
ClrType = target.ClrType,
StartValue = target.StartValue
};
yield return Initialize(operation, target, target.GetAnnotations());
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> Remove([NotNull] ISequence source, [NotNull] DiffContext diffContext)
{
var operation = new DropSequenceOperation { Schema = source.Schema, Name = source.Name };
operation.AddAnnotations(MigrationsAnnotations.ForRemove(source));
yield return operation;
}
private static SequenceOperation Initialize(
SequenceOperation sequenceOperation,
ISequence sequence,
IEnumerable<IAnnotation> migrationsAnnotations)
{
sequenceOperation.IncrementBy = sequence.IncrementBy;
sequenceOperation.MinValue = sequence.MinValue;
sequenceOperation.MaxValue = sequence.MaxValue;
sequenceOperation.IsCyclic = sequence.IsCyclic;
sequenceOperation.AddAnnotations(migrationsAnnotations);
return sequenceOperation;
}
#endregion
#region Data
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual void TrackData(
[CanBeNull] IRelationalModel source,
[CanBeNull] IRelationalModel target,
[NotNull] DiffContext diffContext)
{
if (target == null)
{
_targetUpdateAdapter = null;
return;
}
_targetUpdateAdapter = UpdateAdapterFactory.CreateStandalone(target.Model);
_targetUpdateAdapter.CascadeDeleteTiming = CascadeTiming.Never;
foreach (var targetEntityType in target.Model.GetEntityTypes())
{
foreach (var targetSeed in targetEntityType.GetSeedData())
{
_targetUpdateAdapter
.CreateEntry(targetSeed, targetEntityType)
.EntityState = EntityState.Added;
}
}
if (source == null)
{
_sourceUpdateAdapter = null;
return;
}
_sourceUpdateAdapter = UpdateAdapterFactory.CreateStandalone(source.Model);
_sourceUpdateAdapter.CascadeDeleteTiming = CascadeTiming.OnSaveChanges;
foreach (var sourceEntityType in source.Model.GetEntityTypes())
{
foreach (var sourceSeed in sourceEntityType.GetSeedData())
{
var entry = _sourceUpdateAdapter
.CreateEntry(sourceSeed, sourceEntityType);
// Mark as added first to generate missing values
// Issue #15289
entry.EntityState = EntityState.Added;
entry.EntityState = EntityState.Unchanged;
}
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual Dictionary<IEntityType, List<ITable>> DiffData(
[CanBeNull] IRelationalModel source,
[CanBeNull] IRelationalModel target,
[NotNull] DiffContext diffContext)
{
Check.NotNull(diffContext, nameof(diffContext));
if (source == null
|| target == null)
{
return null;
}
var keyMapping = new Dictionary<IEntityType,
Dictionary<(IKey, ITable), List<(IProperty Property, ValueConverter SourceConverter, ValueConverter TargetConverter)>>>();
foreach (var sourceEntityType in source.Model.GetEntityTypes())
{
foreach (var sourceTableMapping in sourceEntityType.GetTableMappings())
{
var sourceTable = sourceTableMapping.Table;
var targetTable = diffContext.FindTarget(sourceTable);
if (targetTable?.PrimaryKey == null)
{
continue;
}
foreach (var targetKey in targetTable.PrimaryKey.MappedKeys)
{
var keyPropertiesMap = new List<(IProperty, ValueConverter, ValueConverter)>();
foreach (var keyProperty in targetKey.Properties)
{
var targetColumnMapping = keyProperty.GetTableColumnMappings().First(m => m.TableMapping.Table == targetTable);
var targetColumn = targetColumnMapping.Column;
var sourceColumn = diffContext.FindSource(targetColumn);
if (sourceColumn == null)
{
break;
}
foreach (var sourceProperty in sourceColumn.PropertyMappings.Select(m => m.Property).Distinct())
{
if (!sourceProperty.DeclaringEntityType.IsAssignableFrom(sourceEntityType))
{
continue;
}
var sourceConverter = GetValueConverter(sourceProperty);
var targetConverter = GetValueConverter(keyProperty);
if (sourceProperty.ClrType != keyProperty.ClrType
&& (sourceConverter == null || sourceConverter.ProviderClrType != keyProperty.ClrType)
&& (targetConverter == null || targetConverter.ProviderClrType != sourceProperty.ClrType))
{
continue;
}
keyPropertiesMap.Add((sourceProperty, sourceConverter, targetConverter));
break;
}
}
if (keyPropertiesMap.Count == targetKey.Properties.Count)
{
keyMapping.GetOrAddNew(sourceEntityType)[(targetKey, targetTable)] = keyPropertiesMap;
}
}
}
}
var changedTableMappings = new Dictionary<IEntityType, List<ITable>>();
foreach (var targetEntityType in target.Model.GetEntityTypes())
{
var targetKey = targetEntityType.FindPrimaryKey();
if (targetKey == null)
{
continue;
}
ITable mainSourceTable = null;
foreach (var targetTableMapping in targetEntityType.GetTableMappings())
{
var targetTable = targetTableMapping.Table;
if (targetTableMapping.IsMainTableMapping)
{
mainSourceTable = diffContext.FindSource(targetTable);
continue;
}
Check.DebugAssert(mainSourceTable != null, "mainSourceTable is null");
var newMapping = true;
var sourceTable = diffContext.FindSource(targetTable);
if (sourceTable != null)
{
foreach (var sourceEntityTypeMapping in sourceTable.EntityTypeMappings)
{
var sourceEntityType = sourceEntityTypeMapping.EntityType;
if (keyMapping.TryGetValue(sourceEntityType, out var targetKeyMap)
&& targetKeyMap.ContainsKey((targetKey, targetTable))
&& sourceEntityType.GetTableMappings().Any(m => m.IsMainTableMapping && m.Table == mainSourceTable))
{
newMapping = false;
}
}
}
if (newMapping)
{
if (!changedTableMappings.TryGetValue(targetEntityType, out var newTables))
{
newTables = new List<ITable>();
changedTableMappings[targetEntityType] = newTables;
}
newTables.Add(targetTable);
}
}
}
foreach (var sourceEntityType in source.Model.GetEntityTypes())
{
ITable mainSourceTable = null;
if (keyMapping.TryGetValue(sourceEntityType, out var targetKeyMap))
{
ITable mainTargetTable = null;
foreach (var sourceTableMapping in sourceEntityType.GetTableMappings())
{
var sourceTable = sourceTableMapping.Table;
if (sourceTableMapping.IsMainTableMapping)
{
mainSourceTable = sourceTable;
mainTargetTable = diffContext.FindTarget(mainSourceTable);
if (mainTargetTable == null)
{
break;
}
continue;
}
Check.DebugAssert(mainSourceTable != null, "mainSourceTable is null");
var targetTable = diffContext.FindTarget(sourceTable);
var removedMapping = true;
if (targetTable != null
&& targetKeyMap.Keys.Any(k => k.Item2 == targetTable
&& k.Item1.DeclaringEntityType.GetTableMappings().Any(m => m.IsMainTableMapping && m.Table == mainTargetTable)))
{
removedMapping = false;
}
if (removedMapping
&& diffContext.FindDrop(sourceTable) == null)
{
if (!changedTableMappings.TryGetValue(sourceEntityType, out var removedTables))
{
removedTables = new List<ITable>();
changedTableMappings[sourceEntityType] = removedTables;
}
removedTables.Add(sourceTable);
}
}
}
else
{
targetKeyMap = null;
mainSourceTable = sourceEntityType.GetTableMappings().FirstOrDefault(m => m.IsMainTableMapping)?.Table;
}
if (mainSourceTable == null)
{
continue;
}
// If table sharing is being used find the main table of the principal entity type
var mainSourceEntityType = sourceEntityType;
var mainPrincipalSourceTable = mainSourceTable;
while (mainSourceTable.GetRowInternalForeignKeys(mainSourceEntityType).Any())
{
mainSourceEntityType = mainPrincipalSourceTable.EntityTypeMappings.First(m => m.IsMainEntityTypeMapping).EntityType;
mainPrincipalSourceTable = mainSourceEntityType.GetTableMappings().First(m => m.IsMainTableMapping).Table;
}
foreach (var sourceSeed in sourceEntityType.GetSeedData())
{
var sourceEntry = GetEntry(sourceSeed, sourceEntityType, _sourceUpdateAdapter);
if (!_sourceSharedIdentityEntryMaps.TryGetValue(mainPrincipalSourceTable, out var sourceTableEntryMappingMap))
{
sourceTableEntryMappingMap = new SharedIdentityMap(_sourceUpdateAdapter);
_sourceSharedIdentityEntryMaps.Add(mainPrincipalSourceTable, sourceTableEntryMappingMap);
}
var entryMapping = sourceTableEntryMappingMap.GetOrAddValue(sourceEntry, mainSourceTable);
entryMapping.SourceEntries.Add(sourceEntry);
if (targetKeyMap == null)
{
continue;
}
foreach (var targetKeyTuple in targetKeyMap)
{
var (targetKey, targetTable) = targetKeyTuple.Key;
var keyPropertiesMap = targetKeyTuple.Value;
var targetKeyValues = new object[keyPropertiesMap.Count];
for (var i = 0; i < keyPropertiesMap.Count; i++)
{
var (sourceProperty, sourceConverter, targetConverter) = keyPropertiesMap[i];
var sourceValue = sourceEntry.GetCurrentValue(sourceProperty);
targetKeyValues[i] = targetKey.Properties[i].ClrType != sourceProperty.ClrType
? sourceConverter != null
? sourceConverter.ConvertToProvider(sourceValue)
: targetConverter.ConvertFromProvider(sourceValue)
: sourceValue;
}
var entry = _targetUpdateAdapter.TryGetEntry(targetKey, targetKeyValues);
if (entry == null)
{
continue;
}
if (entryMapping.TargetEntries.Add(entry))
{
if (entry.EntityState != EntityState.Added)
{
Check.DebugAssert(false, "All entries must be in added state at this point");
continue;
}
foreach (var targetProperty in entry.EntityType.GetProperties())
{
if (targetProperty.GetAfterSaveBehavior() == PropertySaveBehavior.Save)
{
entry.SetOriginalValue(targetProperty, targetProperty.ClrType.GetDefaultValue());
}
}
entry.EntityState = EntityState.Unchanged;
}
if (entryMapping.RecreateRow)
{
continue;
}
if (!changedTableMappings.TryGetValue(entry.EntityType, out var newMappings))
{
newMappings = null;
}
foreach (var targetProperty in entry.EntityType.GetProperties())
{
if (targetProperty.ValueGenerated != ValueGenerated.Never)
{
continue;
}
var targetColumn = targetProperty.GetTableColumnMappings()
.FirstOrDefault(m => m.TableMapping.EntityType == entry.EntityType && m.TableMapping.Table == targetTable)?.Column;
var sourceColumn = diffContext.FindSource(targetColumn);
if (sourceColumn == null)
{
continue;
}
var sourceProperty = sourceColumn.PropertyMappings.Select(m => m.Property)
.FirstOrDefault(p => p.DeclaringEntityType.IsAssignableFrom(sourceEntityType));
if (sourceProperty == null)
{
continue;
}
var sourceValue = sourceEntry.GetCurrentValue(sourceProperty);
var targetValue = entry.GetCurrentValue(targetProperty);
var comparer = targetProperty.GetValueComparer()
?? sourceProperty.GetValueComparer();
var modelValuesChanged
= sourceProperty.ClrType.UnwrapNullableType() == targetProperty.ClrType.UnwrapNullableType()
&& comparer?.Equals(sourceValue, targetValue) == false;
if (!modelValuesChanged)
{
var sourceConverter = GetValueConverter(sourceProperty);
var targetConverter = GetValueConverter(targetProperty);
var convertedSourceValue = sourceConverter == null
? sourceValue
: sourceConverter.ConvertToProvider(sourceValue);
var convertedTargetValue = targetConverter == null
? targetValue
: targetConverter.ConvertToProvider(targetValue);
var convertedType = sourceConverter?.ProviderClrType
?? targetConverter?.ProviderClrType;
if (convertedType != null
&& !convertedType.IsNullableType())
{
var defaultValue = convertedType.GetDefaultValue();
convertedSourceValue ??= defaultValue;
convertedTargetValue ??= defaultValue;
}
var storeValuesChanged = convertedSourceValue?.GetType().UnwrapNullableType()
!= convertedTargetValue?.GetType().UnwrapNullableType();
if (!storeValuesChanged
&& convertedType != null)
{
comparer = TypeMappingSource.FindMapping(convertedType)?.Comparer;
storeValuesChanged = !comparer?.Equals(convertedSourceValue, convertedTargetValue)
?? !Equals(convertedSourceValue, convertedTargetValue);
}
if (!storeValuesChanged)
{
if (newMappings == null
|| targetProperty.GetTableColumnMappings().Any(m => !newMappings.Contains(m.TableMapping.Table)))
{
entry.SetOriginalValue(targetProperty, entry.GetCurrentValue(targetProperty));
}
continue;
}
}
if (targetProperty.GetAfterSaveBehavior() != PropertySaveBehavior.Save)
{
entryMapping.RecreateRow = true;
break;
}
entry.SetPropertyModified(targetProperty);
}
}
}
}
return changedTableMappings;
}
private static IUpdateEntry GetEntry(
IDictionary<string, object> sourceSeed, IEntityType sourceEntityType, IUpdateAdapter updateAdapter)
{
var key = sourceEntityType.FindPrimaryKey();
var keyValues = new object[key.Properties.Count];
for (var i = 0; i < keyValues.Length; i++)
{
keyValues[i] = sourceSeed[key.Properties[i].Name];
}
return updateAdapter.TryGetEntry(key, keyValues);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> GetDataOperations(
[NotNull] IRelationalModel source, [NotNull] IRelationalModel target, [NotNull] DiffContext diffContext)
{
TrackData(source, target, diffContext);
var changedTableMappings = DiffData(source, target, diffContext);
foreach (var sourceTableEntryMappingMap in _sourceSharedIdentityEntryMaps)
{
foreach (var entryMapping in sourceTableEntryMappingMap.Value.Values)
{
if (entryMapping.RecreateRow
|| entryMapping.TargetEntries.Count == 0)
{
foreach (var sourceEntry in entryMapping.SourceEntries)
{
sourceEntry.EntityState = EntityState.Deleted;
_sourceUpdateAdapter.CascadeDelete(
sourceEntry,
sourceEntry.EntityType.GetReferencingForeignKeys()
.Where(
fk =>
{
var behavior = diffContext.FindTarget(fk)?.DeleteBehavior;
return behavior != null && behavior != DeleteBehavior.ClientNoAction;
}));
}
}
}
}
var entriesWithRemovedMappings = new HashSet<IUpdateEntry>();
foreach (var sourceTableEntryMappingMap in _sourceSharedIdentityEntryMaps)
{
foreach (var entryMapping in sourceTableEntryMappingMap.Value.Values)
{
if (entryMapping.SourceEntries.Any(e => e.EntityState == EntityState.Deleted))
{
foreach (var targetEntry in entryMapping.TargetEntries)
{
targetEntry.EntityState = EntityState.Added;
}
foreach (var sourceEntry in entryMapping.SourceEntries)
{
sourceEntry.EntityState = EntityState.Deleted;
}
}
else if (entryMapping.SourceEntries.Any(en => changedTableMappings.ContainsKey(en.EntityType)))
{
foreach (var sourceEntry in entryMapping.SourceEntries)
{
entriesWithRemovedMappings.Add(sourceEntry);
sourceEntry.EntityState = EntityState.Deleted;
}
}
}
}
_sourceSharedIdentityEntryMaps.Clear();
var dataOperations = GetDataOperations(forSource: true, changedTableMappings, entriesWithRemovedMappings, diffContext)
.Concat(GetDataOperations(forSource: false, changedTableMappings, entriesWithRemovedMappings, diffContext));
foreach(var operation in dataOperations)
{
yield return operation;
}
}
private IEnumerable<MigrationOperation> GetDataOperations(
bool forSource,
Dictionary<IEntityType, List<ITable>> changedTableMappings,
HashSet<IUpdateEntry> entriesWithRemovedMappings,
DiffContext diffContext)
{
var updateAdapter = forSource ? _sourceUpdateAdapter : _targetUpdateAdapter;
if (updateAdapter == null)
{
yield break;
}
updateAdapter.DetectChanges();
var entries = updateAdapter.GetEntriesToSave();
if (entries == null
|| entries.Count == 0)
{
yield break;
}
var model = updateAdapter.Model.GetRelationalModel();
var commandBatches = new CommandBatchPreparer(CommandBatchPreparerDependencies)
.BatchCommands(entries, updateAdapter);
foreach (var commandBatch in commandBatches)
{
InsertDataOperation batchInsertOperation = null;
foreach (var command in commandBatch.ModificationCommands)
{
if (diffContext.FindDrop(model.FindTable(command.TableName, command.Schema)) != null)
{
continue;
}
switch (command.EntityState)
{
case EntityState.Added:
if (batchInsertOperation != null)
{
if (batchInsertOperation.Table == command.TableName
&& batchInsertOperation.Schema == command.Schema
&& batchInsertOperation.Columns.SequenceEqual(
command.ColumnModifications.Where(col => col.IsKey || col.IsWrite).Select(col => col.ColumnName)))
{
batchInsertOperation.Values =
AddToMultidimensionalArray(
command.ColumnModifications.Where(col => col.IsKey || col.IsWrite).Select(GetValue).ToList(),
batchInsertOperation.Values);
continue;
}
yield return batchInsertOperation;
}
if (forSource)
{
// There shouldn't be any inserts using the source model
Check.DebugAssert(false, "Insert using the source model");
break;
}
batchInsertOperation = new InsertDataOperation
{
Schema = command.Schema,
Table = command.TableName,
Columns = command.ColumnModifications.Where(col => col.IsKey || col.IsWrite).Select(col => col.ColumnName)
.ToArray(),
Values = ToMultidimensionalArray(
command.ColumnModifications.Where(col => col.IsKey || col.IsWrite).Select(GetValue).ToList())
};
break;
case EntityState.Modified:
if (batchInsertOperation != null)
{
yield return batchInsertOperation;
batchInsertOperation = null;
}
if (forSource)
{
// There shouldn't be any updates using the source model
Check.DebugAssert(false, "Update using the source model");
break;
}
if (command.Entries.Any(en => changedTableMappings.TryGetValue(en.EntityType, out var newTables)
&& newTables.Any(t => t.Name == command.TableName && t.Schema == command.Schema)))
{
// If the entity type uses TPT add the rows to the new tables to which the entity has been mapped
goto case EntityState.Added;
}
yield return new UpdateDataOperation
{
Schema = command.Schema,
Table = command.TableName,
KeyColumns = command.ColumnModifications.Where(col => col.IsKey).Select(col => col.ColumnName).ToArray(),
KeyValues = ToMultidimensionalArray(
command.ColumnModifications.Where(col => col.IsKey).Select(GetValue).ToList()),
Columns = command.ColumnModifications.Where(col => col.IsWrite).Select(col => col.ColumnName).ToArray(),
Values = ToMultidimensionalArray(
command.ColumnModifications.Where(col => col.IsWrite).Select(GetValue).ToList()),
IsDestructiveChange = true
};
break;
case EntityState.Deleted:
if (batchInsertOperation != null)
{
yield return batchInsertOperation;
batchInsertOperation = null;
}
// There shouldn't be any deletes using the target model
Check.DebugAssert(forSource, "Delete using the target model");
// If the entity type used TPT delete the rows in the tables to which the entity is no longer mapped
if (command.Entries.Any(en => entriesWithRemovedMappings.Contains(en))
&& !command.Entries.Any(en => changedTableMappings.TryGetValue(en.EntityType, out var removedTables)
&& removedTables.Any(t => t.Name == command.TableName && t.Schema == command.Schema)))
{
break;
}
yield return new DeleteDataOperation
{
Schema = command.Schema,
Table = command.TableName,
KeyColumns = command.ColumnModifications.Where(col => col.IsKey).Select(col => col.ColumnName).ToArray(),
KeyValues = ToMultidimensionalArray(
command.ColumnModifications.Where(col => col.IsKey).Select(GetValue).ToArray()),
IsDestructiveChange = true
};
break;
default:
throw new InvalidOperationException(command.EntityState.ToString());
}
}
if (batchInsertOperation != null)
{
yield return batchInsertOperation;
}
}
}
private object GetValue(ColumnModification columnModification)
{
var converter = GetValueConverter(columnModification.Property);
var value = columnModification.UseCurrentValueParameter
? columnModification.Value
: columnModification.OriginalValue;
return converter != null
? converter.ConvertToProvider(value)
: value;
}
#endregion
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<MigrationOperation> DiffCollection<T>(
[NotNull] IEnumerable<T> sources,
[NotNull] IEnumerable<T> targets,
[NotNull] DiffContext diffContext,
[NotNull] Func<T, T, DiffContext, IEnumerable<MigrationOperation>> diff,
[NotNull] Func<T, DiffContext, IEnumerable<MigrationOperation>> add,
[NotNull] Func<T, DiffContext, IEnumerable<MigrationOperation>> remove,
[NotNull] params Func<T, T, DiffContext, bool>[] predicates)
{
var sourceList = sources.ToList();
var targetList = targets.ToList();
var pairedList = new List<(T source, T target)>();
foreach (var predicate in predicates)
{
for (var i = sourceList.Count - 1; i >= 0; i--)
{
var source = sourceList[i];
for (var j = targetList.Count - 1; j >= 0; j--)
{
var target = targetList[j];
if (predicate(source, target, diffContext))
{
sourceList.RemoveAt(i);
targetList.RemoveAt(j);
pairedList.Add((source, target));
diffContext.AddMapping(source, target);
break;
}
}
}
}
foreach (var (source, target) in pairedList)
{
foreach (var operation in diff(source, target, diffContext))
{
yield return operation;
}
}
foreach (var source in sourceList)
{
foreach (var operation in remove(source, diffContext))
{
yield return operation;
}
}
foreach (var target in targetList)
{
foreach (var operation in add(target, diffContext))
{
yield return operation;
}
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual bool HasDifferences([NotNull] IEnumerable<IAnnotation> source, [NotNull] IEnumerable<IAnnotation> target)
{
var unmatched = new List<IAnnotation>(target);
foreach (var annotation in source)
{
var index = unmatched.FindIndex(
a => a.Name == annotation.Name && StructuralComparisons.StructuralEqualityComparer.Equals(a.Value, annotation.Value));
if (index == -1)
{
return true;
}
unmatched.RemoveAt(index);
}
return unmatched.Count != 0;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual IEnumerable<string> GetSchemas([NotNull] IRelationalModel model)
=> model.Tables.Where(t => !t.IsExcludedFromMigrations).Select(t => t.Schema)
.Concat(model.Views.Where(t => t.ViewDefinitionSql != null).Select(s => s.Schema))
.Concat(model.Sequences.Select(s => s.Schema))
.Where(s => !string.IsNullOrEmpty(s))
.Distinct();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual object GetDefaultValue([NotNull] Type type)
=> type == typeof(string)
? string.Empty
: type.IsArray
? Array.CreateInstance(type.GetElementType(), 0)
: type.UnwrapNullableType().GetDefaultValue();
private ValueConverter GetValueConverter(IProperty property, RelationalTypeMapping typeMapping = null)
=> property.GetValueConverter() ?? (property.FindRelationalTypeMapping() ?? typeMapping)?.Converter;
private static IEntityType GetMainType(ITable table)
=> table.EntityTypeMappings.FirstOrDefault(t => t.IsMainEntityTypeMapping).EntityType;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[Obsolete]
public static IProperty[] GetMappedProperties([NotNull] ITable table, [NotNull] string[] names)
{
var properties = new IProperty[names.Length];
for (var i = 0; i < names.Length; i++)
{
var name = names[i];
var column = table.FindColumn(name);
if (column == null)
{
continue;
}
properties[i] = column.PropertyMappings.First().Property;
}
return properties;
}
private static object[,] ToMultidimensionalArray(IReadOnlyList<object> values)
{
var result = new object[1, values.Count];
for (var i = 0; i < values.Count; i++)
{
result[0, i] = values[i];
}
return result;
}
private static object[,] AddToMultidimensionalArray(IReadOnlyList<object> values, object[,] array)
{
var width = array.GetLength(0);
var height = array.GetLength(1);
Check.DebugAssert(height == values.Count, $"height of {height} != values.Count of {values.Count}");
var result = new object[width + 1, height];
for (var i = 0; i < width; i++)
{
Array.Copy(array, i * height, result, i * height, height);
}
for (var i = 0; i < values.Count; i++)
{
result[width, i] = values[i];
}
return result;
}
private sealed class EntryMapping
{
public HashSet<IUpdateEntry> SourceEntries { get; } = new HashSet<IUpdateEntry>();
public HashSet<IUpdateEntry> TargetEntries { get; } = new HashSet<IUpdateEntry>();
public bool RecreateRow { get; set; }
}
private sealed class SharedIdentityMap
{
private readonly IUpdateAdapter _updateAdapter;
private readonly Dictionary<IUpdateEntry, EntryMapping> _entryValueMap
= new Dictionary<IUpdateEntry, EntryMapping>();
public SharedIdentityMap(IUpdateAdapter updateAdapter)
{
_updateAdapter = updateAdapter;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public IEnumerable<EntryMapping> Values => _entryValueMap.Values;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public EntryMapping GetOrAddValue([NotNull] IUpdateEntry entry, ITable table)
{
var mainEntry = GetMainEntry(entry, table);
if (_entryValueMap.TryGetValue(mainEntry, out var entryMapping))
{
return entryMapping;
}
entryMapping = new EntryMapping();
_entryValueMap.Add(mainEntry, entryMapping);
return entryMapping;
}
private IUpdateEntry GetMainEntry(IUpdateEntry entry, ITable table)
{
var entityType = entry.EntityType;
var foreignKeys = table.GetRowInternalForeignKeys(entityType);
foreach (var foreignKey in foreignKeys)
{
var principalEntry = _updateAdapter.FindPrincipal(entry, foreignKey);
if (principalEntry != null)
{
return GetMainEntry(principalEntry, table);
}
}
var mainTable = entry.EntityType.GetTableMappings().First(m => m.IsMainTableMapping).Table;
if (mainTable != table)
{
return GetMainEntry(entry, mainTable);
}
return entry;
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected class DiffContext
{
private readonly IDictionary<object, object> _targetToSource = new Dictionary<object, object>();
private readonly IDictionary<object, object> _sourceToTarget = new Dictionary<object, object>();
private readonly IDictionary<ITable, CreateTableOperation> _createTableOperations
= new Dictionary<ITable, CreateTableOperation>();
private readonly IDictionary<ITable, DropTableOperation> _dropTableOperations
= new Dictionary<ITable, DropTableOperation>();
private readonly IDictionary<DropTableOperation, ITable> _removedTables
= new Dictionary<DropTableOperation, ITable>();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual void AddMapping<T>([NotNull] T source, [NotNull] T target)
{
_targetToSource.Add(target, source);
_sourceToTarget.Add(source, target);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual void AddCreate([NotNull] ITable target, [NotNull] CreateTableOperation operation)
=> _createTableOperations.Add(target, operation);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual void AddDrop([NotNull] ITable source, [NotNull] DropTableOperation operation)
{
_dropTableOperations.Add(source, operation);
_removedTables.Add(operation, source);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual ITable GetTable(IEntityType entityType)
=> entityType.GetTableMappings().First().Table;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual T FindSource<T>([CanBeNull] T target)
where T : class
=> target == null
? null
: _targetToSource.TryGetValue(target, out var source)
? (T)source
: null;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual T FindTarget<T>([CanBeNull] T source)
where T : class
=> source == null
? null
: _sourceToTarget.TryGetValue(source, out var target)
? (T)target
: null;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual CreateTableOperation FindCreate([NotNull] ITable target)
=> _createTableOperations.TryGetValue(target, out var operation)
? operation
: null;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual DropTableOperation FindDrop([NotNull] ITable source)
=> _dropTableOperations.TryGetValue(source, out var operation)
? operation
: null;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual ITable FindTable([NotNull] DropTableOperation operation)
=> _removedTables.TryGetValue(operation, out var source)
? source
: null;
}
}
}
| 48.663548
| 147
| 0.563559
|
[
"Apache-2.0"
] |
MartinBP/efcore
|
src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs
| 130,029
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma warning disable 1634, 1691
using System.Threading;
using Dbg = System.Management.Automation;
namespace System.Management.Automation
{
/// <summary>
/// Defines a drive that exposes a provider path to the user.
/// </summary>
/// <remarks>
/// A cmdlet provider may want to derive from this class to provide their
/// own public members or to cache information related to the drive. For instance,
/// if a drive is a connection to a remote machine and making that connection
/// is expensive, then the provider may want keep a handle to the connection as
/// a member of their derived <see cref="PSDriveInfo"/> class and use it when
/// the provider is invoked.
/// </remarks>
public class PSDriveInfo : IComparable
{
/// <summary>
/// An instance of the PSTraceSource class used for trace output
/// using "SessionState" as the category.
/// This is the same category as the SessionState tracer class.
/// </summary>
[Dbg.TraceSourceAttribute(
"PSDriveInfo",
"The namespace navigation tracer")]
private static Dbg.PSTraceSource s_tracer =
Dbg.PSTraceSource.GetTracer("PSDriveInfo",
"The namespace navigation tracer");
/// <summary>
/// Gets or sets the current working directory for the drive.
/// </summary>
public string CurrentLocation
{
get
{
return _currentWorkingDirectory;
}
set
{
_currentWorkingDirectory = value;
}
} // CurrentLocation
/// <summary>
/// The current working directory for the virtual drive
/// as a relative path from Root
/// </summary>
private string _currentWorkingDirectory;
/// <summary>
/// Gets the name of the drive
/// </summary>
public string Name
{
get
{
return _name;
}
}
/// <summary>
/// The name of the virtual drive
/// </summary>
private string _name;
/// <summary>
/// Gets the name of the provider that root path
/// of the drive represents.
/// </summary>
public ProviderInfo Provider
{
get
{
return _provider;
}
}
/// <summary>
/// The provider information for the provider that implements
/// the functionality for the drive.
/// </summary>
private ProviderInfo _provider;
/// <summary>
/// Gets the root path of the drive.
/// </summary>
public string Root
{
get
{
return _root;
}
internal set
{
_root = value;
}
}
/// <summary>
/// Sets the root of the drive.
/// </summary>
/// <param name="path">
/// The root path to set for the drive.
/// </param>
/// <remarks>
/// This method can only be called during drive
/// creation. A NotSupportedException if this method
/// is called outside of drive creation.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="NotSupportedException">
/// If this method gets called any other time except
/// during drive creation.
/// </exception>
internal void SetRoot(string path)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException("path");
}
if (!DriveBeingCreated)
{
NotSupportedException e =
PSTraceSource.NewNotSupportedException();
throw e;
}
_root = path;
} // SetRoot
/// <summary>
/// The root of the virtual drive
/// </summary>
private string _root;
/// <summary>
/// Gets or sets the description for the drive.
/// </summary>
public string Description { get; set; }
/// <summary>
/// When supported by provider this specifies a maximum drive size.
/// </summary>
public long? MaximumSize { get; internal set; }
/// <summary>
/// Gets the credential to use with the drive.
/// </summary>
public PSCredential Credential { get; } = PSCredential.Empty;
/// <summary>
/// Determines if the root of the drive can
/// be modified during drive creation through
/// the SetRoot method.
/// </summary>
/// <value>
/// True if the drive is being created and the
/// root can be modified through the SetRoot method.
/// False otherwise.
/// </value>
internal bool DriveBeingCreated { get; set; }
/// <summary>
/// True if the drive was automounted by the system,
/// false otherwise.
/// </summary>
/// <value></value>
internal bool IsAutoMounted { get; set; }
/// <summary>
/// True if the drive was automounted by the system,
/// and then manually removed by the user.
/// </summary>
internal bool IsAutoMountedManuallyRemoved { get; set; }
/// <summary>
/// Gets or sets the Persist Switch parameter.
/// If this switch parameter is set then the created PSDrive
/// would be persisted across PowerShell sessions.
/// </summary>
internal bool Persist { get; } = false;
/// <summary>
/// Get or sets the value indicating if the created drive is a network drive.
/// </summary>
internal bool IsNetworkDrive { get; set; } = false;
/// <summary>
/// Gets or sets the UNC path of the drive. This property would be populated only
/// if the created PSDrive is targeting a network drive or else this property
/// would be null.
/// </summary>
public string DisplayRoot { get; internal set; } = null;
/// <summary>
/// Gets or sets if the drive-root relative paths on this drive are separated by a
/// colon or not.
///
/// This is true for all PSDrives on all platforms, except for filesystems on
/// non-Windows platforms.
///
/// This is not a path separator in the sense of separating paths in a single
/// string.
///
/// The biggest difference in filesystem handling between PS internally, and Unix
/// style systems is, that paths on Windows separate the drive letter from the
/// actual path by a colon. The second difference is, that a path that starts with
/// a \ or / on Windows is considered to be a relative path (drive-relative in
/// that case) where a similar path on a Unix style filesystem would be
/// root-relative, which is basically drive-relative for the filesystem, as there
/// is only one filesystem drive.
///
/// This property indicates, that a path can be checked for that drive-relativity
/// by checking for a colon. The main reason for this can be seen in all the
/// places that use this property, where PowerShell's code checks/splits/string
/// manipulates paths according to the colon character. This happens in many
/// places.
///
/// The idea here was to introduce a property that allows a code to query if a
/// PSDrive expects colon to be such a separator or not. I talked to Jim back then
/// about the problem, and this seemed to be a reasonable solution, given that
/// there is no other way to know for a PSDrive if paths can be qualified only in
/// a certain windows way on all platforms, or need special treatment on platforms
/// where colon does not exist as drive separator (regular filesystems on Unix
/// platforms are the only exception).
///
/// Globally this property can also be only true for one single PSDrive, because
/// if there is no drive separator, there is also no drive, and because there is
/// no drive there is no way to match against multiple such drives.
///
/// Additional data:
/// It seems that on single rooted filesystems, only the default
/// drive of "/" needs to set this VolumeSeparatedByColon to false
/// otherwise, creating new drives from the filesystem should actually
/// have this set to true as all the drives will have <string>: except
/// for "/"
/// </summary>
public bool VolumeSeparatedByColon { get; internal set; } = true;
#region ctor
/// <summary>
/// Constructs a new instance of the PSDriveInfo using another PSDriveInfo
/// as a template.
/// </summary>
/// <param name="driveInfo">
/// An existing PSDriveInfo object that should be copied to this instance.
/// </param>
/// <remarks>
/// A protected constructor that derived classes can call with an instance
/// of this class. This allows for easy creation of derived PSDriveInfo objects
/// which can be created in CmdletProvider's NewDrive method using the PSDriveInfo
/// that is passed in.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// If <paramref name="PSDriveInfo"/> is null.
/// </exception>
protected PSDriveInfo(PSDriveInfo driveInfo)
{
if (driveInfo == null)
{
throw PSTraceSource.NewArgumentNullException("driveInfo");
}
_name = driveInfo.Name;
_provider = driveInfo.Provider;
Credential = driveInfo.Credential;
_currentWorkingDirectory = driveInfo.CurrentLocation;
Description = driveInfo.Description;
this.MaximumSize = driveInfo.MaximumSize;
DriveBeingCreated = driveInfo.DriveBeingCreated;
_hidden = driveInfo._hidden;
IsAutoMounted = driveInfo.IsAutoMounted;
_root = driveInfo._root;
Persist = driveInfo.Persist;
this.Trace();
}
/// <summary>
/// Constructs a drive that maps an MSH Path in
/// the shell to a Cmdlet Provider.
/// </summary>
/// <param name="name">
/// The name of the drive.
/// </param>
/// <param name="provider">
/// The name of the provider which implements the functionality
/// for the root path of the drive.
/// </param>
/// <param name="root">
/// The root path of the drive. For example, the root of a
/// drive in the file system can be c:\windows\system32
/// </param>
/// <param name="description">
/// The description for the drive.
/// </param>
/// <param name="credential">
/// The credentials under which all operations on the drive should occur.
/// If null, the current user credential is used.
/// </param>
/// <throws>
/// ArgumentNullException - if <paramref name="name"/>,
/// <paramref name="provider"/>, or <paramref name="root"/>
/// is null.
/// </throws>
public PSDriveInfo(
string name,
ProviderInfo provider,
string root,
string description,
PSCredential credential)
{
// Verify the parameters
if (name == null)
{
throw PSTraceSource.NewArgumentNullException("name");
}
if (provider == null)
{
throw PSTraceSource.NewArgumentNullException("provider");
}
if (root == null)
{
throw PSTraceSource.NewArgumentNullException("root");
}
// Copy the parameters to the local members
_name = name;
_provider = provider;
_root = root;
Description = description;
if (credential != null)
{
Credential = credential;
}
// Set the current working directory to the empty
// string since it is relative to the root.
_currentWorkingDirectory = String.Empty;
Dbg.Diagnostics.Assert(
_currentWorkingDirectory != null,
"The currentWorkingDirectory cannot be null");
// Trace out the fields
this.Trace();
}
/// <summary>
/// Constructs a drive that maps an MSH Path in
/// the shell to a Cmdlet Provider.
/// </summary>
/// <param name="name">
/// The name of the drive.
/// </param>
/// <param name="provider">
/// The name of the provider which implements the functionality
/// for the root path of the drive.
/// </param>
/// <param name="root">
/// The root path of the drive. For example, the root of a
/// drive in the file system can be c:\windows\system32
/// </param>
/// <param name="description">
/// The description for the drive.
/// </param>
/// <param name="credential">
/// The credentials under which all operations on the drive should occur.
/// If null, the current user credential is used.
/// </param>
/// <param name="displayRoot">
/// The network path of the drive. This field would be populated only if PSDriveInfo
/// is targeting the network drive or else this filed is null for local drives.
/// </param>
/// <throws>
/// ArgumentNullException - if <paramref name="name"/>,
/// <paramref name="provider"/>, or <paramref name="root"/>
/// is null.
/// </throws>
public PSDriveInfo(
string name,
ProviderInfo provider,
string root,
string description,
PSCredential credential, string displayRoot)
: this(name, provider, root, description, credential)
{
DisplayRoot = displayRoot;
}
/// <summary>
/// Constructs a drive that maps an MSH Path in
/// the shell to a Cmdlet Provider.
/// </summary>
/// <param name="name">
/// The name of the drive.
/// </param>
/// <param name="provider">
/// The name of the provider which implements the functionality
/// for the root path of the drive.
/// </param>
/// <param name="root">
/// The root path of the drive. For example, the root of a
/// drive in the file system can be c:\windows\system32
/// </param>
/// <param name="description">
/// The description for the drive.
/// </param>
/// <param name="credential">
/// The credentials under which all operations on the drive should occur.
/// If null, the current user credential is used.
/// </param>
/// <param name="persist">
/// It indicates if the the created PSDrive would be
/// persisted across PowerShell sessions.
/// </param>
/// <throws>
/// ArgumentNullException - if <paramref name="name"/>,
/// <paramref name="provider"/>, or <paramref name="root"/>
/// is null.
/// </throws>
public PSDriveInfo(
string name,
ProviderInfo provider,
string root,
string description,
PSCredential credential,
bool persist)
: this(name, provider, root, description, credential)
{
Persist = persist;
}
#endregion ctor
/// <summary>
/// Gets the name of the drive as a string.
/// </summary>
/// <returns>
/// Returns a String that is that name of the drive.
/// </returns>
public override string ToString()
{
return Name;
}
/// <summary>
/// Gets or sets the hidden property. The hidden property
/// determines if the drive should be hidden from the user.
/// </summary>
/// <value>
/// True if the drive should be hidden from the user, false
/// otherwise.
/// </value>
internal bool Hidden
{
get
{
return _hidden;
} //get
set
{
_hidden = value;
} // set
} // Hidden
/// <summary>
/// Determines if the drive should be hidden from the user.
/// </summary>
private bool _hidden;
/// <summary>
/// Sets the name of the drive to a new name.
/// </summary>
/// <param name="newName">
/// The new name for the drive.
/// </param>
/// <remarks>
/// This must be internal so that we allow the renaming of drives
/// via the Core Command API but not through a reference to the
/// drive object. More goes in to renaming a drive than just modifying
/// the name in this class.
/// </remarks>
/// <exception cref="ArgumentException">
/// If <paramref name="newName"/> is null or empty.
/// </exception>
internal void SetName(string newName)
{
if (String.IsNullOrEmpty(newName))
{
throw PSTraceSource.NewArgumentException("newName");
}
_name = newName;
} // SetName
/// <summary>
/// Sets the provider of the drive to a new provider.
/// </summary>
/// <param name="newProvider">
/// The new provider for the drive.
/// </param>
/// <remarks>
/// This must be internal so that we allow the renaming of providers.
/// All drives must be associated with the new provider name and can
/// be changed using the Core Command API but not through a reference to the
/// drive object. More goes in to renaming a provider than just modifying
/// the provider in this class.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// If <paramref name="newProvider"/> is null.
/// </exception>
internal void SetProvider(ProviderInfo newProvider)
{
if (newProvider == null)
{
throw PSTraceSource.NewArgumentNullException("newProvider");
}
_provider = newProvider;
} // SetProvider
/// <summary>
/// Traces the virtual drive
/// </summary>
internal void Trace()
{
s_tracer.WriteLine(
"A drive was found:");
if (Name != null)
{
s_tracer.WriteLine(
"\tName: {0}",
Name);
}
if (Provider != null)
{
s_tracer.WriteLine(
"\tProvider: {0}",
Provider);
}
if (Root != null)
{
s_tracer.WriteLine(
"\tRoot: {0}",
Root);
}
if (CurrentLocation != null)
{
s_tracer.WriteLine(
"\tCWD: {0}",
CurrentLocation);
}
if (Description != null)
{
s_tracer.WriteLine(
"\tDescription: {0}",
Description);
}
}//Trace
/// <summary>
/// Compares this instance to the specified drive.
/// </summary>
/// <param name="drive">
/// A PSDriveInfo object to compare.
/// </param>
/// <returns>
/// A signed number indicating the relative values of this instance and object specified.
/// Return Value: Less than zero Meaning: This instance is less than object.
/// Return Value: Zero Meaning: This instance is equal to object.
/// Return Value: Greater than zero Meaning: This instance is greater than object or object is a null reference.
/// </returns>
public int CompareTo(PSDriveInfo drive)
{
#pragma warning disable 56506
if (drive == null)
{
throw PSTraceSource.NewArgumentNullException("drive");
}
return String.Compare(Name, drive.Name, StringComparison.OrdinalIgnoreCase);
#pragma warning restore 56506
}
/// <summary>
/// Compares this instance to the specified object. The object must be a PSDriveInfo.
/// </summary>
/// <param name="obj">
/// An object to compare.
/// </param>
/// <returns>
/// A signed number indicating the relative values of this
/// instance and object specified.
/// </returns>
/// <exception cref="ArgumentException">
/// If <paramref name="obj"/> is not a PSDriveInfo instance.
/// </exception>
public int CompareTo(object obj)
{
PSDriveInfo drive = obj as PSDriveInfo;
if (drive == null)
{
ArgumentException e =
PSTraceSource.NewArgumentException(
"obj",
SessionStateStrings.OnlyAbleToComparePSDriveInfo);
throw e;
}
return (CompareTo(drive));
}
/// <summary>
/// Compares this instance to the specified object.
/// </summary>
/// <param name="obj">
/// An object to compare.
/// </param>
/// <returns>
/// True if the drive names are equal, false otherwise.
/// </returns>
public override bool Equals(object obj)
{
if (obj is PSDriveInfo)
{
return CompareTo(obj) == 0;
}
else
{
return false;
}
}
/// <summary>
/// Compares this instance to the specified object.
/// </summary>
/// <param name="drive">
/// An object to compare.
/// </param>
/// <returns>
/// True if the drive names are equal, false otherwise.
/// </returns>
public bool Equals(PSDriveInfo drive)
{
return CompareTo(drive) == 0;
}
/// <summary>
/// Equality operator for the drive determines if the drives
/// are equal by having the same name.
/// </summary>
/// <param name="drive1">
/// The first object to compare to the second.
/// </param>
/// <param name="drive2">
/// The second object to compare to the first.
/// </param>
/// <returns>
/// True if the objects are PSDriveInfo objects and have the same name,
/// false otherwise.
/// </returns>
public static bool operator ==(PSDriveInfo drive1, PSDriveInfo drive2)
{
Object drive1Object = drive1;
Object drive2Object = drive2;
if ((drive1Object == null) == (drive2Object == null))
{
if (drive1Object != null)
{
return drive1.Equals(drive2);
}
return true;
}
else
{
return false;
}
}
/// <summary>
/// Inequality operator for the drive determines if the drives
/// are not equal by using the drive name.
/// </summary>
/// <param name="drive1">
/// The first object to compare to the second.
/// </param>
/// <param name="drive2">
/// The second object to compare to the first.
/// </param>
/// <returns>
/// True if the PSDriveInfo objects do not have the same name,
/// false otherwise.
/// </returns>
public static bool operator !=(PSDriveInfo drive1, PSDriveInfo drive2)
{
return !(drive1 == drive2);
}
/// <summary>
/// Compares the specified drives to determine if drive1 is less than
/// drive2.
/// </summary>
/// <param name="drive1">
/// The drive to determine if it is less than the other drive.
/// </param>
/// <param name="drive2">
/// The drive to compare drive1 against.
/// </param>
/// <returns>
/// True if the lexical comparison of drive1's name is less than drive2's name.
/// </returns>
public static bool operator <(PSDriveInfo drive1, PSDriveInfo drive2)
{
Object drive1Object = drive1;
Object drive2Object = drive2;
if (drive1Object == null)
{
return (drive2Object != null);
}
else
{
if (drive2Object == null)
{
// Since drive1 is not null and drive2 is, drive1 is greater than drive2
return false;
}
else
{
// Since drive1 and drive2 are not null use the CompareTo
return drive1.CompareTo(drive2) < 0;
}
}
} // operator <
/// <summary>
/// Compares the specified drives to determine if drive1 is greater than
/// drive2.
/// </summary>
/// <param name="drive1">
/// The drive to determine if it is greater than the other drive.
/// </param>
/// <param name="drive2">
/// The drive to compare drive1 against.
/// </param>
/// <returns>
/// True if the lexical comparison of drive1's name is greater than drive2's name.
/// </returns>
public static bool operator >(PSDriveInfo drive1, PSDriveInfo drive2)
{
Object drive1Object = drive1;
Object drive2Object = drive2;
if ((drive1Object == null))
{
// Since both drives are null, they are equal
// Since drive1 is null it is less than drive2 which is not null
return false;
}
else
{
if (drive2Object == null)
{
// Since drive1 is not null and drive2 is, drive1 is greater than drive2
return true;
}
else
{
// Since drive1 and drive2 are not null use the CompareTo
return drive1.CompareTo(drive2) > 0;
}
}
} // operator >
/// <summary>
/// Gets the hash code for this instance.
/// </summary>
/// <returns>The result of base.GetHashCode()</returns>
/// <!-- Override the base GetHashCode because the compiler complains
/// if you don't when you implement operator== and operator!= -->
public override int GetHashCode()
{
return base.GetHashCode();
}
private PSNoteProperty _noteProperty;
internal PSNoteProperty GetNotePropertyForProviderCmdlets(string name)
{
if (_noteProperty == null)
{
Interlocked.CompareExchange(ref _noteProperty,
new PSNoteProperty(name, this), null);
}
return _noteProperty;
}
}//Class PSDriveInfo
}
| 34.268999
| 124
| 0.524165
|
[
"MIT"
] |
Francisco-Gamino/PowerShell
|
src/System.Management.Automation/engine/DataStoreAdapter.cs
| 28,409
|
C#
|
using System.Collections.Generic;
namespace DotNextDemo.Roles.Dto
{
public class GetRoleForEditOutput
{
public RoleEditDto Role { get; set; }
public List<FlatPermissionDto> Permissions { get; set; }
public List<string> GrantedPermissionNames { get; set; }
}
}
| 23
| 64
| 0.67893
|
[
"MIT"
] |
a-merson/DotNext2019
|
aspnet-core/src/DotNextDemo.Application/Roles/Dto/GetRoleForEditOutput.cs
| 301
|
C#
|
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: global::Android.Runtime.ResourceDesignerAttribute("FormsSample.Droid.Resource", IsApplication=true)]
namespace FormsSample.Droid
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")]
public partial class Resource
{
static Resource()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
public static void UpdateIdValues()
{
global::Xamarin.Forms.Platform.Android.Resource.Attribute.actionBarSize = global::FormsSample.Droid.Resource.Attribute.actionBarSize;
}
public partial class Animation
{
// aapt resource value: 0x7f040000
public const int abc_fade_in = 2130968576;
// aapt resource value: 0x7f040001
public const int abc_fade_out = 2130968577;
// aapt resource value: 0x7f040002
public const int abc_grow_fade_in_from_bottom = 2130968578;
// aapt resource value: 0x7f040003
public const int abc_popup_enter = 2130968579;
// aapt resource value: 0x7f040004
public const int abc_popup_exit = 2130968580;
// aapt resource value: 0x7f040005
public const int abc_shrink_fade_out_from_bottom = 2130968581;
// aapt resource value: 0x7f040006
public const int abc_slide_in_bottom = 2130968582;
// aapt resource value: 0x7f040007
public const int abc_slide_in_top = 2130968583;
// aapt resource value: 0x7f040008
public const int abc_slide_out_bottom = 2130968584;
// aapt resource value: 0x7f040009
public const int abc_slide_out_top = 2130968585;
// aapt resource value: 0x7f04000a
public const int design_bottom_sheet_slide_in = 2130968586;
// aapt resource value: 0x7f04000b
public const int design_bottom_sheet_slide_out = 2130968587;
// aapt resource value: 0x7f04000c
public const int design_fab_in = 2130968588;
// aapt resource value: 0x7f04000d
public const int design_fab_out = 2130968589;
// aapt resource value: 0x7f04000e
public const int design_snackbar_in = 2130968590;
// aapt resource value: 0x7f04000f
public const int design_snackbar_out = 2130968591;
static Animation()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Animation()
{
}
}
public partial class Animator
{
// aapt resource value: 0x7f050000
public const int design_appbar_state_list_animator = 2131034112;
static Animator()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Animator()
{
}
}
public partial class Attribute
{
// aapt resource value: 0x7f01005f
public const int actionBarDivider = 2130772063;
// aapt resource value: 0x7f010060
public const int actionBarItemBackground = 2130772064;
// aapt resource value: 0x7f010059
public const int actionBarPopupTheme = 2130772057;
// aapt resource value: 0x7f01005e
public const int actionBarSize = 2130772062;
// aapt resource value: 0x7f01005b
public const int actionBarSplitStyle = 2130772059;
// aapt resource value: 0x7f01005a
public const int actionBarStyle = 2130772058;
// aapt resource value: 0x7f010055
public const int actionBarTabBarStyle = 2130772053;
// aapt resource value: 0x7f010054
public const int actionBarTabStyle = 2130772052;
// aapt resource value: 0x7f010056
public const int actionBarTabTextStyle = 2130772054;
// aapt resource value: 0x7f01005c
public const int actionBarTheme = 2130772060;
// aapt resource value: 0x7f01005d
public const int actionBarWidgetTheme = 2130772061;
// aapt resource value: 0x7f01007a
public const int actionButtonStyle = 2130772090;
// aapt resource value: 0x7f010076
public const int actionDropDownStyle = 2130772086;
// aapt resource value: 0x7f0100cc
public const int actionLayout = 2130772172;
// aapt resource value: 0x7f010061
public const int actionMenuTextAppearance = 2130772065;
// aapt resource value: 0x7f010062
public const int actionMenuTextColor = 2130772066;
// aapt resource value: 0x7f010065
public const int actionModeBackground = 2130772069;
// aapt resource value: 0x7f010064
public const int actionModeCloseButtonStyle = 2130772068;
// aapt resource value: 0x7f010067
public const int actionModeCloseDrawable = 2130772071;
// aapt resource value: 0x7f010069
public const int actionModeCopyDrawable = 2130772073;
// aapt resource value: 0x7f010068
public const int actionModeCutDrawable = 2130772072;
// aapt resource value: 0x7f01006d
public const int actionModeFindDrawable = 2130772077;
// aapt resource value: 0x7f01006a
public const int actionModePasteDrawable = 2130772074;
// aapt resource value: 0x7f01006f
public const int actionModePopupWindowStyle = 2130772079;
// aapt resource value: 0x7f01006b
public const int actionModeSelectAllDrawable = 2130772075;
// aapt resource value: 0x7f01006c
public const int actionModeShareDrawable = 2130772076;
// aapt resource value: 0x7f010066
public const int actionModeSplitBackground = 2130772070;
// aapt resource value: 0x7f010063
public const int actionModeStyle = 2130772067;
// aapt resource value: 0x7f01006e
public const int actionModeWebSearchDrawable = 2130772078;
// aapt resource value: 0x7f010057
public const int actionOverflowButtonStyle = 2130772055;
// aapt resource value: 0x7f010058
public const int actionOverflowMenuStyle = 2130772056;
// aapt resource value: 0x7f0100ce
public const int actionProviderClass = 2130772174;
// aapt resource value: 0x7f0100cd
public const int actionViewClass = 2130772173;
// aapt resource value: 0x7f010082
public const int activityChooserViewStyle = 2130772098;
// aapt resource value: 0x7f0100a7
public const int alertDialogButtonGroupStyle = 2130772135;
// aapt resource value: 0x7f0100a8
public const int alertDialogCenterButtons = 2130772136;
// aapt resource value: 0x7f0100a6
public const int alertDialogStyle = 2130772134;
// aapt resource value: 0x7f0100a9
public const int alertDialogTheme = 2130772137;
// aapt resource value: 0x7f0100bc
public const int allowStacking = 2130772156;
// aapt resource value: 0x7f0100bd
public const int alpha = 2130772157;
// aapt resource value: 0x7f0100c4
public const int arrowHeadLength = 2130772164;
// aapt resource value: 0x7f0100c5
public const int arrowShaftLength = 2130772165;
// aapt resource value: 0x7f0100ae
public const int autoCompleteTextViewStyle = 2130772142;
// aapt resource value: 0x7f010028
public const int background = 2130772008;
// aapt resource value: 0x7f01002a
public const int backgroundSplit = 2130772010;
// aapt resource value: 0x7f010029
public const int backgroundStacked = 2130772009;
// aapt resource value: 0x7f010101
public const int backgroundTint = 2130772225;
// aapt resource value: 0x7f010102
public const int backgroundTintMode = 2130772226;
// aapt resource value: 0x7f0100c6
public const int barLength = 2130772166;
// aapt resource value: 0x7f01012c
public const int behavior_autoHide = 2130772268;
// aapt resource value: 0x7f010109
public const int behavior_hideable = 2130772233;
// aapt resource value: 0x7f010135
public const int behavior_overlapTop = 2130772277;
// aapt resource value: 0x7f010108
public const int behavior_peekHeight = 2130772232;
// aapt resource value: 0x7f01010a
public const int behavior_skipCollapsed = 2130772234;
// aapt resource value: 0x7f01012a
public const int borderWidth = 2130772266;
// aapt resource value: 0x7f01007f
public const int borderlessButtonStyle = 2130772095;
// aapt resource value: 0x7f010124
public const int bottomSheetDialogTheme = 2130772260;
// aapt resource value: 0x7f010125
public const int bottomSheetStyle = 2130772261;
// aapt resource value: 0x7f01007c
public const int buttonBarButtonStyle = 2130772092;
// aapt resource value: 0x7f0100ac
public const int buttonBarNegativeButtonStyle = 2130772140;
// aapt resource value: 0x7f0100ad
public const int buttonBarNeutralButtonStyle = 2130772141;
// aapt resource value: 0x7f0100ab
public const int buttonBarPositiveButtonStyle = 2130772139;
// aapt resource value: 0x7f01007b
public const int buttonBarStyle = 2130772091;
// aapt resource value: 0x7f0100f6
public const int buttonGravity = 2130772214;
// aapt resource value: 0x7f01003d
public const int buttonPanelSideLayout = 2130772029;
// aapt resource value: 0x7f0100af
public const int buttonStyle = 2130772143;
// aapt resource value: 0x7f0100b0
public const int buttonStyleSmall = 2130772144;
// aapt resource value: 0x7f0100be
public const int buttonTint = 2130772158;
// aapt resource value: 0x7f0100bf
public const int buttonTintMode = 2130772159;
// aapt resource value: 0x7f010011
public const int cardBackgroundColor = 2130771985;
// aapt resource value: 0x7f010012
public const int cardCornerRadius = 2130771986;
// aapt resource value: 0x7f010013
public const int cardElevation = 2130771987;
// aapt resource value: 0x7f010014
public const int cardMaxElevation = 2130771988;
// aapt resource value: 0x7f010016
public const int cardPreventCornerOverlap = 2130771990;
// aapt resource value: 0x7f010015
public const int cardUseCompatPadding = 2130771989;
// aapt resource value: 0x7f0100b1
public const int checkboxStyle = 2130772145;
// aapt resource value: 0x7f0100b2
public const int checkedTextViewStyle = 2130772146;
// aapt resource value: 0x7f0100d9
public const int closeIcon = 2130772185;
// aapt resource value: 0x7f01003a
public const int closeItemLayout = 2130772026;
// aapt resource value: 0x7f0100f8
public const int collapseContentDescription = 2130772216;
// aapt resource value: 0x7f0100f7
public const int collapseIcon = 2130772215;
// aapt resource value: 0x7f010117
public const int collapsedTitleGravity = 2130772247;
// aapt resource value: 0x7f010111
public const int collapsedTitleTextAppearance = 2130772241;
// aapt resource value: 0x7f0100c0
public const int color = 2130772160;
// aapt resource value: 0x7f01009e
public const int colorAccent = 2130772126;
// aapt resource value: 0x7f0100a5
public const int colorBackgroundFloating = 2130772133;
// aapt resource value: 0x7f0100a2
public const int colorButtonNormal = 2130772130;
// aapt resource value: 0x7f0100a0
public const int colorControlActivated = 2130772128;
// aapt resource value: 0x7f0100a1
public const int colorControlHighlight = 2130772129;
// aapt resource value: 0x7f01009f
public const int colorControlNormal = 2130772127;
// aapt resource value: 0x7f01009c
public const int colorPrimary = 2130772124;
// aapt resource value: 0x7f01009d
public const int colorPrimaryDark = 2130772125;
// aapt resource value: 0x7f0100a3
public const int colorSwitchThumbNormal = 2130772131;
// aapt resource value: 0x7f0100de
public const int commitIcon = 2130772190;
// aapt resource value: 0x7f010033
public const int contentInsetEnd = 2130772019;
// aapt resource value: 0x7f010037
public const int contentInsetEndWithActions = 2130772023;
// aapt resource value: 0x7f010034
public const int contentInsetLeft = 2130772020;
// aapt resource value: 0x7f010035
public const int contentInsetRight = 2130772021;
// aapt resource value: 0x7f010032
public const int contentInsetStart = 2130772018;
// aapt resource value: 0x7f010036
public const int contentInsetStartWithNavigation = 2130772022;
// aapt resource value: 0x7f010017
public const int contentPadding = 2130771991;
// aapt resource value: 0x7f01001b
public const int contentPaddingBottom = 2130771995;
// aapt resource value: 0x7f010018
public const int contentPaddingLeft = 2130771992;
// aapt resource value: 0x7f010019
public const int contentPaddingRight = 2130771993;
// aapt resource value: 0x7f01001a
public const int contentPaddingTop = 2130771994;
// aapt resource value: 0x7f010112
public const int contentScrim = 2130772242;
// aapt resource value: 0x7f0100a4
public const int controlBackground = 2130772132;
// aapt resource value: 0x7f01014b
public const int counterEnabled = 2130772299;
// aapt resource value: 0x7f01014c
public const int counterMaxLength = 2130772300;
// aapt resource value: 0x7f01014e
public const int counterOverflowTextAppearance = 2130772302;
// aapt resource value: 0x7f01014d
public const int counterTextAppearance = 2130772301;
// aapt resource value: 0x7f01002b
public const int customNavigationLayout = 2130772011;
// aapt resource value: 0x7f0100d8
public const int defaultQueryHint = 2130772184;
// aapt resource value: 0x7f010074
public const int dialogPreferredPadding = 2130772084;
// aapt resource value: 0x7f010073
public const int dialogTheme = 2130772083;
// aapt resource value: 0x7f010021
public const int displayOptions = 2130772001;
// aapt resource value: 0x7f010027
public const int divider = 2130772007;
// aapt resource value: 0x7f010081
public const int dividerHorizontal = 2130772097;
// aapt resource value: 0x7f0100ca
public const int dividerPadding = 2130772170;
// aapt resource value: 0x7f010080
public const int dividerVertical = 2130772096;
// aapt resource value: 0x7f0100c2
public const int drawableSize = 2130772162;
// aapt resource value: 0x7f01001c
public const int drawerArrowStyle = 2130771996;
// aapt resource value: 0x7f010093
public const int dropDownListViewStyle = 2130772115;
// aapt resource value: 0x7f010077
public const int dropdownListPreferredItemHeight = 2130772087;
// aapt resource value: 0x7f010088
public const int editTextBackground = 2130772104;
// aapt resource value: 0x7f010087
public const int editTextColor = 2130772103;
// aapt resource value: 0x7f0100b3
public const int editTextStyle = 2130772147;
// aapt resource value: 0x7f010038
public const int elevation = 2130772024;
// aapt resource value: 0x7f010149
public const int errorEnabled = 2130772297;
// aapt resource value: 0x7f01014a
public const int errorTextAppearance = 2130772298;
// aapt resource value: 0x7f01003c
public const int expandActivityOverflowButtonDrawable = 2130772028;
// aapt resource value: 0x7f010103
public const int expanded = 2130772227;
// aapt resource value: 0x7f010118
public const int expandedTitleGravity = 2130772248;
// aapt resource value: 0x7f01010b
public const int expandedTitleMargin = 2130772235;
// aapt resource value: 0x7f01010f
public const int expandedTitleMarginBottom = 2130772239;
// aapt resource value: 0x7f01010e
public const int expandedTitleMarginEnd = 2130772238;
// aapt resource value: 0x7f01010c
public const int expandedTitleMarginStart = 2130772236;
// aapt resource value: 0x7f01010d
public const int expandedTitleMarginTop = 2130772237;
// aapt resource value: 0x7f010110
public const int expandedTitleTextAppearance = 2130772240;
// aapt resource value: 0x7f010010
public const int externalRouteEnabledDrawable = 2130771984;
// aapt resource value: 0x7f010128
public const int fabSize = 2130772264;
// aapt resource value: 0x7f01012d
public const int foregroundInsidePadding = 2130772269;
// aapt resource value: 0x7f0100c3
public const int gapBetweenBars = 2130772163;
// aapt resource value: 0x7f0100da
public const int goIcon = 2130772186;
// aapt resource value: 0x7f010133
public const int headerLayout = 2130772275;
// aapt resource value: 0x7f01001d
public const int height = 2130771997;
// aapt resource value: 0x7f010031
public const int hideOnContentScroll = 2130772017;
// aapt resource value: 0x7f01014f
public const int hintAnimationEnabled = 2130772303;
// aapt resource value: 0x7f010148
public const int hintEnabled = 2130772296;
// aapt resource value: 0x7f010147
public const int hintTextAppearance = 2130772295;
// aapt resource value: 0x7f010079
public const int homeAsUpIndicator = 2130772089;
// aapt resource value: 0x7f01002c
public const int homeLayout = 2130772012;
// aapt resource value: 0x7f010025
public const int icon = 2130772005;
// aapt resource value: 0x7f0100d6
public const int iconifiedByDefault = 2130772182;
// aapt resource value: 0x7f010089
public const int imageButtonStyle = 2130772105;
// aapt resource value: 0x7f01002e
public const int indeterminateProgressStyle = 2130772014;
// aapt resource value: 0x7f01003b
public const int initialActivityCount = 2130772027;
// aapt resource value: 0x7f010134
public const int insetForeground = 2130772276;
// aapt resource value: 0x7f01001e
public const int isLightTheme = 2130771998;
// aapt resource value: 0x7f010131
public const int itemBackground = 2130772273;
// aapt resource value: 0x7f01012f
public const int itemIconTint = 2130772271;
// aapt resource value: 0x7f010030
public const int itemPadding = 2130772016;
// aapt resource value: 0x7f010132
public const int itemTextAppearance = 2130772274;
// aapt resource value: 0x7f010130
public const int itemTextColor = 2130772272;
// aapt resource value: 0x7f01011c
public const int keylines = 2130772252;
// aapt resource value: 0x7f0100d5
public const int layout = 2130772181;
// aapt resource value: 0x7f010000
public const int layoutManager = 2130771968;
// aapt resource value: 0x7f01011f
public const int layout_anchor = 2130772255;
// aapt resource value: 0x7f010121
public const int layout_anchorGravity = 2130772257;
// aapt resource value: 0x7f01011e
public const int layout_behavior = 2130772254;
// aapt resource value: 0x7f01011a
public const int layout_collapseMode = 2130772250;
// aapt resource value: 0x7f01011b
public const int layout_collapseParallaxMultiplier = 2130772251;
// aapt resource value: 0x7f010123
public const int layout_dodgeInsetEdges = 2130772259;
// aapt resource value: 0x7f010122
public const int layout_insetEdge = 2130772258;
// aapt resource value: 0x7f010120
public const int layout_keyline = 2130772256;
// aapt resource value: 0x7f010106
public const int layout_scrollFlags = 2130772230;
// aapt resource value: 0x7f010107
public const int layout_scrollInterpolator = 2130772231;
// aapt resource value: 0x7f01009b
public const int listChoiceBackgroundIndicator = 2130772123;
// aapt resource value: 0x7f010075
public const int listDividerAlertDialog = 2130772085;
// aapt resource value: 0x7f010041
public const int listItemLayout = 2130772033;
// aapt resource value: 0x7f01003e
public const int listLayout = 2130772030;
// aapt resource value: 0x7f0100bb
public const int listMenuViewStyle = 2130772155;
// aapt resource value: 0x7f010094
public const int listPopupWindowStyle = 2130772116;
// aapt resource value: 0x7f01008e
public const int listPreferredItemHeight = 2130772110;
// aapt resource value: 0x7f010090
public const int listPreferredItemHeightLarge = 2130772112;
// aapt resource value: 0x7f01008f
public const int listPreferredItemHeightSmall = 2130772111;
// aapt resource value: 0x7f010091
public const int listPreferredItemPaddingLeft = 2130772113;
// aapt resource value: 0x7f010092
public const int listPreferredItemPaddingRight = 2130772114;
// aapt resource value: 0x7f010026
public const int logo = 2130772006;
// aapt resource value: 0x7f0100fb
public const int logoDescription = 2130772219;
// aapt resource value: 0x7f010136
public const int maxActionInlineWidth = 2130772278;
// aapt resource value: 0x7f0100f5
public const int maxButtonHeight = 2130772213;
// aapt resource value: 0x7f0100c8
public const int measureWithLargestChild = 2130772168;
// aapt resource value: 0x7f010004
public const int mediaRouteAudioTrackDrawable = 2130771972;
// aapt resource value: 0x7f010005
public const int mediaRouteButtonStyle = 2130771973;
// aapt resource value: 0x7f010006
public const int mediaRouteCloseDrawable = 2130771974;
// aapt resource value: 0x7f010007
public const int mediaRouteControlPanelThemeOverlay = 2130771975;
// aapt resource value: 0x7f010008
public const int mediaRouteDefaultIconDrawable = 2130771976;
// aapt resource value: 0x7f010009
public const int mediaRoutePauseDrawable = 2130771977;
// aapt resource value: 0x7f01000a
public const int mediaRoutePlayDrawable = 2130771978;
// aapt resource value: 0x7f01000b
public const int mediaRouteSpeakerGroupIconDrawable = 2130771979;
// aapt resource value: 0x7f01000c
public const int mediaRouteSpeakerIconDrawable = 2130771980;
// aapt resource value: 0x7f01000d
public const int mediaRouteStopDrawable = 2130771981;
// aapt resource value: 0x7f01000e
public const int mediaRouteTheme = 2130771982;
// aapt resource value: 0x7f01000f
public const int mediaRouteTvIconDrawable = 2130771983;
// aapt resource value: 0x7f01012e
public const int menu = 2130772270;
// aapt resource value: 0x7f01003f
public const int multiChoiceItemLayout = 2130772031;
// aapt resource value: 0x7f0100fa
public const int navigationContentDescription = 2130772218;
// aapt resource value: 0x7f0100f9
public const int navigationIcon = 2130772217;
// aapt resource value: 0x7f010020
public const int navigationMode = 2130772000;
// aapt resource value: 0x7f0100d1
public const int overlapAnchor = 2130772177;
// aapt resource value: 0x7f0100d3
public const int paddingBottomNoButtons = 2130772179;
// aapt resource value: 0x7f0100ff
public const int paddingEnd = 2130772223;
// aapt resource value: 0x7f0100fe
public const int paddingStart = 2130772222;
// aapt resource value: 0x7f0100d4
public const int paddingTopNoTitle = 2130772180;
// aapt resource value: 0x7f010098
public const int panelBackground = 2130772120;
// aapt resource value: 0x7f01009a
public const int panelMenuListTheme = 2130772122;
// aapt resource value: 0x7f010099
public const int panelMenuListWidth = 2130772121;
// aapt resource value: 0x7f010152
public const int passwordToggleContentDescription = 2130772306;
// aapt resource value: 0x7f010151
public const int passwordToggleDrawable = 2130772305;
// aapt resource value: 0x7f010150
public const int passwordToggleEnabled = 2130772304;
// aapt resource value: 0x7f010153
public const int passwordToggleTint = 2130772307;
// aapt resource value: 0x7f010154
public const int passwordToggleTintMode = 2130772308;
// aapt resource value: 0x7f010085
public const int popupMenuStyle = 2130772101;
// aapt resource value: 0x7f010039
public const int popupTheme = 2130772025;
// aapt resource value: 0x7f010086
public const int popupWindowStyle = 2130772102;
// aapt resource value: 0x7f0100cf
public const int preserveIconSpacing = 2130772175;
// aapt resource value: 0x7f010129
public const int pressedTranslationZ = 2130772265;
// aapt resource value: 0x7f01002f
public const int progressBarPadding = 2130772015;
// aapt resource value: 0x7f01002d
public const int progressBarStyle = 2130772013;
// aapt resource value: 0x7f0100e0
public const int queryBackground = 2130772192;
// aapt resource value: 0x7f0100d7
public const int queryHint = 2130772183;
// aapt resource value: 0x7f0100b4
public const int radioButtonStyle = 2130772148;
// aapt resource value: 0x7f0100b5
public const int ratingBarStyle = 2130772149;
// aapt resource value: 0x7f0100b6
public const int ratingBarStyleIndicator = 2130772150;
// aapt resource value: 0x7f0100b7
public const int ratingBarStyleSmall = 2130772151;
// aapt resource value: 0x7f010002
public const int reverseLayout = 2130771970;
// aapt resource value: 0x7f010127
public const int rippleColor = 2130772263;
// aapt resource value: 0x7f010116
public const int scrimAnimationDuration = 2130772246;
// aapt resource value: 0x7f010115
public const int scrimVisibleHeightTrigger = 2130772245;
// aapt resource value: 0x7f0100dc
public const int searchHintIcon = 2130772188;
// aapt resource value: 0x7f0100db
public const int searchIcon = 2130772187;
// aapt resource value: 0x7f01008d
public const int searchViewStyle = 2130772109;
// aapt resource value: 0x7f0100b8
public const int seekBarStyle = 2130772152;
// aapt resource value: 0x7f01007d
public const int selectableItemBackground = 2130772093;
// aapt resource value: 0x7f01007e
public const int selectableItemBackgroundBorderless = 2130772094;
// aapt resource value: 0x7f0100cb
public const int showAsAction = 2130772171;
// aapt resource value: 0x7f0100c9
public const int showDividers = 2130772169;
// aapt resource value: 0x7f0100ec
public const int showText = 2130772204;
// aapt resource value: 0x7f010042
public const int showTitle = 2130772034;
// aapt resource value: 0x7f010040
public const int singleChoiceItemLayout = 2130772032;
// aapt resource value: 0x7f010001
public const int spanCount = 2130771969;
// aapt resource value: 0x7f0100c1
public const int spinBars = 2130772161;
// aapt resource value: 0x7f010078
public const int spinnerDropDownItemStyle = 2130772088;
// aapt resource value: 0x7f0100b9
public const int spinnerStyle = 2130772153;
// aapt resource value: 0x7f0100eb
public const int splitTrack = 2130772203;
// aapt resource value: 0x7f010043
public const int srcCompat = 2130772035;
// aapt resource value: 0x7f010003
public const int stackFromEnd = 2130771971;
// aapt resource value: 0x7f0100d2
public const int state_above_anchor = 2130772178;
// aapt resource value: 0x7f010104
public const int state_collapsed = 2130772228;
// aapt resource value: 0x7f010105
public const int state_collapsible = 2130772229;
// aapt resource value: 0x7f01011d
public const int statusBarBackground = 2130772253;
// aapt resource value: 0x7f010113
public const int statusBarScrim = 2130772243;
// aapt resource value: 0x7f0100d0
public const int subMenuArrow = 2130772176;
// aapt resource value: 0x7f0100e1
public const int submitBackground = 2130772193;
// aapt resource value: 0x7f010022
public const int subtitle = 2130772002;
// aapt resource value: 0x7f0100ee
public const int subtitleTextAppearance = 2130772206;
// aapt resource value: 0x7f0100fd
public const int subtitleTextColor = 2130772221;
// aapt resource value: 0x7f010024
public const int subtitleTextStyle = 2130772004;
// aapt resource value: 0x7f0100df
public const int suggestionRowLayout = 2130772191;
// aapt resource value: 0x7f0100e9
public const int switchMinWidth = 2130772201;
// aapt resource value: 0x7f0100ea
public const int switchPadding = 2130772202;
// aapt resource value: 0x7f0100ba
public const int switchStyle = 2130772154;
// aapt resource value: 0x7f0100e8
public const int switchTextAppearance = 2130772200;
// aapt resource value: 0x7f01013a
public const int tabBackground = 2130772282;
// aapt resource value: 0x7f010139
public const int tabContentStart = 2130772281;
// aapt resource value: 0x7f01013c
public const int tabGravity = 2130772284;
// aapt resource value: 0x7f010137
public const int tabIndicatorColor = 2130772279;
// aapt resource value: 0x7f010138
public const int tabIndicatorHeight = 2130772280;
// aapt resource value: 0x7f01013e
public const int tabMaxWidth = 2130772286;
// aapt resource value: 0x7f01013d
public const int tabMinWidth = 2130772285;
// aapt resource value: 0x7f01013b
public const int tabMode = 2130772283;
// aapt resource value: 0x7f010146
public const int tabPadding = 2130772294;
// aapt resource value: 0x7f010145
public const int tabPaddingBottom = 2130772293;
// aapt resource value: 0x7f010144
public const int tabPaddingEnd = 2130772292;
// aapt resource value: 0x7f010142
public const int tabPaddingStart = 2130772290;
// aapt resource value: 0x7f010143
public const int tabPaddingTop = 2130772291;
// aapt resource value: 0x7f010141
public const int tabSelectedTextColor = 2130772289;
// aapt resource value: 0x7f01013f
public const int tabTextAppearance = 2130772287;
// aapt resource value: 0x7f010140
public const int tabTextColor = 2130772288;
// aapt resource value: 0x7f010049
public const int textAllCaps = 2130772041;
// aapt resource value: 0x7f010070
public const int textAppearanceLargePopupMenu = 2130772080;
// aapt resource value: 0x7f010095
public const int textAppearanceListItem = 2130772117;
// aapt resource value: 0x7f010096
public const int textAppearanceListItemSecondary = 2130772118;
// aapt resource value: 0x7f010097
public const int textAppearanceListItemSmall = 2130772119;
// aapt resource value: 0x7f010072
public const int textAppearancePopupMenuHeader = 2130772082;
// aapt resource value: 0x7f01008b
public const int textAppearanceSearchResultSubtitle = 2130772107;
// aapt resource value: 0x7f01008a
public const int textAppearanceSearchResultTitle = 2130772106;
// aapt resource value: 0x7f010071
public const int textAppearanceSmallPopupMenu = 2130772081;
// aapt resource value: 0x7f0100aa
public const int textColorAlertDialogListItem = 2130772138;
// aapt resource value: 0x7f010126
public const int textColorError = 2130772262;
// aapt resource value: 0x7f01008c
public const int textColorSearchUrl = 2130772108;
// aapt resource value: 0x7f010100
public const int theme = 2130772224;
// aapt resource value: 0x7f0100c7
public const int thickness = 2130772167;
// aapt resource value: 0x7f0100e7
public const int thumbTextPadding = 2130772199;
// aapt resource value: 0x7f0100e2
public const int thumbTint = 2130772194;
// aapt resource value: 0x7f0100e3
public const int thumbTintMode = 2130772195;
// aapt resource value: 0x7f010046
public const int tickMark = 2130772038;
// aapt resource value: 0x7f010047
public const int tickMarkTint = 2130772039;
// aapt resource value: 0x7f010048
public const int tickMarkTintMode = 2130772040;
// aapt resource value: 0x7f010044
public const int tint = 2130772036;
// aapt resource value: 0x7f010045
public const int tintMode = 2130772037;
// aapt resource value: 0x7f01001f
public const int title = 2130771999;
// aapt resource value: 0x7f010119
public const int titleEnabled = 2130772249;
// aapt resource value: 0x7f0100ef
public const int titleMargin = 2130772207;
// aapt resource value: 0x7f0100f3
public const int titleMarginBottom = 2130772211;
// aapt resource value: 0x7f0100f1
public const int titleMarginEnd = 2130772209;
// aapt resource value: 0x7f0100f0
public const int titleMarginStart = 2130772208;
// aapt resource value: 0x7f0100f2
public const int titleMarginTop = 2130772210;
// aapt resource value: 0x7f0100f4
public const int titleMargins = 2130772212;
// aapt resource value: 0x7f0100ed
public const int titleTextAppearance = 2130772205;
// aapt resource value: 0x7f0100fc
public const int titleTextColor = 2130772220;
// aapt resource value: 0x7f010023
public const int titleTextStyle = 2130772003;
// aapt resource value: 0x7f010114
public const int toolbarId = 2130772244;
// aapt resource value: 0x7f010084
public const int toolbarNavigationButtonStyle = 2130772100;
// aapt resource value: 0x7f010083
public const int toolbarStyle = 2130772099;
// aapt resource value: 0x7f0100e4
public const int track = 2130772196;
// aapt resource value: 0x7f0100e5
public const int trackTint = 2130772197;
// aapt resource value: 0x7f0100e6
public const int trackTintMode = 2130772198;
// aapt resource value: 0x7f01012b
public const int useCompatPadding = 2130772267;
// aapt resource value: 0x7f0100dd
public const int voiceIcon = 2130772189;
// aapt resource value: 0x7f01004a
public const int windowActionBar = 2130772042;
// aapt resource value: 0x7f01004c
public const int windowActionBarOverlay = 2130772044;
// aapt resource value: 0x7f01004d
public const int windowActionModeOverlay = 2130772045;
// aapt resource value: 0x7f010051
public const int windowFixedHeightMajor = 2130772049;
// aapt resource value: 0x7f01004f
public const int windowFixedHeightMinor = 2130772047;
// aapt resource value: 0x7f01004e
public const int windowFixedWidthMajor = 2130772046;
// aapt resource value: 0x7f010050
public const int windowFixedWidthMinor = 2130772048;
// aapt resource value: 0x7f010052
public const int windowMinWidthMajor = 2130772050;
// aapt resource value: 0x7f010053
public const int windowMinWidthMinor = 2130772051;
// aapt resource value: 0x7f01004b
public const int windowNoTitle = 2130772043;
static Attribute()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Attribute()
{
}
}
public partial class Boolean
{
// aapt resource value: 0x7f0d0000
public const int abc_action_bar_embed_tabs = 2131558400;
// aapt resource value: 0x7f0d0001
public const int abc_allow_stacked_button_bar = 2131558401;
// aapt resource value: 0x7f0d0002
public const int abc_config_actionMenuItemAllCaps = 2131558402;
// aapt resource value: 0x7f0d0003
public const int abc_config_closeDialogWhenTouchOutside = 2131558403;
// aapt resource value: 0x7f0d0004
public const int abc_config_showMenuShortcutsWhenKeyboardPresent = 2131558404;
static Boolean()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Boolean()
{
}
}
public partial class Color
{
// aapt resource value: 0x7f0c004a
public const int abc_background_cache_hint_selector_material_dark = 2131492938;
// aapt resource value: 0x7f0c004b
public const int abc_background_cache_hint_selector_material_light = 2131492939;
// aapt resource value: 0x7f0c004c
public const int abc_btn_colored_borderless_text_material = 2131492940;
// aapt resource value: 0x7f0c004d
public const int abc_btn_colored_text_material = 2131492941;
// aapt resource value: 0x7f0c004e
public const int abc_color_highlight_material = 2131492942;
// aapt resource value: 0x7f0c004f
public const int abc_hint_foreground_material_dark = 2131492943;
// aapt resource value: 0x7f0c0050
public const int abc_hint_foreground_material_light = 2131492944;
// aapt resource value: 0x7f0c0005
public const int abc_input_method_navigation_guard = 2131492869;
// aapt resource value: 0x7f0c0051
public const int abc_primary_text_disable_only_material_dark = 2131492945;
// aapt resource value: 0x7f0c0052
public const int abc_primary_text_disable_only_material_light = 2131492946;
// aapt resource value: 0x7f0c0053
public const int abc_primary_text_material_dark = 2131492947;
// aapt resource value: 0x7f0c0054
public const int abc_primary_text_material_light = 2131492948;
// aapt resource value: 0x7f0c0055
public const int abc_search_url_text = 2131492949;
// aapt resource value: 0x7f0c0006
public const int abc_search_url_text_normal = 2131492870;
// aapt resource value: 0x7f0c0007
public const int abc_search_url_text_pressed = 2131492871;
// aapt resource value: 0x7f0c0008
public const int abc_search_url_text_selected = 2131492872;
// aapt resource value: 0x7f0c0056
public const int abc_secondary_text_material_dark = 2131492950;
// aapt resource value: 0x7f0c0057
public const int abc_secondary_text_material_light = 2131492951;
// aapt resource value: 0x7f0c0058
public const int abc_tint_btn_checkable = 2131492952;
// aapt resource value: 0x7f0c0059
public const int abc_tint_default = 2131492953;
// aapt resource value: 0x7f0c005a
public const int abc_tint_edittext = 2131492954;
// aapt resource value: 0x7f0c005b
public const int abc_tint_seek_thumb = 2131492955;
// aapt resource value: 0x7f0c005c
public const int abc_tint_spinner = 2131492956;
// aapt resource value: 0x7f0c005d
public const int abc_tint_switch_thumb = 2131492957;
// aapt resource value: 0x7f0c005e
public const int abc_tint_switch_track = 2131492958;
// aapt resource value: 0x7f0c0009
public const int accent_material_dark = 2131492873;
// aapt resource value: 0x7f0c000a
public const int accent_material_light = 2131492874;
// aapt resource value: 0x7f0c000b
public const int background_floating_material_dark = 2131492875;
// aapt resource value: 0x7f0c000c
public const int background_floating_material_light = 2131492876;
// aapt resource value: 0x7f0c000d
public const int background_material_dark = 2131492877;
// aapt resource value: 0x7f0c000e
public const int background_material_light = 2131492878;
// aapt resource value: 0x7f0c000f
public const int bright_foreground_disabled_material_dark = 2131492879;
// aapt resource value: 0x7f0c0010
public const int bright_foreground_disabled_material_light = 2131492880;
// aapt resource value: 0x7f0c0011
public const int bright_foreground_inverse_material_dark = 2131492881;
// aapt resource value: 0x7f0c0012
public const int bright_foreground_inverse_material_light = 2131492882;
// aapt resource value: 0x7f0c0013
public const int bright_foreground_material_dark = 2131492883;
// aapt resource value: 0x7f0c0014
public const int bright_foreground_material_light = 2131492884;
// aapt resource value: 0x7f0c0015
public const int button_material_dark = 2131492885;
// aapt resource value: 0x7f0c0016
public const int button_material_light = 2131492886;
// aapt resource value: 0x7f0c0000
public const int cardview_dark_background = 2131492864;
// aapt resource value: 0x7f0c0001
public const int cardview_light_background = 2131492865;
// aapt resource value: 0x7f0c0002
public const int cardview_shadow_end_color = 2131492866;
// aapt resource value: 0x7f0c0003
public const int cardview_shadow_start_color = 2131492867;
// aapt resource value: 0x7f0c003f
public const int design_bottom_navigation_shadow_color = 2131492927;
// aapt resource value: 0x7f0c005f
public const int design_error = 2131492959;
// aapt resource value: 0x7f0c0040
public const int design_fab_shadow_end_color = 2131492928;
// aapt resource value: 0x7f0c0041
public const int design_fab_shadow_mid_color = 2131492929;
// aapt resource value: 0x7f0c0042
public const int design_fab_shadow_start_color = 2131492930;
// aapt resource value: 0x7f0c0043
public const int design_fab_stroke_end_inner_color = 2131492931;
// aapt resource value: 0x7f0c0044
public const int design_fab_stroke_end_outer_color = 2131492932;
// aapt resource value: 0x7f0c0045
public const int design_fab_stroke_top_inner_color = 2131492933;
// aapt resource value: 0x7f0c0046
public const int design_fab_stroke_top_outer_color = 2131492934;
// aapt resource value: 0x7f0c0047
public const int design_snackbar_background_color = 2131492935;
// aapt resource value: 0x7f0c0048
public const int design_textinput_error_color_dark = 2131492936;
// aapt resource value: 0x7f0c0049
public const int design_textinput_error_color_light = 2131492937;
// aapt resource value: 0x7f0c0060
public const int design_tint_password_toggle = 2131492960;
// aapt resource value: 0x7f0c0017
public const int dim_foreground_disabled_material_dark = 2131492887;
// aapt resource value: 0x7f0c0018
public const int dim_foreground_disabled_material_light = 2131492888;
// aapt resource value: 0x7f0c0019
public const int dim_foreground_material_dark = 2131492889;
// aapt resource value: 0x7f0c001a
public const int dim_foreground_material_light = 2131492890;
// aapt resource value: 0x7f0c001b
public const int foreground_material_dark = 2131492891;
// aapt resource value: 0x7f0c001c
public const int foreground_material_light = 2131492892;
// aapt resource value: 0x7f0c001d
public const int highlighted_text_material_dark = 2131492893;
// aapt resource value: 0x7f0c001e
public const int highlighted_text_material_light = 2131492894;
// aapt resource value: 0x7f0c001f
public const int material_blue_grey_800 = 2131492895;
// aapt resource value: 0x7f0c0020
public const int material_blue_grey_900 = 2131492896;
// aapt resource value: 0x7f0c0021
public const int material_blue_grey_950 = 2131492897;
// aapt resource value: 0x7f0c0022
public const int material_deep_teal_200 = 2131492898;
// aapt resource value: 0x7f0c0023
public const int material_deep_teal_500 = 2131492899;
// aapt resource value: 0x7f0c0024
public const int material_grey_100 = 2131492900;
// aapt resource value: 0x7f0c0025
public const int material_grey_300 = 2131492901;
// aapt resource value: 0x7f0c0026
public const int material_grey_50 = 2131492902;
// aapt resource value: 0x7f0c0027
public const int material_grey_600 = 2131492903;
// aapt resource value: 0x7f0c0028
public const int material_grey_800 = 2131492904;
// aapt resource value: 0x7f0c0029
public const int material_grey_850 = 2131492905;
// aapt resource value: 0x7f0c002a
public const int material_grey_900 = 2131492906;
// aapt resource value: 0x7f0c0004
public const int notification_action_color_filter = 2131492868;
// aapt resource value: 0x7f0c002b
public const int notification_icon_bg_color = 2131492907;
// aapt resource value: 0x7f0c002c
public const int notification_material_background_media_default_color = 2131492908;
// aapt resource value: 0x7f0c002d
public const int primary_dark_material_dark = 2131492909;
// aapt resource value: 0x7f0c002e
public const int primary_dark_material_light = 2131492910;
// aapt resource value: 0x7f0c002f
public const int primary_material_dark = 2131492911;
// aapt resource value: 0x7f0c0030
public const int primary_material_light = 2131492912;
// aapt resource value: 0x7f0c0031
public const int primary_text_default_material_dark = 2131492913;
// aapt resource value: 0x7f0c0032
public const int primary_text_default_material_light = 2131492914;
// aapt resource value: 0x7f0c0033
public const int primary_text_disabled_material_dark = 2131492915;
// aapt resource value: 0x7f0c0034
public const int primary_text_disabled_material_light = 2131492916;
// aapt resource value: 0x7f0c0035
public const int ripple_material_dark = 2131492917;
// aapt resource value: 0x7f0c0036
public const int ripple_material_light = 2131492918;
// aapt resource value: 0x7f0c0037
public const int secondary_text_default_material_dark = 2131492919;
// aapt resource value: 0x7f0c0038
public const int secondary_text_default_material_light = 2131492920;
// aapt resource value: 0x7f0c0039
public const int secondary_text_disabled_material_dark = 2131492921;
// aapt resource value: 0x7f0c003a
public const int secondary_text_disabled_material_light = 2131492922;
// aapt resource value: 0x7f0c003b
public const int switch_thumb_disabled_material_dark = 2131492923;
// aapt resource value: 0x7f0c003c
public const int switch_thumb_disabled_material_light = 2131492924;
// aapt resource value: 0x7f0c0061
public const int switch_thumb_material_dark = 2131492961;
// aapt resource value: 0x7f0c0062
public const int switch_thumb_material_light = 2131492962;
// aapt resource value: 0x7f0c003d
public const int switch_thumb_normal_material_dark = 2131492925;
// aapt resource value: 0x7f0c003e
public const int switch_thumb_normal_material_light = 2131492926;
static Color()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Color()
{
}
}
public partial class Dimension
{
// aapt resource value: 0x7f070018
public const int abc_action_bar_content_inset_material = 2131165208;
// aapt resource value: 0x7f070019
public const int abc_action_bar_content_inset_with_nav = 2131165209;
// aapt resource value: 0x7f07000d
public const int abc_action_bar_default_height_material = 2131165197;
// aapt resource value: 0x7f07001a
public const int abc_action_bar_default_padding_end_material = 2131165210;
// aapt resource value: 0x7f07001b
public const int abc_action_bar_default_padding_start_material = 2131165211;
// aapt resource value: 0x7f070021
public const int abc_action_bar_elevation_material = 2131165217;
// aapt resource value: 0x7f070022
public const int abc_action_bar_icon_vertical_padding_material = 2131165218;
// aapt resource value: 0x7f070023
public const int abc_action_bar_overflow_padding_end_material = 2131165219;
// aapt resource value: 0x7f070024
public const int abc_action_bar_overflow_padding_start_material = 2131165220;
// aapt resource value: 0x7f07000e
public const int abc_action_bar_progress_bar_size = 2131165198;
// aapt resource value: 0x7f070025
public const int abc_action_bar_stacked_max_height = 2131165221;
// aapt resource value: 0x7f070026
public const int abc_action_bar_stacked_tab_max_width = 2131165222;
// aapt resource value: 0x7f070027
public const int abc_action_bar_subtitle_bottom_margin_material = 2131165223;
// aapt resource value: 0x7f070028
public const int abc_action_bar_subtitle_top_margin_material = 2131165224;
// aapt resource value: 0x7f070029
public const int abc_action_button_min_height_material = 2131165225;
// aapt resource value: 0x7f07002a
public const int abc_action_button_min_width_material = 2131165226;
// aapt resource value: 0x7f07002b
public const int abc_action_button_min_width_overflow_material = 2131165227;
// aapt resource value: 0x7f07000c
public const int abc_alert_dialog_button_bar_height = 2131165196;
// aapt resource value: 0x7f07002c
public const int abc_button_inset_horizontal_material = 2131165228;
// aapt resource value: 0x7f07002d
public const int abc_button_inset_vertical_material = 2131165229;
// aapt resource value: 0x7f07002e
public const int abc_button_padding_horizontal_material = 2131165230;
// aapt resource value: 0x7f07002f
public const int abc_button_padding_vertical_material = 2131165231;
// aapt resource value: 0x7f070030
public const int abc_cascading_menus_min_smallest_width = 2131165232;
// aapt resource value: 0x7f070011
public const int abc_config_prefDialogWidth = 2131165201;
// aapt resource value: 0x7f070031
public const int abc_control_corner_material = 2131165233;
// aapt resource value: 0x7f070032
public const int abc_control_inset_material = 2131165234;
// aapt resource value: 0x7f070033
public const int abc_control_padding_material = 2131165235;
// aapt resource value: 0x7f070012
public const int abc_dialog_fixed_height_major = 2131165202;
// aapt resource value: 0x7f070013
public const int abc_dialog_fixed_height_minor = 2131165203;
// aapt resource value: 0x7f070014
public const int abc_dialog_fixed_width_major = 2131165204;
// aapt resource value: 0x7f070015
public const int abc_dialog_fixed_width_minor = 2131165205;
// aapt resource value: 0x7f070034
public const int abc_dialog_list_padding_bottom_no_buttons = 2131165236;
// aapt resource value: 0x7f070035
public const int abc_dialog_list_padding_top_no_title = 2131165237;
// aapt resource value: 0x7f070016
public const int abc_dialog_min_width_major = 2131165206;
// aapt resource value: 0x7f070017
public const int abc_dialog_min_width_minor = 2131165207;
// aapt resource value: 0x7f070036
public const int abc_dialog_padding_material = 2131165238;
// aapt resource value: 0x7f070037
public const int abc_dialog_padding_top_material = 2131165239;
// aapt resource value: 0x7f070038
public const int abc_dialog_title_divider_material = 2131165240;
// aapt resource value: 0x7f070039
public const int abc_disabled_alpha_material_dark = 2131165241;
// aapt resource value: 0x7f07003a
public const int abc_disabled_alpha_material_light = 2131165242;
// aapt resource value: 0x7f07003b
public const int abc_dropdownitem_icon_width = 2131165243;
// aapt resource value: 0x7f07003c
public const int abc_dropdownitem_text_padding_left = 2131165244;
// aapt resource value: 0x7f07003d
public const int abc_dropdownitem_text_padding_right = 2131165245;
// aapt resource value: 0x7f07003e
public const int abc_edit_text_inset_bottom_material = 2131165246;
// aapt resource value: 0x7f07003f
public const int abc_edit_text_inset_horizontal_material = 2131165247;
// aapt resource value: 0x7f070040
public const int abc_edit_text_inset_top_material = 2131165248;
// aapt resource value: 0x7f070041
public const int abc_floating_window_z = 2131165249;
// aapt resource value: 0x7f070042
public const int abc_list_item_padding_horizontal_material = 2131165250;
// aapt resource value: 0x7f070043
public const int abc_panel_menu_list_width = 2131165251;
// aapt resource value: 0x7f070044
public const int abc_progress_bar_height_material = 2131165252;
// aapt resource value: 0x7f070045
public const int abc_search_view_preferred_height = 2131165253;
// aapt resource value: 0x7f070046
public const int abc_search_view_preferred_width = 2131165254;
// aapt resource value: 0x7f070047
public const int abc_seekbar_track_background_height_material = 2131165255;
// aapt resource value: 0x7f070048
public const int abc_seekbar_track_progress_height_material = 2131165256;
// aapt resource value: 0x7f070049
public const int abc_select_dialog_padding_start_material = 2131165257;
// aapt resource value: 0x7f07001d
public const int abc_switch_padding = 2131165213;
// aapt resource value: 0x7f07004a
public const int abc_text_size_body_1_material = 2131165258;
// aapt resource value: 0x7f07004b
public const int abc_text_size_body_2_material = 2131165259;
// aapt resource value: 0x7f07004c
public const int abc_text_size_button_material = 2131165260;
// aapt resource value: 0x7f07004d
public const int abc_text_size_caption_material = 2131165261;
// aapt resource value: 0x7f07004e
public const int abc_text_size_display_1_material = 2131165262;
// aapt resource value: 0x7f07004f
public const int abc_text_size_display_2_material = 2131165263;
// aapt resource value: 0x7f070050
public const int abc_text_size_display_3_material = 2131165264;
// aapt resource value: 0x7f070051
public const int abc_text_size_display_4_material = 2131165265;
// aapt resource value: 0x7f070052
public const int abc_text_size_headline_material = 2131165266;
// aapt resource value: 0x7f070053
public const int abc_text_size_large_material = 2131165267;
// aapt resource value: 0x7f070054
public const int abc_text_size_medium_material = 2131165268;
// aapt resource value: 0x7f070055
public const int abc_text_size_menu_header_material = 2131165269;
// aapt resource value: 0x7f070056
public const int abc_text_size_menu_material = 2131165270;
// aapt resource value: 0x7f070057
public const int abc_text_size_small_material = 2131165271;
// aapt resource value: 0x7f070058
public const int abc_text_size_subhead_material = 2131165272;
// aapt resource value: 0x7f07000f
public const int abc_text_size_subtitle_material_toolbar = 2131165199;
// aapt resource value: 0x7f070059
public const int abc_text_size_title_material = 2131165273;
// aapt resource value: 0x7f070010
public const int abc_text_size_title_material_toolbar = 2131165200;
// aapt resource value: 0x7f070009
public const int cardview_compat_inset_shadow = 2131165193;
// aapt resource value: 0x7f07000a
public const int cardview_default_elevation = 2131165194;
// aapt resource value: 0x7f07000b
public const int cardview_default_radius = 2131165195;
// aapt resource value: 0x7f070076
public const int design_appbar_elevation = 2131165302;
// aapt resource value: 0x7f070077
public const int design_bottom_navigation_active_item_max_width = 2131165303;
// aapt resource value: 0x7f070078
public const int design_bottom_navigation_active_text_size = 2131165304;
// aapt resource value: 0x7f070079
public const int design_bottom_navigation_elevation = 2131165305;
// aapt resource value: 0x7f07007a
public const int design_bottom_navigation_height = 2131165306;
// aapt resource value: 0x7f07007b
public const int design_bottom_navigation_item_max_width = 2131165307;
// aapt resource value: 0x7f07007c
public const int design_bottom_navigation_item_min_width = 2131165308;
// aapt resource value: 0x7f07007d
public const int design_bottom_navigation_margin = 2131165309;
// aapt resource value: 0x7f07007e
public const int design_bottom_navigation_shadow_height = 2131165310;
// aapt resource value: 0x7f07007f
public const int design_bottom_navigation_text_size = 2131165311;
// aapt resource value: 0x7f070080
public const int design_bottom_sheet_modal_elevation = 2131165312;
// aapt resource value: 0x7f070081
public const int design_bottom_sheet_peek_height_min = 2131165313;
// aapt resource value: 0x7f070082
public const int design_fab_border_width = 2131165314;
// aapt resource value: 0x7f070083
public const int design_fab_elevation = 2131165315;
// aapt resource value: 0x7f070084
public const int design_fab_image_size = 2131165316;
// aapt resource value: 0x7f070085
public const int design_fab_size_mini = 2131165317;
// aapt resource value: 0x7f070086
public const int design_fab_size_normal = 2131165318;
// aapt resource value: 0x7f070087
public const int design_fab_translation_z_pressed = 2131165319;
// aapt resource value: 0x7f070088
public const int design_navigation_elevation = 2131165320;
// aapt resource value: 0x7f070089
public const int design_navigation_icon_padding = 2131165321;
// aapt resource value: 0x7f07008a
public const int design_navigation_icon_size = 2131165322;
// aapt resource value: 0x7f07006e
public const int design_navigation_max_width = 2131165294;
// aapt resource value: 0x7f07008b
public const int design_navigation_padding_bottom = 2131165323;
// aapt resource value: 0x7f07008c
public const int design_navigation_separator_vertical_padding = 2131165324;
// aapt resource value: 0x7f07006f
public const int design_snackbar_action_inline_max_width = 2131165295;
// aapt resource value: 0x7f070070
public const int design_snackbar_background_corner_radius = 2131165296;
// aapt resource value: 0x7f07008d
public const int design_snackbar_elevation = 2131165325;
// aapt resource value: 0x7f070071
public const int design_snackbar_extra_spacing_horizontal = 2131165297;
// aapt resource value: 0x7f070072
public const int design_snackbar_max_width = 2131165298;
// aapt resource value: 0x7f070073
public const int design_snackbar_min_width = 2131165299;
// aapt resource value: 0x7f07008e
public const int design_snackbar_padding_horizontal = 2131165326;
// aapt resource value: 0x7f07008f
public const int design_snackbar_padding_vertical = 2131165327;
// aapt resource value: 0x7f070074
public const int design_snackbar_padding_vertical_2lines = 2131165300;
// aapt resource value: 0x7f070090
public const int design_snackbar_text_size = 2131165328;
// aapt resource value: 0x7f070091
public const int design_tab_max_width = 2131165329;
// aapt resource value: 0x7f070075
public const int design_tab_scrollable_min_width = 2131165301;
// aapt resource value: 0x7f070092
public const int design_tab_text_size = 2131165330;
// aapt resource value: 0x7f070093
public const int design_tab_text_size_2line = 2131165331;
// aapt resource value: 0x7f07005a
public const int disabled_alpha_material_dark = 2131165274;
// aapt resource value: 0x7f07005b
public const int disabled_alpha_material_light = 2131165275;
// aapt resource value: 0x7f07005c
public const int highlight_alpha_material_colored = 2131165276;
// aapt resource value: 0x7f07005d
public const int highlight_alpha_material_dark = 2131165277;
// aapt resource value: 0x7f07005e
public const int highlight_alpha_material_light = 2131165278;
// aapt resource value: 0x7f07005f
public const int hint_alpha_material_dark = 2131165279;
// aapt resource value: 0x7f070060
public const int hint_alpha_material_light = 2131165280;
// aapt resource value: 0x7f070061
public const int hint_pressed_alpha_material_dark = 2131165281;
// aapt resource value: 0x7f070062
public const int hint_pressed_alpha_material_light = 2131165282;
// aapt resource value: 0x7f070000
public const int item_touch_helper_max_drag_scroll_per_frame = 2131165184;
// aapt resource value: 0x7f070001
public const int item_touch_helper_swipe_escape_max_velocity = 2131165185;
// aapt resource value: 0x7f070002
public const int item_touch_helper_swipe_escape_velocity = 2131165186;
// aapt resource value: 0x7f070003
public const int mr_controller_volume_group_list_item_height = 2131165187;
// aapt resource value: 0x7f070004
public const int mr_controller_volume_group_list_item_icon_size = 2131165188;
// aapt resource value: 0x7f070005
public const int mr_controller_volume_group_list_max_height = 2131165189;
// aapt resource value: 0x7f070008
public const int mr_controller_volume_group_list_padding_top = 2131165192;
// aapt resource value: 0x7f070006
public const int mr_dialog_fixed_width_major = 2131165190;
// aapt resource value: 0x7f070007
public const int mr_dialog_fixed_width_minor = 2131165191;
// aapt resource value: 0x7f070063
public const int notification_action_icon_size = 2131165283;
// aapt resource value: 0x7f070064
public const int notification_action_text_size = 2131165284;
// aapt resource value: 0x7f070065
public const int notification_big_circle_margin = 2131165285;
// aapt resource value: 0x7f07001e
public const int notification_content_margin_start = 2131165214;
// aapt resource value: 0x7f070066
public const int notification_large_icon_height = 2131165286;
// aapt resource value: 0x7f070067
public const int notification_large_icon_width = 2131165287;
// aapt resource value: 0x7f07001f
public const int notification_main_column_padding_top = 2131165215;
// aapt resource value: 0x7f070020
public const int notification_media_narrow_margin = 2131165216;
// aapt resource value: 0x7f070068
public const int notification_right_icon_size = 2131165288;
// aapt resource value: 0x7f07001c
public const int notification_right_side_padding_top = 2131165212;
// aapt resource value: 0x7f070069
public const int notification_small_icon_background_padding = 2131165289;
// aapt resource value: 0x7f07006a
public const int notification_small_icon_size_as_large = 2131165290;
// aapt resource value: 0x7f07006b
public const int notification_subtext_size = 2131165291;
// aapt resource value: 0x7f07006c
public const int notification_top_pad = 2131165292;
// aapt resource value: 0x7f07006d
public const int notification_top_pad_large_text = 2131165293;
static Dimension()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Dimension()
{
}
}
public partial class Drawable
{
// aapt resource value: 0x7f020000
public const int abc_ab_share_pack_mtrl_alpha = 2130837504;
// aapt resource value: 0x7f020001
public const int abc_action_bar_item_background_material = 2130837505;
// aapt resource value: 0x7f020002
public const int abc_btn_borderless_material = 2130837506;
// aapt resource value: 0x7f020003
public const int abc_btn_check_material = 2130837507;
// aapt resource value: 0x7f020004
public const int abc_btn_check_to_on_mtrl_000 = 2130837508;
// aapt resource value: 0x7f020005
public const int abc_btn_check_to_on_mtrl_015 = 2130837509;
// aapt resource value: 0x7f020006
public const int abc_btn_colored_material = 2130837510;
// aapt resource value: 0x7f020007
public const int abc_btn_default_mtrl_shape = 2130837511;
// aapt resource value: 0x7f020008
public const int abc_btn_radio_material = 2130837512;
// aapt resource value: 0x7f020009
public const int abc_btn_radio_to_on_mtrl_000 = 2130837513;
// aapt resource value: 0x7f02000a
public const int abc_btn_radio_to_on_mtrl_015 = 2130837514;
// aapt resource value: 0x7f02000b
public const int abc_btn_switch_to_on_mtrl_00001 = 2130837515;
// aapt resource value: 0x7f02000c
public const int abc_btn_switch_to_on_mtrl_00012 = 2130837516;
// aapt resource value: 0x7f02000d
public const int abc_cab_background_internal_bg = 2130837517;
// aapt resource value: 0x7f02000e
public const int abc_cab_background_top_material = 2130837518;
// aapt resource value: 0x7f02000f
public const int abc_cab_background_top_mtrl_alpha = 2130837519;
// aapt resource value: 0x7f020010
public const int abc_control_background_material = 2130837520;
// aapt resource value: 0x7f020011
public const int abc_dialog_material_background = 2130837521;
// aapt resource value: 0x7f020012
public const int abc_edit_text_material = 2130837522;
// aapt resource value: 0x7f020013
public const int abc_ic_ab_back_material = 2130837523;
// aapt resource value: 0x7f020014
public const int abc_ic_arrow_drop_right_black_24dp = 2130837524;
// aapt resource value: 0x7f020015
public const int abc_ic_clear_material = 2130837525;
// aapt resource value: 0x7f020016
public const int abc_ic_commit_search_api_mtrl_alpha = 2130837526;
// aapt resource value: 0x7f020017
public const int abc_ic_go_search_api_material = 2130837527;
// aapt resource value: 0x7f020018
public const int abc_ic_menu_copy_mtrl_am_alpha = 2130837528;
// aapt resource value: 0x7f020019
public const int abc_ic_menu_cut_mtrl_alpha = 2130837529;
// aapt resource value: 0x7f02001a
public const int abc_ic_menu_overflow_material = 2130837530;
// aapt resource value: 0x7f02001b
public const int abc_ic_menu_paste_mtrl_am_alpha = 2130837531;
// aapt resource value: 0x7f02001c
public const int abc_ic_menu_selectall_mtrl_alpha = 2130837532;
// aapt resource value: 0x7f02001d
public const int abc_ic_menu_share_mtrl_alpha = 2130837533;
// aapt resource value: 0x7f02001e
public const int abc_ic_search_api_material = 2130837534;
// aapt resource value: 0x7f02001f
public const int abc_ic_star_black_16dp = 2130837535;
// aapt resource value: 0x7f020020
public const int abc_ic_star_black_36dp = 2130837536;
// aapt resource value: 0x7f020021
public const int abc_ic_star_black_48dp = 2130837537;
// aapt resource value: 0x7f020022
public const int abc_ic_star_half_black_16dp = 2130837538;
// aapt resource value: 0x7f020023
public const int abc_ic_star_half_black_36dp = 2130837539;
// aapt resource value: 0x7f020024
public const int abc_ic_star_half_black_48dp = 2130837540;
// aapt resource value: 0x7f020025
public const int abc_ic_voice_search_api_material = 2130837541;
// aapt resource value: 0x7f020026
public const int abc_item_background_holo_dark = 2130837542;
// aapt resource value: 0x7f020027
public const int abc_item_background_holo_light = 2130837543;
// aapt resource value: 0x7f020028
public const int abc_list_divider_mtrl_alpha = 2130837544;
// aapt resource value: 0x7f020029
public const int abc_list_focused_holo = 2130837545;
// aapt resource value: 0x7f02002a
public const int abc_list_longpressed_holo = 2130837546;
// aapt resource value: 0x7f02002b
public const int abc_list_pressed_holo_dark = 2130837547;
// aapt resource value: 0x7f02002c
public const int abc_list_pressed_holo_light = 2130837548;
// aapt resource value: 0x7f02002d
public const int abc_list_selector_background_transition_holo_dark = 2130837549;
// aapt resource value: 0x7f02002e
public const int abc_list_selector_background_transition_holo_light = 2130837550;
// aapt resource value: 0x7f02002f
public const int abc_list_selector_disabled_holo_dark = 2130837551;
// aapt resource value: 0x7f020030
public const int abc_list_selector_disabled_holo_light = 2130837552;
// aapt resource value: 0x7f020031
public const int abc_list_selector_holo_dark = 2130837553;
// aapt resource value: 0x7f020032
public const int abc_list_selector_holo_light = 2130837554;
// aapt resource value: 0x7f020033
public const int abc_menu_hardkey_panel_mtrl_mult = 2130837555;
// aapt resource value: 0x7f020034
public const int abc_popup_background_mtrl_mult = 2130837556;
// aapt resource value: 0x7f020035
public const int abc_ratingbar_indicator_material = 2130837557;
// aapt resource value: 0x7f020036
public const int abc_ratingbar_material = 2130837558;
// aapt resource value: 0x7f020037
public const int abc_ratingbar_small_material = 2130837559;
// aapt resource value: 0x7f020038
public const int abc_scrubber_control_off_mtrl_alpha = 2130837560;
// aapt resource value: 0x7f020039
public const int abc_scrubber_control_to_pressed_mtrl_000 = 2130837561;
// aapt resource value: 0x7f02003a
public const int abc_scrubber_control_to_pressed_mtrl_005 = 2130837562;
// aapt resource value: 0x7f02003b
public const int abc_scrubber_primary_mtrl_alpha = 2130837563;
// aapt resource value: 0x7f02003c
public const int abc_scrubber_track_mtrl_alpha = 2130837564;
// aapt resource value: 0x7f02003d
public const int abc_seekbar_thumb_material = 2130837565;
// aapt resource value: 0x7f02003e
public const int abc_seekbar_tick_mark_material = 2130837566;
// aapt resource value: 0x7f02003f
public const int abc_seekbar_track_material = 2130837567;
// aapt resource value: 0x7f020040
public const int abc_spinner_mtrl_am_alpha = 2130837568;
// aapt resource value: 0x7f020041
public const int abc_spinner_textfield_background_material = 2130837569;
// aapt resource value: 0x7f020042
public const int abc_switch_thumb_material = 2130837570;
// aapt resource value: 0x7f020043
public const int abc_switch_track_mtrl_alpha = 2130837571;
// aapt resource value: 0x7f020044
public const int abc_tab_indicator_material = 2130837572;
// aapt resource value: 0x7f020045
public const int abc_tab_indicator_mtrl_alpha = 2130837573;
// aapt resource value: 0x7f020046
public const int abc_text_cursor_material = 2130837574;
// aapt resource value: 0x7f020047
public const int abc_text_select_handle_left_mtrl_dark = 2130837575;
// aapt resource value: 0x7f020048
public const int abc_text_select_handle_left_mtrl_light = 2130837576;
// aapt resource value: 0x7f020049
public const int abc_text_select_handle_middle_mtrl_dark = 2130837577;
// aapt resource value: 0x7f02004a
public const int abc_text_select_handle_middle_mtrl_light = 2130837578;
// aapt resource value: 0x7f02004b
public const int abc_text_select_handle_right_mtrl_dark = 2130837579;
// aapt resource value: 0x7f02004c
public const int abc_text_select_handle_right_mtrl_light = 2130837580;
// aapt resource value: 0x7f02004d
public const int abc_textfield_activated_mtrl_alpha = 2130837581;
// aapt resource value: 0x7f02004e
public const int abc_textfield_default_mtrl_alpha = 2130837582;
// aapt resource value: 0x7f02004f
public const int abc_textfield_search_activated_mtrl_alpha = 2130837583;
// aapt resource value: 0x7f020050
public const int abc_textfield_search_default_mtrl_alpha = 2130837584;
// aapt resource value: 0x7f020051
public const int abc_textfield_search_material = 2130837585;
// aapt resource value: 0x7f020052
public const int abc_vector_test = 2130837586;
// aapt resource value: 0x7f020053
public const int avd_hide_password = 2130837587;
// aapt resource value: 0x7f02010e
public const int avd_hide_password_1 = 2130837774;
// aapt resource value: 0x7f02010f
public const int avd_hide_password_2 = 2130837775;
// aapt resource value: 0x7f020110
public const int avd_hide_password_3 = 2130837776;
// aapt resource value: 0x7f020054
public const int avd_show_password = 2130837588;
// aapt resource value: 0x7f020111
public const int avd_show_password_1 = 2130837777;
// aapt resource value: 0x7f020112
public const int avd_show_password_2 = 2130837778;
// aapt resource value: 0x7f020113
public const int avd_show_password_3 = 2130837779;
// aapt resource value: 0x7f020055
public const int design_bottom_navigation_item_background = 2130837589;
// aapt resource value: 0x7f020056
public const int design_fab_background = 2130837590;
// aapt resource value: 0x7f020057
public const int design_ic_visibility = 2130837591;
// aapt resource value: 0x7f020058
public const int design_ic_visibility_off = 2130837592;
// aapt resource value: 0x7f020059
public const int design_password_eye = 2130837593;
// aapt resource value: 0x7f02005a
public const int design_snackbar_background = 2130837594;
// aapt resource value: 0x7f02005b
public const int ic_audiotrack_dark = 2130837595;
// aapt resource value: 0x7f02005c
public const int ic_audiotrack_light = 2130837596;
// aapt resource value: 0x7f02005d
public const int ic_dialog_close_dark = 2130837597;
// aapt resource value: 0x7f02005e
public const int ic_dialog_close_light = 2130837598;
// aapt resource value: 0x7f02005f
public const int ic_group_collapse_00 = 2130837599;
// aapt resource value: 0x7f020060
public const int ic_group_collapse_01 = 2130837600;
// aapt resource value: 0x7f020061
public const int ic_group_collapse_02 = 2130837601;
// aapt resource value: 0x7f020062
public const int ic_group_collapse_03 = 2130837602;
// aapt resource value: 0x7f020063
public const int ic_group_collapse_04 = 2130837603;
// aapt resource value: 0x7f020064
public const int ic_group_collapse_05 = 2130837604;
// aapt resource value: 0x7f020065
public const int ic_group_collapse_06 = 2130837605;
// aapt resource value: 0x7f020066
public const int ic_group_collapse_07 = 2130837606;
// aapt resource value: 0x7f020067
public const int ic_group_collapse_08 = 2130837607;
// aapt resource value: 0x7f020068
public const int ic_group_collapse_09 = 2130837608;
// aapt resource value: 0x7f020069
public const int ic_group_collapse_10 = 2130837609;
// aapt resource value: 0x7f02006a
public const int ic_group_collapse_11 = 2130837610;
// aapt resource value: 0x7f02006b
public const int ic_group_collapse_12 = 2130837611;
// aapt resource value: 0x7f02006c
public const int ic_group_collapse_13 = 2130837612;
// aapt resource value: 0x7f02006d
public const int ic_group_collapse_14 = 2130837613;
// aapt resource value: 0x7f02006e
public const int ic_group_collapse_15 = 2130837614;
// aapt resource value: 0x7f02006f
public const int ic_group_expand_00 = 2130837615;
// aapt resource value: 0x7f020070
public const int ic_group_expand_01 = 2130837616;
// aapt resource value: 0x7f020071
public const int ic_group_expand_02 = 2130837617;
// aapt resource value: 0x7f020072
public const int ic_group_expand_03 = 2130837618;
// aapt resource value: 0x7f020073
public const int ic_group_expand_04 = 2130837619;
// aapt resource value: 0x7f020074
public const int ic_group_expand_05 = 2130837620;
// aapt resource value: 0x7f020075
public const int ic_group_expand_06 = 2130837621;
// aapt resource value: 0x7f020076
public const int ic_group_expand_07 = 2130837622;
// aapt resource value: 0x7f020077
public const int ic_group_expand_08 = 2130837623;
// aapt resource value: 0x7f020078
public const int ic_group_expand_09 = 2130837624;
// aapt resource value: 0x7f020079
public const int ic_group_expand_10 = 2130837625;
// aapt resource value: 0x7f02007a
public const int ic_group_expand_11 = 2130837626;
// aapt resource value: 0x7f02007b
public const int ic_group_expand_12 = 2130837627;
// aapt resource value: 0x7f02007c
public const int ic_group_expand_13 = 2130837628;
// aapt resource value: 0x7f02007d
public const int ic_group_expand_14 = 2130837629;
// aapt resource value: 0x7f02007e
public const int ic_group_expand_15 = 2130837630;
// aapt resource value: 0x7f02007f
public const int ic_media_pause_dark = 2130837631;
// aapt resource value: 0x7f020080
public const int ic_media_pause_light = 2130837632;
// aapt resource value: 0x7f020081
public const int ic_media_play_dark = 2130837633;
// aapt resource value: 0x7f020082
public const int ic_media_play_light = 2130837634;
// aapt resource value: 0x7f020083
public const int ic_media_stop_dark = 2130837635;
// aapt resource value: 0x7f020084
public const int ic_media_stop_light = 2130837636;
// aapt resource value: 0x7f020085
public const int ic_mr_button_connected_00_dark = 2130837637;
// aapt resource value: 0x7f020086
public const int ic_mr_button_connected_00_light = 2130837638;
// aapt resource value: 0x7f020087
public const int ic_mr_button_connected_01_dark = 2130837639;
// aapt resource value: 0x7f020088
public const int ic_mr_button_connected_01_light = 2130837640;
// aapt resource value: 0x7f020089
public const int ic_mr_button_connected_02_dark = 2130837641;
// aapt resource value: 0x7f02008a
public const int ic_mr_button_connected_02_light = 2130837642;
// aapt resource value: 0x7f02008b
public const int ic_mr_button_connected_03_dark = 2130837643;
// aapt resource value: 0x7f02008c
public const int ic_mr_button_connected_03_light = 2130837644;
// aapt resource value: 0x7f02008d
public const int ic_mr_button_connected_04_dark = 2130837645;
// aapt resource value: 0x7f02008e
public const int ic_mr_button_connected_04_light = 2130837646;
// aapt resource value: 0x7f02008f
public const int ic_mr_button_connected_05_dark = 2130837647;
// aapt resource value: 0x7f020090
public const int ic_mr_button_connected_05_light = 2130837648;
// aapt resource value: 0x7f020091
public const int ic_mr_button_connected_06_dark = 2130837649;
// aapt resource value: 0x7f020092
public const int ic_mr_button_connected_06_light = 2130837650;
// aapt resource value: 0x7f020093
public const int ic_mr_button_connected_07_dark = 2130837651;
// aapt resource value: 0x7f020094
public const int ic_mr_button_connected_07_light = 2130837652;
// aapt resource value: 0x7f020095
public const int ic_mr_button_connected_08_dark = 2130837653;
// aapt resource value: 0x7f020096
public const int ic_mr_button_connected_08_light = 2130837654;
// aapt resource value: 0x7f020097
public const int ic_mr_button_connected_09_dark = 2130837655;
// aapt resource value: 0x7f020098
public const int ic_mr_button_connected_09_light = 2130837656;
// aapt resource value: 0x7f020099
public const int ic_mr_button_connected_10_dark = 2130837657;
// aapt resource value: 0x7f02009a
public const int ic_mr_button_connected_10_light = 2130837658;
// aapt resource value: 0x7f02009b
public const int ic_mr_button_connected_11_dark = 2130837659;
// aapt resource value: 0x7f02009c
public const int ic_mr_button_connected_11_light = 2130837660;
// aapt resource value: 0x7f02009d
public const int ic_mr_button_connected_12_dark = 2130837661;
// aapt resource value: 0x7f02009e
public const int ic_mr_button_connected_12_light = 2130837662;
// aapt resource value: 0x7f02009f
public const int ic_mr_button_connected_13_dark = 2130837663;
// aapt resource value: 0x7f0200a0
public const int ic_mr_button_connected_13_light = 2130837664;
// aapt resource value: 0x7f0200a1
public const int ic_mr_button_connected_14_dark = 2130837665;
// aapt resource value: 0x7f0200a2
public const int ic_mr_button_connected_14_light = 2130837666;
// aapt resource value: 0x7f0200a3
public const int ic_mr_button_connected_15_dark = 2130837667;
// aapt resource value: 0x7f0200a4
public const int ic_mr_button_connected_15_light = 2130837668;
// aapt resource value: 0x7f0200a5
public const int ic_mr_button_connected_16_dark = 2130837669;
// aapt resource value: 0x7f0200a6
public const int ic_mr_button_connected_16_light = 2130837670;
// aapt resource value: 0x7f0200a7
public const int ic_mr_button_connected_17_dark = 2130837671;
// aapt resource value: 0x7f0200a8
public const int ic_mr_button_connected_17_light = 2130837672;
// aapt resource value: 0x7f0200a9
public const int ic_mr_button_connected_18_dark = 2130837673;
// aapt resource value: 0x7f0200aa
public const int ic_mr_button_connected_18_light = 2130837674;
// aapt resource value: 0x7f0200ab
public const int ic_mr_button_connected_19_dark = 2130837675;
// aapt resource value: 0x7f0200ac
public const int ic_mr_button_connected_19_light = 2130837676;
// aapt resource value: 0x7f0200ad
public const int ic_mr_button_connected_20_dark = 2130837677;
// aapt resource value: 0x7f0200ae
public const int ic_mr_button_connected_20_light = 2130837678;
// aapt resource value: 0x7f0200af
public const int ic_mr_button_connected_21_dark = 2130837679;
// aapt resource value: 0x7f0200b0
public const int ic_mr_button_connected_21_light = 2130837680;
// aapt resource value: 0x7f0200b1
public const int ic_mr_button_connected_22_dark = 2130837681;
// aapt resource value: 0x7f0200b2
public const int ic_mr_button_connected_22_light = 2130837682;
// aapt resource value: 0x7f0200b3
public const int ic_mr_button_connecting_00_dark = 2130837683;
// aapt resource value: 0x7f0200b4
public const int ic_mr_button_connecting_00_light = 2130837684;
// aapt resource value: 0x7f0200b5
public const int ic_mr_button_connecting_01_dark = 2130837685;
// aapt resource value: 0x7f0200b6
public const int ic_mr_button_connecting_01_light = 2130837686;
// aapt resource value: 0x7f0200b7
public const int ic_mr_button_connecting_02_dark = 2130837687;
// aapt resource value: 0x7f0200b8
public const int ic_mr_button_connecting_02_light = 2130837688;
// aapt resource value: 0x7f0200b9
public const int ic_mr_button_connecting_03_dark = 2130837689;
// aapt resource value: 0x7f0200ba
public const int ic_mr_button_connecting_03_light = 2130837690;
// aapt resource value: 0x7f0200bb
public const int ic_mr_button_connecting_04_dark = 2130837691;
// aapt resource value: 0x7f0200bc
public const int ic_mr_button_connecting_04_light = 2130837692;
// aapt resource value: 0x7f0200bd
public const int ic_mr_button_connecting_05_dark = 2130837693;
// aapt resource value: 0x7f0200be
public const int ic_mr_button_connecting_05_light = 2130837694;
// aapt resource value: 0x7f0200bf
public const int ic_mr_button_connecting_06_dark = 2130837695;
// aapt resource value: 0x7f0200c0
public const int ic_mr_button_connecting_06_light = 2130837696;
// aapt resource value: 0x7f0200c1
public const int ic_mr_button_connecting_07_dark = 2130837697;
// aapt resource value: 0x7f0200c2
public const int ic_mr_button_connecting_07_light = 2130837698;
// aapt resource value: 0x7f0200c3
public const int ic_mr_button_connecting_08_dark = 2130837699;
// aapt resource value: 0x7f0200c4
public const int ic_mr_button_connecting_08_light = 2130837700;
// aapt resource value: 0x7f0200c5
public const int ic_mr_button_connecting_09_dark = 2130837701;
// aapt resource value: 0x7f0200c6
public const int ic_mr_button_connecting_09_light = 2130837702;
// aapt resource value: 0x7f0200c7
public const int ic_mr_button_connecting_10_dark = 2130837703;
// aapt resource value: 0x7f0200c8
public const int ic_mr_button_connecting_10_light = 2130837704;
// aapt resource value: 0x7f0200c9
public const int ic_mr_button_connecting_11_dark = 2130837705;
// aapt resource value: 0x7f0200ca
public const int ic_mr_button_connecting_11_light = 2130837706;
// aapt resource value: 0x7f0200cb
public const int ic_mr_button_connecting_12_dark = 2130837707;
// aapt resource value: 0x7f0200cc
public const int ic_mr_button_connecting_12_light = 2130837708;
// aapt resource value: 0x7f0200cd
public const int ic_mr_button_connecting_13_dark = 2130837709;
// aapt resource value: 0x7f0200ce
public const int ic_mr_button_connecting_13_light = 2130837710;
// aapt resource value: 0x7f0200cf
public const int ic_mr_button_connecting_14_dark = 2130837711;
// aapt resource value: 0x7f0200d0
public const int ic_mr_button_connecting_14_light = 2130837712;
// aapt resource value: 0x7f0200d1
public const int ic_mr_button_connecting_15_dark = 2130837713;
// aapt resource value: 0x7f0200d2
public const int ic_mr_button_connecting_15_light = 2130837714;
// aapt resource value: 0x7f0200d3
public const int ic_mr_button_connecting_16_dark = 2130837715;
// aapt resource value: 0x7f0200d4
public const int ic_mr_button_connecting_16_light = 2130837716;
// aapt resource value: 0x7f0200d5
public const int ic_mr_button_connecting_17_dark = 2130837717;
// aapt resource value: 0x7f0200d6
public const int ic_mr_button_connecting_17_light = 2130837718;
// aapt resource value: 0x7f0200d7
public const int ic_mr_button_connecting_18_dark = 2130837719;
// aapt resource value: 0x7f0200d8
public const int ic_mr_button_connecting_18_light = 2130837720;
// aapt resource value: 0x7f0200d9
public const int ic_mr_button_connecting_19_dark = 2130837721;
// aapt resource value: 0x7f0200da
public const int ic_mr_button_connecting_19_light = 2130837722;
// aapt resource value: 0x7f0200db
public const int ic_mr_button_connecting_20_dark = 2130837723;
// aapt resource value: 0x7f0200dc
public const int ic_mr_button_connecting_20_light = 2130837724;
// aapt resource value: 0x7f0200dd
public const int ic_mr_button_connecting_21_dark = 2130837725;
// aapt resource value: 0x7f0200de
public const int ic_mr_button_connecting_21_light = 2130837726;
// aapt resource value: 0x7f0200df
public const int ic_mr_button_connecting_22_dark = 2130837727;
// aapt resource value: 0x7f0200e0
public const int ic_mr_button_connecting_22_light = 2130837728;
// aapt resource value: 0x7f0200e1
public const int ic_mr_button_disabled_dark = 2130837729;
// aapt resource value: 0x7f0200e2
public const int ic_mr_button_disabled_light = 2130837730;
// aapt resource value: 0x7f0200e3
public const int ic_mr_button_disconnected_dark = 2130837731;
// aapt resource value: 0x7f0200e4
public const int ic_mr_button_disconnected_light = 2130837732;
// aapt resource value: 0x7f0200e5
public const int ic_mr_button_grey = 2130837733;
// aapt resource value: 0x7f0200e6
public const int ic_vol_type_speaker_dark = 2130837734;
// aapt resource value: 0x7f0200e7
public const int ic_vol_type_speaker_group_dark = 2130837735;
// aapt resource value: 0x7f0200e8
public const int ic_vol_type_speaker_group_light = 2130837736;
// aapt resource value: 0x7f0200e9
public const int ic_vol_type_speaker_light = 2130837737;
// aapt resource value: 0x7f0200ea
public const int ic_vol_type_tv_dark = 2130837738;
// aapt resource value: 0x7f0200eb
public const int ic_vol_type_tv_light = 2130837739;
// aapt resource value: 0x7f0200ec
public const int icon = 2130837740;
// aapt resource value: 0x7f0200ed
public const int mr_button_connected_dark = 2130837741;
// aapt resource value: 0x7f0200ee
public const int mr_button_connected_light = 2130837742;
// aapt resource value: 0x7f0200ef
public const int mr_button_connecting_dark = 2130837743;
// aapt resource value: 0x7f0200f0
public const int mr_button_connecting_light = 2130837744;
// aapt resource value: 0x7f0200f1
public const int mr_button_dark = 2130837745;
// aapt resource value: 0x7f0200f2
public const int mr_button_light = 2130837746;
// aapt resource value: 0x7f0200f3
public const int mr_dialog_close_dark = 2130837747;
// aapt resource value: 0x7f0200f4
public const int mr_dialog_close_light = 2130837748;
// aapt resource value: 0x7f0200f5
public const int mr_dialog_material_background_dark = 2130837749;
// aapt resource value: 0x7f0200f6
public const int mr_dialog_material_background_light = 2130837750;
// aapt resource value: 0x7f0200f7
public const int mr_group_collapse = 2130837751;
// aapt resource value: 0x7f0200f8
public const int mr_group_expand = 2130837752;
// aapt resource value: 0x7f0200f9
public const int mr_media_pause_dark = 2130837753;
// aapt resource value: 0x7f0200fa
public const int mr_media_pause_light = 2130837754;
// aapt resource value: 0x7f0200fb
public const int mr_media_play_dark = 2130837755;
// aapt resource value: 0x7f0200fc
public const int mr_media_play_light = 2130837756;
// aapt resource value: 0x7f0200fd
public const int mr_media_stop_dark = 2130837757;
// aapt resource value: 0x7f0200fe
public const int mr_media_stop_light = 2130837758;
// aapt resource value: 0x7f0200ff
public const int mr_vol_type_audiotrack_dark = 2130837759;
// aapt resource value: 0x7f020100
public const int mr_vol_type_audiotrack_light = 2130837760;
// aapt resource value: 0x7f020101
public const int navigation_empty_icon = 2130837761;
// aapt resource value: 0x7f020102
public const int notification_action_background = 2130837762;
// aapt resource value: 0x7f020103
public const int notification_bg = 2130837763;
// aapt resource value: 0x7f020104
public const int notification_bg_low = 2130837764;
// aapt resource value: 0x7f020105
public const int notification_bg_low_normal = 2130837765;
// aapt resource value: 0x7f020106
public const int notification_bg_low_pressed = 2130837766;
// aapt resource value: 0x7f020107
public const int notification_bg_normal = 2130837767;
// aapt resource value: 0x7f020108
public const int notification_bg_normal_pressed = 2130837768;
// aapt resource value: 0x7f020109
public const int notification_icon_background = 2130837769;
// aapt resource value: 0x7f02010c
public const int notification_template_icon_bg = 2130837772;
// aapt resource value: 0x7f02010d
public const int notification_template_icon_low_bg = 2130837773;
// aapt resource value: 0x7f02010a
public const int notification_tile_bg = 2130837770;
// aapt resource value: 0x7f02010b
public const int notify_panel_notification_icon_bg = 2130837771;
static Drawable()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Drawable()
{
}
}
public partial class Id
{
// aapt resource value: 0x7f08009e
public const int action0 = 2131230878;
// aapt resource value: 0x7f080064
public const int action_bar = 2131230820;
// aapt resource value: 0x7f080001
public const int action_bar_activity_content = 2131230721;
// aapt resource value: 0x7f080063
public const int action_bar_container = 2131230819;
// aapt resource value: 0x7f08005f
public const int action_bar_root = 2131230815;
// aapt resource value: 0x7f080002
public const int action_bar_spinner = 2131230722;
// aapt resource value: 0x7f080042
public const int action_bar_subtitle = 2131230786;
// aapt resource value: 0x7f080041
public const int action_bar_title = 2131230785;
// aapt resource value: 0x7f08009b
public const int action_container = 2131230875;
// aapt resource value: 0x7f080065
public const int action_context_bar = 2131230821;
// aapt resource value: 0x7f0800a2
public const int action_divider = 2131230882;
// aapt resource value: 0x7f08009c
public const int action_image = 2131230876;
// aapt resource value: 0x7f080003
public const int action_menu_divider = 2131230723;
// aapt resource value: 0x7f080004
public const int action_menu_presenter = 2131230724;
// aapt resource value: 0x7f080061
public const int action_mode_bar = 2131230817;
// aapt resource value: 0x7f080060
public const int action_mode_bar_stub = 2131230816;
// aapt resource value: 0x7f080043
public const int action_mode_close_button = 2131230787;
// aapt resource value: 0x7f08009d
public const int action_text = 2131230877;
// aapt resource value: 0x7f0800ab
public const int actions = 2131230891;
// aapt resource value: 0x7f080044
public const int activity_chooser_view_content = 2131230788;
// aapt resource value: 0x7f08001e
public const int add = 2131230750;
// aapt resource value: 0x7f080058
public const int alertTitle = 2131230808;
// aapt resource value: 0x7f08003d
public const int all = 2131230781;
// aapt resource value: 0x7f080023
public const int always = 2131230755;
// aapt resource value: 0x7f08002f
public const int auto = 2131230767;
// aapt resource value: 0x7f080020
public const int beginning = 2131230752;
// aapt resource value: 0x7f080028
public const int bottom = 2131230760;
// aapt resource value: 0x7f08004b
public const int buttonPanel = 2131230795;
// aapt resource value: 0x7f08009f
public const int cancel_action = 2131230879;
// aapt resource value: 0x7f080030
public const int center = 2131230768;
// aapt resource value: 0x7f080031
public const int center_horizontal = 2131230769;
// aapt resource value: 0x7f080032
public const int center_vertical = 2131230770;
// aapt resource value: 0x7f08005b
public const int checkbox = 2131230811;
// aapt resource value: 0x7f0800a7
public const int chronometer = 2131230887;
// aapt resource value: 0x7f080039
public const int clip_horizontal = 2131230777;
// aapt resource value: 0x7f08003a
public const int clip_vertical = 2131230778;
// aapt resource value: 0x7f080024
public const int collapseActionView = 2131230756;
// aapt resource value: 0x7f080075
public const int container = 2131230837;
// aapt resource value: 0x7f08004e
public const int contentPanel = 2131230798;
// aapt resource value: 0x7f080076
public const int coordinator = 2131230838;
// aapt resource value: 0x7f080055
public const int custom = 2131230805;
// aapt resource value: 0x7f080054
public const int customPanel = 2131230804;
// aapt resource value: 0x7f080062
public const int decor_content_parent = 2131230818;
// aapt resource value: 0x7f080047
public const int default_activity_button = 2131230791;
// aapt resource value: 0x7f080078
public const int design_bottom_sheet = 2131230840;
// aapt resource value: 0x7f08007f
public const int design_menu_item_action_area = 2131230847;
// aapt resource value: 0x7f08007e
public const int design_menu_item_action_area_stub = 2131230846;
// aapt resource value: 0x7f08007d
public const int design_menu_item_text = 2131230845;
// aapt resource value: 0x7f08007c
public const int design_navigation_view = 2131230844;
// aapt resource value: 0x7f080012
public const int disableHome = 2131230738;
// aapt resource value: 0x7f080066
public const int edit_query = 2131230822;
// aapt resource value: 0x7f080021
public const int end = 2131230753;
// aapt resource value: 0x7f0800b1
public const int end_padder = 2131230897;
// aapt resource value: 0x7f08002a
public const int enterAlways = 2131230762;
// aapt resource value: 0x7f08002b
public const int enterAlwaysCollapsed = 2131230763;
// aapt resource value: 0x7f08002c
public const int exitUntilCollapsed = 2131230764;
// aapt resource value: 0x7f080045
public const int expand_activities_button = 2131230789;
// aapt resource value: 0x7f08005a
public const int expanded_menu = 2131230810;
// aapt resource value: 0x7f08003b
public const int fill = 2131230779;
// aapt resource value: 0x7f08003c
public const int fill_horizontal = 2131230780;
// aapt resource value: 0x7f080033
public const int fill_vertical = 2131230771;
// aapt resource value: 0x7f08003f
public const int @fixed = 2131230783;
// aapt resource value: 0x7f080005
public const int home = 2131230725;
// aapt resource value: 0x7f080013
public const int homeAsUp = 2131230739;
// aapt resource value: 0x7f080049
public const int icon = 2131230793;
// aapt resource value: 0x7f0800ac
public const int icon_group = 2131230892;
// aapt resource value: 0x7f080025
public const int ifRoom = 2131230757;
// aapt resource value: 0x7f080046
public const int image = 2131230790;
// aapt resource value: 0x7f0800a8
public const int info = 2131230888;
// aapt resource value: 0x7f080000
public const int item_touch_helper_previous_elevation = 2131230720;
// aapt resource value: 0x7f080074
public const int largeLabel = 2131230836;
// aapt resource value: 0x7f080034
public const int left = 2131230772;
// aapt resource value: 0x7f0800ad
public const int line1 = 2131230893;
// aapt resource value: 0x7f0800af
public const int line3 = 2131230895;
// aapt resource value: 0x7f08000f
public const int listMode = 2131230735;
// aapt resource value: 0x7f080048
public const int list_item = 2131230792;
// aapt resource value: 0x7f0800b3
public const int masked = 2131230899;
// aapt resource value: 0x7f0800a1
public const int media_actions = 2131230881;
// aapt resource value: 0x7f080022
public const int middle = 2131230754;
// aapt resource value: 0x7f08003e
public const int mini = 2131230782;
// aapt resource value: 0x7f08008d
public const int mr_art = 2131230861;
// aapt resource value: 0x7f080082
public const int mr_chooser_list = 2131230850;
// aapt resource value: 0x7f080085
public const int mr_chooser_route_desc = 2131230853;
// aapt resource value: 0x7f080083
public const int mr_chooser_route_icon = 2131230851;
// aapt resource value: 0x7f080084
public const int mr_chooser_route_name = 2131230852;
// aapt resource value: 0x7f080081
public const int mr_chooser_title = 2131230849;
// aapt resource value: 0x7f08008a
public const int mr_close = 2131230858;
// aapt resource value: 0x7f080090
public const int mr_control_divider = 2131230864;
// aapt resource value: 0x7f080096
public const int mr_control_playback_ctrl = 2131230870;
// aapt resource value: 0x7f080099
public const int mr_control_subtitle = 2131230873;
// aapt resource value: 0x7f080098
public const int mr_control_title = 2131230872;
// aapt resource value: 0x7f080097
public const int mr_control_title_container = 2131230871;
// aapt resource value: 0x7f08008b
public const int mr_custom_control = 2131230859;
// aapt resource value: 0x7f08008c
public const int mr_default_control = 2131230860;
// aapt resource value: 0x7f080087
public const int mr_dialog_area = 2131230855;
// aapt resource value: 0x7f080086
public const int mr_expandable_area = 2131230854;
// aapt resource value: 0x7f08009a
public const int mr_group_expand_collapse = 2131230874;
// aapt resource value: 0x7f08008e
public const int mr_media_main_control = 2131230862;
// aapt resource value: 0x7f080089
public const int mr_name = 2131230857;
// aapt resource value: 0x7f08008f
public const int mr_playback_control = 2131230863;
// aapt resource value: 0x7f080088
public const int mr_title_bar = 2131230856;
// aapt resource value: 0x7f080091
public const int mr_volume_control = 2131230865;
// aapt resource value: 0x7f080092
public const int mr_volume_group_list = 2131230866;
// aapt resource value: 0x7f080094
public const int mr_volume_item_icon = 2131230868;
// aapt resource value: 0x7f080095
public const int mr_volume_slider = 2131230869;
// aapt resource value: 0x7f080019
public const int multiply = 2131230745;
// aapt resource value: 0x7f08007b
public const int navigation_header_container = 2131230843;
// aapt resource value: 0x7f080026
public const int never = 2131230758;
// aapt resource value: 0x7f080014
public const int none = 2131230740;
// aapt resource value: 0x7f080010
public const int normal = 2131230736;
// aapt resource value: 0x7f0800aa
public const int notification_background = 2131230890;
// aapt resource value: 0x7f0800a4
public const int notification_main_column = 2131230884;
// aapt resource value: 0x7f0800a3
public const int notification_main_column_container = 2131230883;
// aapt resource value: 0x7f080037
public const int parallax = 2131230775;
// aapt resource value: 0x7f08004d
public const int parentPanel = 2131230797;
// aapt resource value: 0x7f080038
public const int pin = 2131230776;
// aapt resource value: 0x7f080006
public const int progress_circular = 2131230726;
// aapt resource value: 0x7f080007
public const int progress_horizontal = 2131230727;
// aapt resource value: 0x7f08005d
public const int radio = 2131230813;
// aapt resource value: 0x7f080035
public const int right = 2131230773;
// aapt resource value: 0x7f0800a9
public const int right_icon = 2131230889;
// aapt resource value: 0x7f0800a5
public const int right_side = 2131230885;
// aapt resource value: 0x7f08001a
public const int screen = 2131230746;
// aapt resource value: 0x7f08002d
public const int scroll = 2131230765;
// aapt resource value: 0x7f080053
public const int scrollIndicatorDown = 2131230803;
// aapt resource value: 0x7f08004f
public const int scrollIndicatorUp = 2131230799;
// aapt resource value: 0x7f080050
public const int scrollView = 2131230800;
// aapt resource value: 0x7f080040
public const int scrollable = 2131230784;
// aapt resource value: 0x7f080068
public const int search_badge = 2131230824;
// aapt resource value: 0x7f080067
public const int search_bar = 2131230823;
// aapt resource value: 0x7f080069
public const int search_button = 2131230825;
// aapt resource value: 0x7f08006e
public const int search_close_btn = 2131230830;
// aapt resource value: 0x7f08006a
public const int search_edit_frame = 2131230826;
// aapt resource value: 0x7f080070
public const int search_go_btn = 2131230832;
// aapt resource value: 0x7f08006b
public const int search_mag_icon = 2131230827;
// aapt resource value: 0x7f08006c
public const int search_plate = 2131230828;
// aapt resource value: 0x7f08006d
public const int search_src_text = 2131230829;
// aapt resource value: 0x7f080071
public const int search_voice_btn = 2131230833;
// aapt resource value: 0x7f080072
public const int select_dialog_listview = 2131230834;
// aapt resource value: 0x7f08005c
public const int shortcut = 2131230812;
// aapt resource value: 0x7f080015
public const int showCustom = 2131230741;
// aapt resource value: 0x7f080016
public const int showHome = 2131230742;
// aapt resource value: 0x7f080017
public const int showTitle = 2131230743;
// aapt resource value: 0x7f080073
public const int smallLabel = 2131230835;
// aapt resource value: 0x7f08007a
public const int snackbar_action = 2131230842;
// aapt resource value: 0x7f080079
public const int snackbar_text = 2131230841;
// aapt resource value: 0x7f08002e
public const int snap = 2131230766;
// aapt resource value: 0x7f08004c
public const int spacer = 2131230796;
// aapt resource value: 0x7f080008
public const int split_action_bar = 2131230728;
// aapt resource value: 0x7f08001b
public const int src_atop = 2131230747;
// aapt resource value: 0x7f08001c
public const int src_in = 2131230748;
// aapt resource value: 0x7f08001d
public const int src_over = 2131230749;
// aapt resource value: 0x7f080036
public const int start = 2131230774;
// aapt resource value: 0x7f0800a0
public const int status_bar_latest_event_content = 2131230880;
// aapt resource value: 0x7f08005e
public const int submenuarrow = 2131230814;
// aapt resource value: 0x7f08006f
public const int submit_area = 2131230831;
// aapt resource value: 0x7f080011
public const int tabMode = 2131230737;
// aapt resource value: 0x7f0800b0
public const int text = 2131230896;
// aapt resource value: 0x7f0800ae
public const int text2 = 2131230894;
// aapt resource value: 0x7f080052
public const int textSpacerNoButtons = 2131230802;
// aapt resource value: 0x7f080051
public const int textSpacerNoTitle = 2131230801;
// aapt resource value: 0x7f080080
public const int text_input_password_toggle = 2131230848;
// aapt resource value: 0x7f08000c
public const int textinput_counter = 2131230732;
// aapt resource value: 0x7f08000d
public const int textinput_error = 2131230733;
// aapt resource value: 0x7f0800a6
public const int time = 2131230886;
// aapt resource value: 0x7f08004a
public const int title = 2131230794;
// aapt resource value: 0x7f080059
public const int titleDividerNoCustom = 2131230809;
// aapt resource value: 0x7f080057
public const int title_template = 2131230807;
// aapt resource value: 0x7f080029
public const int top = 2131230761;
// aapt resource value: 0x7f080056
public const int topPanel = 2131230806;
// aapt resource value: 0x7f080077
public const int touch_outside = 2131230839;
// aapt resource value: 0x7f08000a
public const int transition_current_scene = 2131230730;
// aapt resource value: 0x7f08000b
public const int transition_scene_layoutid_cache = 2131230731;
// aapt resource value: 0x7f080009
public const int up = 2131230729;
// aapt resource value: 0x7f080018
public const int useLogo = 2131230744;
// aapt resource value: 0x7f08000e
public const int view_offset_helper = 2131230734;
// aapt resource value: 0x7f0800b2
public const int visible = 2131230898;
// aapt resource value: 0x7f080093
public const int volume_item_container = 2131230867;
// aapt resource value: 0x7f080027
public const int withText = 2131230759;
// aapt resource value: 0x7f08001f
public const int wrap_content = 2131230751;
static Id()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Id()
{
}
}
public partial class Integer
{
// aapt resource value: 0x7f0a0003
public const int abc_config_activityDefaultDur = 2131361795;
// aapt resource value: 0x7f0a0004
public const int abc_config_activityShortDur = 2131361796;
// aapt resource value: 0x7f0a0008
public const int app_bar_elevation_anim_duration = 2131361800;
// aapt resource value: 0x7f0a0009
public const int bottom_sheet_slide_duration = 2131361801;
// aapt resource value: 0x7f0a0005
public const int cancel_button_image_alpha = 2131361797;
// aapt resource value: 0x7f0a0007
public const int design_snackbar_text_max_lines = 2131361799;
// aapt resource value: 0x7f0a000a
public const int hide_password_duration = 2131361802;
// aapt resource value: 0x7f0a0000
public const int mr_controller_volume_group_list_animation_duration_ms = 2131361792;
// aapt resource value: 0x7f0a0001
public const int mr_controller_volume_group_list_fade_in_duration_ms = 2131361793;
// aapt resource value: 0x7f0a0002
public const int mr_controller_volume_group_list_fade_out_duration_ms = 2131361794;
// aapt resource value: 0x7f0a000b
public const int show_password_duration = 2131361803;
// aapt resource value: 0x7f0a0006
public const int status_bar_notification_info_maxnum = 2131361798;
static Integer()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Integer()
{
}
}
public partial class Interpolator
{
// aapt resource value: 0x7f060000
public const int mr_fast_out_slow_in = 2131099648;
// aapt resource value: 0x7f060001
public const int mr_linear_out_slow_in = 2131099649;
static Interpolator()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Interpolator()
{
}
}
public partial class Layout
{
// aapt resource value: 0x7f030000
public const int abc_action_bar_title_item = 2130903040;
// aapt resource value: 0x7f030001
public const int abc_action_bar_up_container = 2130903041;
// aapt resource value: 0x7f030002
public const int abc_action_bar_view_list_nav_layout = 2130903042;
// aapt resource value: 0x7f030003
public const int abc_action_menu_item_layout = 2130903043;
// aapt resource value: 0x7f030004
public const int abc_action_menu_layout = 2130903044;
// aapt resource value: 0x7f030005
public const int abc_action_mode_bar = 2130903045;
// aapt resource value: 0x7f030006
public const int abc_action_mode_close_item_material = 2130903046;
// aapt resource value: 0x7f030007
public const int abc_activity_chooser_view = 2130903047;
// aapt resource value: 0x7f030008
public const int abc_activity_chooser_view_list_item = 2130903048;
// aapt resource value: 0x7f030009
public const int abc_alert_dialog_button_bar_material = 2130903049;
// aapt resource value: 0x7f03000a
public const int abc_alert_dialog_material = 2130903050;
// aapt resource value: 0x7f03000b
public const int abc_alert_dialog_title_material = 2130903051;
// aapt resource value: 0x7f03000c
public const int abc_dialog_title_material = 2130903052;
// aapt resource value: 0x7f03000d
public const int abc_expanded_menu_layout = 2130903053;
// aapt resource value: 0x7f03000e
public const int abc_list_menu_item_checkbox = 2130903054;
// aapt resource value: 0x7f03000f
public const int abc_list_menu_item_icon = 2130903055;
// aapt resource value: 0x7f030010
public const int abc_list_menu_item_layout = 2130903056;
// aapt resource value: 0x7f030011
public const int abc_list_menu_item_radio = 2130903057;
// aapt resource value: 0x7f030012
public const int abc_popup_menu_header_item_layout = 2130903058;
// aapt resource value: 0x7f030013
public const int abc_popup_menu_item_layout = 2130903059;
// aapt resource value: 0x7f030014
public const int abc_screen_content_include = 2130903060;
// aapt resource value: 0x7f030015
public const int abc_screen_simple = 2130903061;
// aapt resource value: 0x7f030016
public const int abc_screen_simple_overlay_action_mode = 2130903062;
// aapt resource value: 0x7f030017
public const int abc_screen_toolbar = 2130903063;
// aapt resource value: 0x7f030018
public const int abc_search_dropdown_item_icons_2line = 2130903064;
// aapt resource value: 0x7f030019
public const int abc_search_view = 2130903065;
// aapt resource value: 0x7f03001a
public const int abc_select_dialog_material = 2130903066;
// aapt resource value: 0x7f03001b
public const int design_bottom_navigation_item = 2130903067;
// aapt resource value: 0x7f03001c
public const int design_bottom_sheet_dialog = 2130903068;
// aapt resource value: 0x7f03001d
public const int design_layout_snackbar = 2130903069;
// aapt resource value: 0x7f03001e
public const int design_layout_snackbar_include = 2130903070;
// aapt resource value: 0x7f03001f
public const int design_layout_tab_icon = 2130903071;
// aapt resource value: 0x7f030020
public const int design_layout_tab_text = 2130903072;
// aapt resource value: 0x7f030021
public const int design_menu_item_action_area = 2130903073;
// aapt resource value: 0x7f030022
public const int design_navigation_item = 2130903074;
// aapt resource value: 0x7f030023
public const int design_navigation_item_header = 2130903075;
// aapt resource value: 0x7f030024
public const int design_navigation_item_separator = 2130903076;
// aapt resource value: 0x7f030025
public const int design_navigation_item_subheader = 2130903077;
// aapt resource value: 0x7f030026
public const int design_navigation_menu = 2130903078;
// aapt resource value: 0x7f030027
public const int design_navigation_menu_item = 2130903079;
// aapt resource value: 0x7f030028
public const int design_text_input_password_icon = 2130903080;
// aapt resource value: 0x7f030029
public const int mr_chooser_dialog = 2130903081;
// aapt resource value: 0x7f03002a
public const int mr_chooser_list_item = 2130903082;
// aapt resource value: 0x7f03002b
public const int mr_controller_material_dialog_b = 2130903083;
// aapt resource value: 0x7f03002c
public const int mr_controller_volume_item = 2130903084;
// aapt resource value: 0x7f03002d
public const int mr_playback_control = 2130903085;
// aapt resource value: 0x7f03002e
public const int mr_volume_control = 2130903086;
// aapt resource value: 0x7f03002f
public const int notification_action = 2130903087;
// aapt resource value: 0x7f030030
public const int notification_action_tombstone = 2130903088;
// aapt resource value: 0x7f030031
public const int notification_media_action = 2130903089;
// aapt resource value: 0x7f030032
public const int notification_media_cancel_action = 2130903090;
// aapt resource value: 0x7f030033
public const int notification_template_big_media = 2130903091;
// aapt resource value: 0x7f030034
public const int notification_template_big_media_custom = 2130903092;
// aapt resource value: 0x7f030035
public const int notification_template_big_media_narrow = 2130903093;
// aapt resource value: 0x7f030036
public const int notification_template_big_media_narrow_custom = 2130903094;
// aapt resource value: 0x7f030037
public const int notification_template_custom_big = 2130903095;
// aapt resource value: 0x7f030038
public const int notification_template_icon_group = 2130903096;
// aapt resource value: 0x7f030039
public const int notification_template_lines_media = 2130903097;
// aapt resource value: 0x7f03003a
public const int notification_template_media = 2130903098;
// aapt resource value: 0x7f03003b
public const int notification_template_media_custom = 2130903099;
// aapt resource value: 0x7f03003c
public const int notification_template_part_chronometer = 2130903100;
// aapt resource value: 0x7f03003d
public const int notification_template_part_time = 2130903101;
// aapt resource value: 0x7f03003e
public const int select_dialog_item_material = 2130903102;
// aapt resource value: 0x7f03003f
public const int select_dialog_multichoice_material = 2130903103;
// aapt resource value: 0x7f030040
public const int select_dialog_singlechoice_material = 2130903104;
// aapt resource value: 0x7f030041
public const int support_simple_spinner_dropdown_item = 2130903105;
static Layout()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Layout()
{
}
}
public partial class String
{
// aapt resource value: 0x7f090015
public const int abc_action_bar_home_description = 2131296277;
// aapt resource value: 0x7f090016
public const int abc_action_bar_home_description_format = 2131296278;
// aapt resource value: 0x7f090017
public const int abc_action_bar_home_subtitle_description_format = 2131296279;
// aapt resource value: 0x7f090018
public const int abc_action_bar_up_description = 2131296280;
// aapt resource value: 0x7f090019
public const int abc_action_menu_overflow_description = 2131296281;
// aapt resource value: 0x7f09001a
public const int abc_action_mode_done = 2131296282;
// aapt resource value: 0x7f09001b
public const int abc_activity_chooser_view_see_all = 2131296283;
// aapt resource value: 0x7f09001c
public const int abc_activitychooserview_choose_application = 2131296284;
// aapt resource value: 0x7f09001d
public const int abc_capital_off = 2131296285;
// aapt resource value: 0x7f09001e
public const int abc_capital_on = 2131296286;
// aapt resource value: 0x7f09002a
public const int abc_font_family_body_1_material = 2131296298;
// aapt resource value: 0x7f09002b
public const int abc_font_family_body_2_material = 2131296299;
// aapt resource value: 0x7f09002c
public const int abc_font_family_button_material = 2131296300;
// aapt resource value: 0x7f09002d
public const int abc_font_family_caption_material = 2131296301;
// aapt resource value: 0x7f09002e
public const int abc_font_family_display_1_material = 2131296302;
// aapt resource value: 0x7f09002f
public const int abc_font_family_display_2_material = 2131296303;
// aapt resource value: 0x7f090030
public const int abc_font_family_display_3_material = 2131296304;
// aapt resource value: 0x7f090031
public const int abc_font_family_display_4_material = 2131296305;
// aapt resource value: 0x7f090032
public const int abc_font_family_headline_material = 2131296306;
// aapt resource value: 0x7f090033
public const int abc_font_family_menu_material = 2131296307;
// aapt resource value: 0x7f090034
public const int abc_font_family_subhead_material = 2131296308;
// aapt resource value: 0x7f090035
public const int abc_font_family_title_material = 2131296309;
// aapt resource value: 0x7f09001f
public const int abc_search_hint = 2131296287;
// aapt resource value: 0x7f090020
public const int abc_searchview_description_clear = 2131296288;
// aapt resource value: 0x7f090021
public const int abc_searchview_description_query = 2131296289;
// aapt resource value: 0x7f090022
public const int abc_searchview_description_search = 2131296290;
// aapt resource value: 0x7f090023
public const int abc_searchview_description_submit = 2131296291;
// aapt resource value: 0x7f090024
public const int abc_searchview_description_voice = 2131296292;
// aapt resource value: 0x7f090025
public const int abc_shareactionprovider_share_with = 2131296293;
// aapt resource value: 0x7f090026
public const int abc_shareactionprovider_share_with_application = 2131296294;
// aapt resource value: 0x7f090027
public const int abc_toolbar_collapse_description = 2131296295;
// aapt resource value: 0x7f09003e
public const int app_name = 2131296318;
// aapt resource value: 0x7f090036
public const int appbar_scrolling_view_behavior = 2131296310;
// aapt resource value: 0x7f090037
public const int bottom_sheet_behavior = 2131296311;
// aapt resource value: 0x7f090038
public const int character_counter_pattern = 2131296312;
// aapt resource value: 0x7f090000
public const int mr_button_content_description = 2131296256;
// aapt resource value: 0x7f090001
public const int mr_cast_button_connected = 2131296257;
// aapt resource value: 0x7f090002
public const int mr_cast_button_connecting = 2131296258;
// aapt resource value: 0x7f090003
public const int mr_cast_button_disconnected = 2131296259;
// aapt resource value: 0x7f090004
public const int mr_chooser_searching = 2131296260;
// aapt resource value: 0x7f090005
public const int mr_chooser_title = 2131296261;
// aapt resource value: 0x7f090006
public const int mr_controller_album_art = 2131296262;
// aapt resource value: 0x7f090007
public const int mr_controller_casting_screen = 2131296263;
// aapt resource value: 0x7f090008
public const int mr_controller_close_description = 2131296264;
// aapt resource value: 0x7f090009
public const int mr_controller_collapse_group = 2131296265;
// aapt resource value: 0x7f09000a
public const int mr_controller_disconnect = 2131296266;
// aapt resource value: 0x7f09000b
public const int mr_controller_expand_group = 2131296267;
// aapt resource value: 0x7f09000c
public const int mr_controller_no_info_available = 2131296268;
// aapt resource value: 0x7f09000d
public const int mr_controller_no_media_selected = 2131296269;
// aapt resource value: 0x7f09000e
public const int mr_controller_pause = 2131296270;
// aapt resource value: 0x7f09000f
public const int mr_controller_play = 2131296271;
// aapt resource value: 0x7f090014
public const int mr_controller_stop = 2131296276;
// aapt resource value: 0x7f090010
public const int mr_controller_stop_casting = 2131296272;
// aapt resource value: 0x7f090011
public const int mr_controller_volume_slider = 2131296273;
// aapt resource value: 0x7f090012
public const int mr_system_route_name = 2131296274;
// aapt resource value: 0x7f090013
public const int mr_user_route_category_name = 2131296275;
// aapt resource value: 0x7f090039
public const int password_toggle_content_description = 2131296313;
// aapt resource value: 0x7f09003a
public const int path_password_eye = 2131296314;
// aapt resource value: 0x7f09003b
public const int path_password_eye_mask_strike_through = 2131296315;
// aapt resource value: 0x7f09003c
public const int path_password_eye_mask_visible = 2131296316;
// aapt resource value: 0x7f09003d
public const int path_password_strike_through = 2131296317;
// aapt resource value: 0x7f090028
public const int search_menu_title = 2131296296;
// aapt resource value: 0x7f090029
public const int status_bar_notification_info_overflow = 2131296297;
static String()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private String()
{
}
}
public partial class Style
{
// aapt resource value: 0x7f0b00ae
public const int AlertDialog_AppCompat = 2131427502;
// aapt resource value: 0x7f0b00af
public const int AlertDialog_AppCompat_Light = 2131427503;
// aapt resource value: 0x7f0b00b0
public const int Animation_AppCompat_Dialog = 2131427504;
// aapt resource value: 0x7f0b00b1
public const int Animation_AppCompat_DropDownUp = 2131427505;
// aapt resource value: 0x7f0b0170
public const int Animation_Design_BottomSheetDialog = 2131427696;
// aapt resource value: 0x7f0b00b2
public const int Base_AlertDialog_AppCompat = 2131427506;
// aapt resource value: 0x7f0b00b3
public const int Base_AlertDialog_AppCompat_Light = 2131427507;
// aapt resource value: 0x7f0b00b4
public const int Base_Animation_AppCompat_Dialog = 2131427508;
// aapt resource value: 0x7f0b00b5
public const int Base_Animation_AppCompat_DropDownUp = 2131427509;
// aapt resource value: 0x7f0b000c
public const int Base_CardView = 2131427340;
// aapt resource value: 0x7f0b00b6
public const int Base_DialogWindowTitle_AppCompat = 2131427510;
// aapt resource value: 0x7f0b00b7
public const int Base_DialogWindowTitleBackground_AppCompat = 2131427511;
// aapt resource value: 0x7f0b004e
public const int Base_TextAppearance_AppCompat = 2131427406;
// aapt resource value: 0x7f0b004f
public const int Base_TextAppearance_AppCompat_Body1 = 2131427407;
// aapt resource value: 0x7f0b0050
public const int Base_TextAppearance_AppCompat_Body2 = 2131427408;
// aapt resource value: 0x7f0b0036
public const int Base_TextAppearance_AppCompat_Button = 2131427382;
// aapt resource value: 0x7f0b0051
public const int Base_TextAppearance_AppCompat_Caption = 2131427409;
// aapt resource value: 0x7f0b0052
public const int Base_TextAppearance_AppCompat_Display1 = 2131427410;
// aapt resource value: 0x7f0b0053
public const int Base_TextAppearance_AppCompat_Display2 = 2131427411;
// aapt resource value: 0x7f0b0054
public const int Base_TextAppearance_AppCompat_Display3 = 2131427412;
// aapt resource value: 0x7f0b0055
public const int Base_TextAppearance_AppCompat_Display4 = 2131427413;
// aapt resource value: 0x7f0b0056
public const int Base_TextAppearance_AppCompat_Headline = 2131427414;
// aapt resource value: 0x7f0b001a
public const int Base_TextAppearance_AppCompat_Inverse = 2131427354;
// aapt resource value: 0x7f0b0057
public const int Base_TextAppearance_AppCompat_Large = 2131427415;
// aapt resource value: 0x7f0b001b
public const int Base_TextAppearance_AppCompat_Large_Inverse = 2131427355;
// aapt resource value: 0x7f0b0058
public const int Base_TextAppearance_AppCompat_Light_Widget_PopupMenu_Large = 2131427416;
// aapt resource value: 0x7f0b0059
public const int Base_TextAppearance_AppCompat_Light_Widget_PopupMenu_Small = 2131427417;
// aapt resource value: 0x7f0b005a
public const int Base_TextAppearance_AppCompat_Medium = 2131427418;
// aapt resource value: 0x7f0b001c
public const int Base_TextAppearance_AppCompat_Medium_Inverse = 2131427356;
// aapt resource value: 0x7f0b005b
public const int Base_TextAppearance_AppCompat_Menu = 2131427419;
// aapt resource value: 0x7f0b00b8
public const int Base_TextAppearance_AppCompat_SearchResult = 2131427512;
// aapt resource value: 0x7f0b005c
public const int Base_TextAppearance_AppCompat_SearchResult_Subtitle = 2131427420;
// aapt resource value: 0x7f0b005d
public const int Base_TextAppearance_AppCompat_SearchResult_Title = 2131427421;
// aapt resource value: 0x7f0b005e
public const int Base_TextAppearance_AppCompat_Small = 2131427422;
// aapt resource value: 0x7f0b001d
public const int Base_TextAppearance_AppCompat_Small_Inverse = 2131427357;
// aapt resource value: 0x7f0b005f
public const int Base_TextAppearance_AppCompat_Subhead = 2131427423;
// aapt resource value: 0x7f0b001e
public const int Base_TextAppearance_AppCompat_Subhead_Inverse = 2131427358;
// aapt resource value: 0x7f0b0060
public const int Base_TextAppearance_AppCompat_Title = 2131427424;
// aapt resource value: 0x7f0b001f
public const int Base_TextAppearance_AppCompat_Title_Inverse = 2131427359;
// aapt resource value: 0x7f0b00a3
public const int Base_TextAppearance_AppCompat_Widget_ActionBar_Menu = 2131427491;
// aapt resource value: 0x7f0b0061
public const int Base_TextAppearance_AppCompat_Widget_ActionBar_Subtitle = 2131427425;
// aapt resource value: 0x7f0b0062
public const int Base_TextAppearance_AppCompat_Widget_ActionBar_Subtitle_Inverse = 2131427426;
// aapt resource value: 0x7f0b0063
public const int Base_TextAppearance_AppCompat_Widget_ActionBar_Title = 2131427427;
// aapt resource value: 0x7f0b0064
public const int Base_TextAppearance_AppCompat_Widget_ActionBar_Title_Inverse = 2131427428;
// aapt resource value: 0x7f0b0065
public const int Base_TextAppearance_AppCompat_Widget_ActionMode_Subtitle = 2131427429;
// aapt resource value: 0x7f0b0066
public const int Base_TextAppearance_AppCompat_Widget_ActionMode_Title = 2131427430;
// aapt resource value: 0x7f0b0067
public const int Base_TextAppearance_AppCompat_Widget_Button = 2131427431;
// aapt resource value: 0x7f0b00aa
public const int Base_TextAppearance_AppCompat_Widget_Button_Borderless_Colored = 2131427498;
// aapt resource value: 0x7f0b00ab
public const int Base_TextAppearance_AppCompat_Widget_Button_Colored = 2131427499;
// aapt resource value: 0x7f0b00a4
public const int Base_TextAppearance_AppCompat_Widget_Button_Inverse = 2131427492;
// aapt resource value: 0x7f0b00b9
public const int Base_TextAppearance_AppCompat_Widget_DropDownItem = 2131427513;
// aapt resource value: 0x7f0b0068
public const int Base_TextAppearance_AppCompat_Widget_PopupMenu_Header = 2131427432;
// aapt resource value: 0x7f0b0069
public const int Base_TextAppearance_AppCompat_Widget_PopupMenu_Large = 2131427433;
// aapt resource value: 0x7f0b006a
public const int Base_TextAppearance_AppCompat_Widget_PopupMenu_Small = 2131427434;
// aapt resource value: 0x7f0b006b
public const int Base_TextAppearance_AppCompat_Widget_Switch = 2131427435;
// aapt resource value: 0x7f0b006c
public const int Base_TextAppearance_AppCompat_Widget_TextView_SpinnerItem = 2131427436;
// aapt resource value: 0x7f0b00ba
public const int Base_TextAppearance_Widget_AppCompat_ExpandedMenu_Item = 2131427514;
// aapt resource value: 0x7f0b006d
public const int Base_TextAppearance_Widget_AppCompat_Toolbar_Subtitle = 2131427437;
// aapt resource value: 0x7f0b006e
public const int Base_TextAppearance_Widget_AppCompat_Toolbar_Title = 2131427438;
// aapt resource value: 0x7f0b006f
public const int Base_Theme_AppCompat = 2131427439;
// aapt resource value: 0x7f0b00bb
public const int Base_Theme_AppCompat_CompactMenu = 2131427515;
// aapt resource value: 0x7f0b0020
public const int Base_Theme_AppCompat_Dialog = 2131427360;
// aapt resource value: 0x7f0b0021
public const int Base_Theme_AppCompat_Dialog_Alert = 2131427361;
// aapt resource value: 0x7f0b00bc
public const int Base_Theme_AppCompat_Dialog_FixedSize = 2131427516;
// aapt resource value: 0x7f0b0022
public const int Base_Theme_AppCompat_Dialog_MinWidth = 2131427362;
// aapt resource value: 0x7f0b0010
public const int Base_Theme_AppCompat_DialogWhenLarge = 2131427344;
// aapt resource value: 0x7f0b0070
public const int Base_Theme_AppCompat_Light = 2131427440;
// aapt resource value: 0x7f0b00bd
public const int Base_Theme_AppCompat_Light_DarkActionBar = 2131427517;
// aapt resource value: 0x7f0b0023
public const int Base_Theme_AppCompat_Light_Dialog = 2131427363;
// aapt resource value: 0x7f0b0024
public const int Base_Theme_AppCompat_Light_Dialog_Alert = 2131427364;
// aapt resource value: 0x7f0b00be
public const int Base_Theme_AppCompat_Light_Dialog_FixedSize = 2131427518;
// aapt resource value: 0x7f0b0025
public const int Base_Theme_AppCompat_Light_Dialog_MinWidth = 2131427365;
// aapt resource value: 0x7f0b0011
public const int Base_Theme_AppCompat_Light_DialogWhenLarge = 2131427345;
// aapt resource value: 0x7f0b00bf
public const int Base_ThemeOverlay_AppCompat = 2131427519;
// aapt resource value: 0x7f0b00c0
public const int Base_ThemeOverlay_AppCompat_ActionBar = 2131427520;
// aapt resource value: 0x7f0b00c1
public const int Base_ThemeOverlay_AppCompat_Dark = 2131427521;
// aapt resource value: 0x7f0b00c2
public const int Base_ThemeOverlay_AppCompat_Dark_ActionBar = 2131427522;
// aapt resource value: 0x7f0b0026
public const int Base_ThemeOverlay_AppCompat_Dialog = 2131427366;
// aapt resource value: 0x7f0b0027
public const int Base_ThemeOverlay_AppCompat_Dialog_Alert = 2131427367;
// aapt resource value: 0x7f0b00c3
public const int Base_ThemeOverlay_AppCompat_Light = 2131427523;
// aapt resource value: 0x7f0b0028
public const int Base_V11_Theme_AppCompat_Dialog = 2131427368;
// aapt resource value: 0x7f0b0029
public const int Base_V11_Theme_AppCompat_Light_Dialog = 2131427369;
// aapt resource value: 0x7f0b002a
public const int Base_V11_ThemeOverlay_AppCompat_Dialog = 2131427370;
// aapt resource value: 0x7f0b0032
public const int Base_V12_Widget_AppCompat_AutoCompleteTextView = 2131427378;
// aapt resource value: 0x7f0b0033
public const int Base_V12_Widget_AppCompat_EditText = 2131427379;
// aapt resource value: 0x7f0b0071
public const int Base_V21_Theme_AppCompat = 2131427441;
// aapt resource value: 0x7f0b0072
public const int Base_V21_Theme_AppCompat_Dialog = 2131427442;
// aapt resource value: 0x7f0b0073
public const int Base_V21_Theme_AppCompat_Light = 2131427443;
// aapt resource value: 0x7f0b0074
public const int Base_V21_Theme_AppCompat_Light_Dialog = 2131427444;
// aapt resource value: 0x7f0b0075
public const int Base_V21_ThemeOverlay_AppCompat_Dialog = 2131427445;
// aapt resource value: 0x7f0b00a1
public const int Base_V22_Theme_AppCompat = 2131427489;
// aapt resource value: 0x7f0b00a2
public const int Base_V22_Theme_AppCompat_Light = 2131427490;
// aapt resource value: 0x7f0b00a5
public const int Base_V23_Theme_AppCompat = 2131427493;
// aapt resource value: 0x7f0b00a6
public const int Base_V23_Theme_AppCompat_Light = 2131427494;
// aapt resource value: 0x7f0b00c4
public const int Base_V7_Theme_AppCompat = 2131427524;
// aapt resource value: 0x7f0b00c5
public const int Base_V7_Theme_AppCompat_Dialog = 2131427525;
// aapt resource value: 0x7f0b00c6
public const int Base_V7_Theme_AppCompat_Light = 2131427526;
// aapt resource value: 0x7f0b00c7
public const int Base_V7_Theme_AppCompat_Light_Dialog = 2131427527;
// aapt resource value: 0x7f0b00c8
public const int Base_V7_ThemeOverlay_AppCompat_Dialog = 2131427528;
// aapt resource value: 0x7f0b00c9
public const int Base_V7_Widget_AppCompat_AutoCompleteTextView = 2131427529;
// aapt resource value: 0x7f0b00ca
public const int Base_V7_Widget_AppCompat_EditText = 2131427530;
// aapt resource value: 0x7f0b00cb
public const int Base_Widget_AppCompat_ActionBar = 2131427531;
// aapt resource value: 0x7f0b00cc
public const int Base_Widget_AppCompat_ActionBar_Solid = 2131427532;
// aapt resource value: 0x7f0b00cd
public const int Base_Widget_AppCompat_ActionBar_TabBar = 2131427533;
// aapt resource value: 0x7f0b0076
public const int Base_Widget_AppCompat_ActionBar_TabText = 2131427446;
// aapt resource value: 0x7f0b0077
public const int Base_Widget_AppCompat_ActionBar_TabView = 2131427447;
// aapt resource value: 0x7f0b0078
public const int Base_Widget_AppCompat_ActionButton = 2131427448;
// aapt resource value: 0x7f0b0079
public const int Base_Widget_AppCompat_ActionButton_CloseMode = 2131427449;
// aapt resource value: 0x7f0b007a
public const int Base_Widget_AppCompat_ActionButton_Overflow = 2131427450;
// aapt resource value: 0x7f0b00ce
public const int Base_Widget_AppCompat_ActionMode = 2131427534;
// aapt resource value: 0x7f0b00cf
public const int Base_Widget_AppCompat_ActivityChooserView = 2131427535;
// aapt resource value: 0x7f0b0034
public const int Base_Widget_AppCompat_AutoCompleteTextView = 2131427380;
// aapt resource value: 0x7f0b007b
public const int Base_Widget_AppCompat_Button = 2131427451;
// aapt resource value: 0x7f0b007c
public const int Base_Widget_AppCompat_Button_Borderless = 2131427452;
// aapt resource value: 0x7f0b007d
public const int Base_Widget_AppCompat_Button_Borderless_Colored = 2131427453;
// aapt resource value: 0x7f0b00d0
public const int Base_Widget_AppCompat_Button_ButtonBar_AlertDialog = 2131427536;
// aapt resource value: 0x7f0b00a7
public const int Base_Widget_AppCompat_Button_Colored = 2131427495;
// aapt resource value: 0x7f0b007e
public const int Base_Widget_AppCompat_Button_Small = 2131427454;
// aapt resource value: 0x7f0b007f
public const int Base_Widget_AppCompat_ButtonBar = 2131427455;
// aapt resource value: 0x7f0b00d1
public const int Base_Widget_AppCompat_ButtonBar_AlertDialog = 2131427537;
// aapt resource value: 0x7f0b0080
public const int Base_Widget_AppCompat_CompoundButton_CheckBox = 2131427456;
// aapt resource value: 0x7f0b0081
public const int Base_Widget_AppCompat_CompoundButton_RadioButton = 2131427457;
// aapt resource value: 0x7f0b00d2
public const int Base_Widget_AppCompat_CompoundButton_Switch = 2131427538;
// aapt resource value: 0x7f0b000f
public const int Base_Widget_AppCompat_DrawerArrowToggle = 2131427343;
// aapt resource value: 0x7f0b00d3
public const int Base_Widget_AppCompat_DrawerArrowToggle_Common = 2131427539;
// aapt resource value: 0x7f0b0082
public const int Base_Widget_AppCompat_DropDownItem_Spinner = 2131427458;
// aapt resource value: 0x7f0b0035
public const int Base_Widget_AppCompat_EditText = 2131427381;
// aapt resource value: 0x7f0b0083
public const int Base_Widget_AppCompat_ImageButton = 2131427459;
// aapt resource value: 0x7f0b00d4
public const int Base_Widget_AppCompat_Light_ActionBar = 2131427540;
// aapt resource value: 0x7f0b00d5
public const int Base_Widget_AppCompat_Light_ActionBar_Solid = 2131427541;
// aapt resource value: 0x7f0b00d6
public const int Base_Widget_AppCompat_Light_ActionBar_TabBar = 2131427542;
// aapt resource value: 0x7f0b0084
public const int Base_Widget_AppCompat_Light_ActionBar_TabText = 2131427460;
// aapt resource value: 0x7f0b0085
public const int Base_Widget_AppCompat_Light_ActionBar_TabText_Inverse = 2131427461;
// aapt resource value: 0x7f0b0086
public const int Base_Widget_AppCompat_Light_ActionBar_TabView = 2131427462;
// aapt resource value: 0x7f0b0087
public const int Base_Widget_AppCompat_Light_PopupMenu = 2131427463;
// aapt resource value: 0x7f0b0088
public const int Base_Widget_AppCompat_Light_PopupMenu_Overflow = 2131427464;
// aapt resource value: 0x7f0b00d7
public const int Base_Widget_AppCompat_ListMenuView = 2131427543;
// aapt resource value: 0x7f0b0089
public const int Base_Widget_AppCompat_ListPopupWindow = 2131427465;
// aapt resource value: 0x7f0b008a
public const int Base_Widget_AppCompat_ListView = 2131427466;
// aapt resource value: 0x7f0b008b
public const int Base_Widget_AppCompat_ListView_DropDown = 2131427467;
// aapt resource value: 0x7f0b008c
public const int Base_Widget_AppCompat_ListView_Menu = 2131427468;
// aapt resource value: 0x7f0b008d
public const int Base_Widget_AppCompat_PopupMenu = 2131427469;
// aapt resource value: 0x7f0b008e
public const int Base_Widget_AppCompat_PopupMenu_Overflow = 2131427470;
// aapt resource value: 0x7f0b00d8
public const int Base_Widget_AppCompat_PopupWindow = 2131427544;
// aapt resource value: 0x7f0b002b
public const int Base_Widget_AppCompat_ProgressBar = 2131427371;
// aapt resource value: 0x7f0b002c
public const int Base_Widget_AppCompat_ProgressBar_Horizontal = 2131427372;
// aapt resource value: 0x7f0b008f
public const int Base_Widget_AppCompat_RatingBar = 2131427471;
// aapt resource value: 0x7f0b00a8
public const int Base_Widget_AppCompat_RatingBar_Indicator = 2131427496;
// aapt resource value: 0x7f0b00a9
public const int Base_Widget_AppCompat_RatingBar_Small = 2131427497;
// aapt resource value: 0x7f0b00d9
public const int Base_Widget_AppCompat_SearchView = 2131427545;
// aapt resource value: 0x7f0b00da
public const int Base_Widget_AppCompat_SearchView_ActionBar = 2131427546;
// aapt resource value: 0x7f0b0090
public const int Base_Widget_AppCompat_SeekBar = 2131427472;
// aapt resource value: 0x7f0b00db
public const int Base_Widget_AppCompat_SeekBar_Discrete = 2131427547;
// aapt resource value: 0x7f0b0091
public const int Base_Widget_AppCompat_Spinner = 2131427473;
// aapt resource value: 0x7f0b0012
public const int Base_Widget_AppCompat_Spinner_Underlined = 2131427346;
// aapt resource value: 0x7f0b0092
public const int Base_Widget_AppCompat_TextView_SpinnerItem = 2131427474;
// aapt resource value: 0x7f0b00dc
public const int Base_Widget_AppCompat_Toolbar = 2131427548;
// aapt resource value: 0x7f0b0093
public const int Base_Widget_AppCompat_Toolbar_Button_Navigation = 2131427475;
// aapt resource value: 0x7f0b0171
public const int Base_Widget_Design_AppBarLayout = 2131427697;
// aapt resource value: 0x7f0b0172
public const int Base_Widget_Design_TabLayout = 2131427698;
// aapt resource value: 0x7f0b000b
public const int CardView = 2131427339;
// aapt resource value: 0x7f0b000d
public const int CardView_Dark = 2131427341;
// aapt resource value: 0x7f0b000e
public const int CardView_Light = 2131427342;
// aapt resource value: 0x7f0b002d
public const int Platform_AppCompat = 2131427373;
// aapt resource value: 0x7f0b002e
public const int Platform_AppCompat_Light = 2131427374;
// aapt resource value: 0x7f0b0094
public const int Platform_ThemeOverlay_AppCompat = 2131427476;
// aapt resource value: 0x7f0b0095
public const int Platform_ThemeOverlay_AppCompat_Dark = 2131427477;
// aapt resource value: 0x7f0b0096
public const int Platform_ThemeOverlay_AppCompat_Light = 2131427478;
// aapt resource value: 0x7f0b002f
public const int Platform_V11_AppCompat = 2131427375;
// aapt resource value: 0x7f0b0030
public const int Platform_V11_AppCompat_Light = 2131427376;
// aapt resource value: 0x7f0b0037
public const int Platform_V14_AppCompat = 2131427383;
// aapt resource value: 0x7f0b0038
public const int Platform_V14_AppCompat_Light = 2131427384;
// aapt resource value: 0x7f0b0097
public const int Platform_V21_AppCompat = 2131427479;
// aapt resource value: 0x7f0b0098
public const int Platform_V21_AppCompat_Light = 2131427480;
// aapt resource value: 0x7f0b00ac
public const int Platform_V25_AppCompat = 2131427500;
// aapt resource value: 0x7f0b00ad
public const int Platform_V25_AppCompat_Light = 2131427501;
// aapt resource value: 0x7f0b0031
public const int Platform_Widget_AppCompat_Spinner = 2131427377;
// aapt resource value: 0x7f0b0040
public const int RtlOverlay_DialogWindowTitle_AppCompat = 2131427392;
// aapt resource value: 0x7f0b0041
public const int RtlOverlay_Widget_AppCompat_ActionBar_TitleItem = 2131427393;
// aapt resource value: 0x7f0b0042
public const int RtlOverlay_Widget_AppCompat_DialogTitle_Icon = 2131427394;
// aapt resource value: 0x7f0b0043
public const int RtlOverlay_Widget_AppCompat_PopupMenuItem = 2131427395;
// aapt resource value: 0x7f0b0044
public const int RtlOverlay_Widget_AppCompat_PopupMenuItem_InternalGroup = 2131427396;
// aapt resource value: 0x7f0b0045
public const int RtlOverlay_Widget_AppCompat_PopupMenuItem_Text = 2131427397;
// aapt resource value: 0x7f0b0046
public const int RtlOverlay_Widget_AppCompat_Search_DropDown = 2131427398;
// aapt resource value: 0x7f0b0047
public const int RtlOverlay_Widget_AppCompat_Search_DropDown_Icon1 = 2131427399;
// aapt resource value: 0x7f0b0048
public const int RtlOverlay_Widget_AppCompat_Search_DropDown_Icon2 = 2131427400;
// aapt resource value: 0x7f0b0049
public const int RtlOverlay_Widget_AppCompat_Search_DropDown_Query = 2131427401;
// aapt resource value: 0x7f0b004a
public const int RtlOverlay_Widget_AppCompat_Search_DropDown_Text = 2131427402;
// aapt resource value: 0x7f0b004b
public const int RtlOverlay_Widget_AppCompat_SearchView_MagIcon = 2131427403;
// aapt resource value: 0x7f0b004c
public const int RtlUnderlay_Widget_AppCompat_ActionButton = 2131427404;
// aapt resource value: 0x7f0b004d
public const int RtlUnderlay_Widget_AppCompat_ActionButton_Overflow = 2131427405;
// aapt resource value: 0x7f0b00dd
public const int TextAppearance_AppCompat = 2131427549;
// aapt resource value: 0x7f0b00de
public const int TextAppearance_AppCompat_Body1 = 2131427550;
// aapt resource value: 0x7f0b00df
public const int TextAppearance_AppCompat_Body2 = 2131427551;
// aapt resource value: 0x7f0b00e0
public const int TextAppearance_AppCompat_Button = 2131427552;
// aapt resource value: 0x7f0b00e1
public const int TextAppearance_AppCompat_Caption = 2131427553;
// aapt resource value: 0x7f0b00e2
public const int TextAppearance_AppCompat_Display1 = 2131427554;
// aapt resource value: 0x7f0b00e3
public const int TextAppearance_AppCompat_Display2 = 2131427555;
// aapt resource value: 0x7f0b00e4
public const int TextAppearance_AppCompat_Display3 = 2131427556;
// aapt resource value: 0x7f0b00e5
public const int TextAppearance_AppCompat_Display4 = 2131427557;
// aapt resource value: 0x7f0b00e6
public const int TextAppearance_AppCompat_Headline = 2131427558;
// aapt resource value: 0x7f0b00e7
public const int TextAppearance_AppCompat_Inverse = 2131427559;
// aapt resource value: 0x7f0b00e8
public const int TextAppearance_AppCompat_Large = 2131427560;
// aapt resource value: 0x7f0b00e9
public const int TextAppearance_AppCompat_Large_Inverse = 2131427561;
// aapt resource value: 0x7f0b00ea
public const int TextAppearance_AppCompat_Light_SearchResult_Subtitle = 2131427562;
// aapt resource value: 0x7f0b00eb
public const int TextAppearance_AppCompat_Light_SearchResult_Title = 2131427563;
// aapt resource value: 0x7f0b00ec
public const int TextAppearance_AppCompat_Light_Widget_PopupMenu_Large = 2131427564;
// aapt resource value: 0x7f0b00ed
public const int TextAppearance_AppCompat_Light_Widget_PopupMenu_Small = 2131427565;
// aapt resource value: 0x7f0b00ee
public const int TextAppearance_AppCompat_Medium = 2131427566;
// aapt resource value: 0x7f0b00ef
public const int TextAppearance_AppCompat_Medium_Inverse = 2131427567;
// aapt resource value: 0x7f0b00f0
public const int TextAppearance_AppCompat_Menu = 2131427568;
// aapt resource value: 0x7f0b0039
public const int TextAppearance_AppCompat_Notification = 2131427385;
// aapt resource value: 0x7f0b0099
public const int TextAppearance_AppCompat_Notification_Info = 2131427481;
// aapt resource value: 0x7f0b009a
public const int TextAppearance_AppCompat_Notification_Info_Media = 2131427482;
// aapt resource value: 0x7f0b00f1
public const int TextAppearance_AppCompat_Notification_Line2 = 2131427569;
// aapt resource value: 0x7f0b00f2
public const int TextAppearance_AppCompat_Notification_Line2_Media = 2131427570;
// aapt resource value: 0x7f0b009b
public const int TextAppearance_AppCompat_Notification_Media = 2131427483;
// aapt resource value: 0x7f0b009c
public const int TextAppearance_AppCompat_Notification_Time = 2131427484;
// aapt resource value: 0x7f0b009d
public const int TextAppearance_AppCompat_Notification_Time_Media = 2131427485;
// aapt resource value: 0x7f0b003a
public const int TextAppearance_AppCompat_Notification_Title = 2131427386;
// aapt resource value: 0x7f0b009e
public const int TextAppearance_AppCompat_Notification_Title_Media = 2131427486;
// aapt resource value: 0x7f0b00f3
public const int TextAppearance_AppCompat_SearchResult_Subtitle = 2131427571;
// aapt resource value: 0x7f0b00f4
public const int TextAppearance_AppCompat_SearchResult_Title = 2131427572;
// aapt resource value: 0x7f0b00f5
public const int TextAppearance_AppCompat_Small = 2131427573;
// aapt resource value: 0x7f0b00f6
public const int TextAppearance_AppCompat_Small_Inverse = 2131427574;
// aapt resource value: 0x7f0b00f7
public const int TextAppearance_AppCompat_Subhead = 2131427575;
// aapt resource value: 0x7f0b00f8
public const int TextAppearance_AppCompat_Subhead_Inverse = 2131427576;
// aapt resource value: 0x7f0b00f9
public const int TextAppearance_AppCompat_Title = 2131427577;
// aapt resource value: 0x7f0b00fa
public const int TextAppearance_AppCompat_Title_Inverse = 2131427578;
// aapt resource value: 0x7f0b00fb
public const int TextAppearance_AppCompat_Widget_ActionBar_Menu = 2131427579;
// aapt resource value: 0x7f0b00fc
public const int TextAppearance_AppCompat_Widget_ActionBar_Subtitle = 2131427580;
// aapt resource value: 0x7f0b00fd
public const int TextAppearance_AppCompat_Widget_ActionBar_Subtitle_Inverse = 2131427581;
// aapt resource value: 0x7f0b00fe
public const int TextAppearance_AppCompat_Widget_ActionBar_Title = 2131427582;
// aapt resource value: 0x7f0b00ff
public const int TextAppearance_AppCompat_Widget_ActionBar_Title_Inverse = 2131427583;
// aapt resource value: 0x7f0b0100
public const int TextAppearance_AppCompat_Widget_ActionMode_Subtitle = 2131427584;
// aapt resource value: 0x7f0b0101
public const int TextAppearance_AppCompat_Widget_ActionMode_Subtitle_Inverse = 2131427585;
// aapt resource value: 0x7f0b0102
public const int TextAppearance_AppCompat_Widget_ActionMode_Title = 2131427586;
// aapt resource value: 0x7f0b0103
public const int TextAppearance_AppCompat_Widget_ActionMode_Title_Inverse = 2131427587;
// aapt resource value: 0x7f0b0104
public const int TextAppearance_AppCompat_Widget_Button = 2131427588;
// aapt resource value: 0x7f0b0105
public const int TextAppearance_AppCompat_Widget_Button_Borderless_Colored = 2131427589;
// aapt resource value: 0x7f0b0106
public const int TextAppearance_AppCompat_Widget_Button_Colored = 2131427590;
// aapt resource value: 0x7f0b0107
public const int TextAppearance_AppCompat_Widget_Button_Inverse = 2131427591;
// aapt resource value: 0x7f0b0108
public const int TextAppearance_AppCompat_Widget_DropDownItem = 2131427592;
// aapt resource value: 0x7f0b0109
public const int TextAppearance_AppCompat_Widget_PopupMenu_Header = 2131427593;
// aapt resource value: 0x7f0b010a
public const int TextAppearance_AppCompat_Widget_PopupMenu_Large = 2131427594;
// aapt resource value: 0x7f0b010b
public const int TextAppearance_AppCompat_Widget_PopupMenu_Small = 2131427595;
// aapt resource value: 0x7f0b010c
public const int TextAppearance_AppCompat_Widget_Switch = 2131427596;
// aapt resource value: 0x7f0b010d
public const int TextAppearance_AppCompat_Widget_TextView_SpinnerItem = 2131427597;
// aapt resource value: 0x7f0b0173
public const int TextAppearance_Design_CollapsingToolbar_Expanded = 2131427699;
// aapt resource value: 0x7f0b0174
public const int TextAppearance_Design_Counter = 2131427700;
// aapt resource value: 0x7f0b0175
public const int TextAppearance_Design_Counter_Overflow = 2131427701;
// aapt resource value: 0x7f0b0176
public const int TextAppearance_Design_Error = 2131427702;
// aapt resource value: 0x7f0b0177
public const int TextAppearance_Design_Hint = 2131427703;
// aapt resource value: 0x7f0b0178
public const int TextAppearance_Design_Snackbar_Message = 2131427704;
// aapt resource value: 0x7f0b0179
public const int TextAppearance_Design_Tab = 2131427705;
// aapt resource value: 0x7f0b0000
public const int TextAppearance_MediaRouter_PrimaryText = 2131427328;
// aapt resource value: 0x7f0b0001
public const int TextAppearance_MediaRouter_SecondaryText = 2131427329;
// aapt resource value: 0x7f0b0002
public const int TextAppearance_MediaRouter_Title = 2131427330;
// aapt resource value: 0x7f0b003b
public const int TextAppearance_StatusBar_EventContent = 2131427387;
// aapt resource value: 0x7f0b003c
public const int TextAppearance_StatusBar_EventContent_Info = 2131427388;
// aapt resource value: 0x7f0b003d
public const int TextAppearance_StatusBar_EventContent_Line2 = 2131427389;
// aapt resource value: 0x7f0b003e
public const int TextAppearance_StatusBar_EventContent_Time = 2131427390;
// aapt resource value: 0x7f0b003f
public const int TextAppearance_StatusBar_EventContent_Title = 2131427391;
// aapt resource value: 0x7f0b010e
public const int TextAppearance_Widget_AppCompat_ExpandedMenu_Item = 2131427598;
// aapt resource value: 0x7f0b010f
public const int TextAppearance_Widget_AppCompat_Toolbar_Subtitle = 2131427599;
// aapt resource value: 0x7f0b0110
public const int TextAppearance_Widget_AppCompat_Toolbar_Title = 2131427600;
// aapt resource value: 0x7f0b0111
public const int Theme_AppCompat = 2131427601;
// aapt resource value: 0x7f0b0112
public const int Theme_AppCompat_CompactMenu = 2131427602;
// aapt resource value: 0x7f0b0013
public const int Theme_AppCompat_DayNight = 2131427347;
// aapt resource value: 0x7f0b0014
public const int Theme_AppCompat_DayNight_DarkActionBar = 2131427348;
// aapt resource value: 0x7f0b0015
public const int Theme_AppCompat_DayNight_Dialog = 2131427349;
// aapt resource value: 0x7f0b0016
public const int Theme_AppCompat_DayNight_Dialog_Alert = 2131427350;
// aapt resource value: 0x7f0b0017
public const int Theme_AppCompat_DayNight_Dialog_MinWidth = 2131427351;
// aapt resource value: 0x7f0b0018
public const int Theme_AppCompat_DayNight_DialogWhenLarge = 2131427352;
// aapt resource value: 0x7f0b0019
public const int Theme_AppCompat_DayNight_NoActionBar = 2131427353;
// aapt resource value: 0x7f0b0113
public const int Theme_AppCompat_Dialog = 2131427603;
// aapt resource value: 0x7f0b0114
public const int Theme_AppCompat_Dialog_Alert = 2131427604;
// aapt resource value: 0x7f0b0115
public const int Theme_AppCompat_Dialog_MinWidth = 2131427605;
// aapt resource value: 0x7f0b0116
public const int Theme_AppCompat_DialogWhenLarge = 2131427606;
// aapt resource value: 0x7f0b0117
public const int Theme_AppCompat_Light = 2131427607;
// aapt resource value: 0x7f0b0118
public const int Theme_AppCompat_Light_DarkActionBar = 2131427608;
// aapt resource value: 0x7f0b0119
public const int Theme_AppCompat_Light_Dialog = 2131427609;
// aapt resource value: 0x7f0b011a
public const int Theme_AppCompat_Light_Dialog_Alert = 2131427610;
// aapt resource value: 0x7f0b011b
public const int Theme_AppCompat_Light_Dialog_MinWidth = 2131427611;
// aapt resource value: 0x7f0b011c
public const int Theme_AppCompat_Light_DialogWhenLarge = 2131427612;
// aapt resource value: 0x7f0b011d
public const int Theme_AppCompat_Light_NoActionBar = 2131427613;
// aapt resource value: 0x7f0b011e
public const int Theme_AppCompat_NoActionBar = 2131427614;
// aapt resource value: 0x7f0b017a
public const int Theme_Design = 2131427706;
// aapt resource value: 0x7f0b017b
public const int Theme_Design_BottomSheetDialog = 2131427707;
// aapt resource value: 0x7f0b017c
public const int Theme_Design_Light = 2131427708;
// aapt resource value: 0x7f0b017d
public const int Theme_Design_Light_BottomSheetDialog = 2131427709;
// aapt resource value: 0x7f0b017e
public const int Theme_Design_Light_NoActionBar = 2131427710;
// aapt resource value: 0x7f0b017f
public const int Theme_Design_NoActionBar = 2131427711;
// aapt resource value: 0x7f0b0003
public const int Theme_MediaRouter = 2131427331;
// aapt resource value: 0x7f0b0004
public const int Theme_MediaRouter_Light = 2131427332;
// aapt resource value: 0x7f0b0005
public const int Theme_MediaRouter_Light_DarkControlPanel = 2131427333;
// aapt resource value: 0x7f0b0006
public const int Theme_MediaRouter_LightControlPanel = 2131427334;
// aapt resource value: 0x7f0b011f
public const int ThemeOverlay_AppCompat = 2131427615;
// aapt resource value: 0x7f0b0120
public const int ThemeOverlay_AppCompat_ActionBar = 2131427616;
// aapt resource value: 0x7f0b0121
public const int ThemeOverlay_AppCompat_Dark = 2131427617;
// aapt resource value: 0x7f0b0122
public const int ThemeOverlay_AppCompat_Dark_ActionBar = 2131427618;
// aapt resource value: 0x7f0b0123
public const int ThemeOverlay_AppCompat_Dialog = 2131427619;
// aapt resource value: 0x7f0b0124
public const int ThemeOverlay_AppCompat_Dialog_Alert = 2131427620;
// aapt resource value: 0x7f0b0125
public const int ThemeOverlay_AppCompat_Light = 2131427621;
// aapt resource value: 0x7f0b0007
public const int ThemeOverlay_MediaRouter_Dark = 2131427335;
// aapt resource value: 0x7f0b0008
public const int ThemeOverlay_MediaRouter_Light = 2131427336;
// aapt resource value: 0x7f0b0126
public const int Widget_AppCompat_ActionBar = 2131427622;
// aapt resource value: 0x7f0b0127
public const int Widget_AppCompat_ActionBar_Solid = 2131427623;
// aapt resource value: 0x7f0b0128
public const int Widget_AppCompat_ActionBar_TabBar = 2131427624;
// aapt resource value: 0x7f0b0129
public const int Widget_AppCompat_ActionBar_TabText = 2131427625;
// aapt resource value: 0x7f0b012a
public const int Widget_AppCompat_ActionBar_TabView = 2131427626;
// aapt resource value: 0x7f0b012b
public const int Widget_AppCompat_ActionButton = 2131427627;
// aapt resource value: 0x7f0b012c
public const int Widget_AppCompat_ActionButton_CloseMode = 2131427628;
// aapt resource value: 0x7f0b012d
public const int Widget_AppCompat_ActionButton_Overflow = 2131427629;
// aapt resource value: 0x7f0b012e
public const int Widget_AppCompat_ActionMode = 2131427630;
// aapt resource value: 0x7f0b012f
public const int Widget_AppCompat_ActivityChooserView = 2131427631;
// aapt resource value: 0x7f0b0130
public const int Widget_AppCompat_AutoCompleteTextView = 2131427632;
// aapt resource value: 0x7f0b0131
public const int Widget_AppCompat_Button = 2131427633;
// aapt resource value: 0x7f0b0132
public const int Widget_AppCompat_Button_Borderless = 2131427634;
// aapt resource value: 0x7f0b0133
public const int Widget_AppCompat_Button_Borderless_Colored = 2131427635;
// aapt resource value: 0x7f0b0134
public const int Widget_AppCompat_Button_ButtonBar_AlertDialog = 2131427636;
// aapt resource value: 0x7f0b0135
public const int Widget_AppCompat_Button_Colored = 2131427637;
// aapt resource value: 0x7f0b0136
public const int Widget_AppCompat_Button_Small = 2131427638;
// aapt resource value: 0x7f0b0137
public const int Widget_AppCompat_ButtonBar = 2131427639;
// aapt resource value: 0x7f0b0138
public const int Widget_AppCompat_ButtonBar_AlertDialog = 2131427640;
// aapt resource value: 0x7f0b0139
public const int Widget_AppCompat_CompoundButton_CheckBox = 2131427641;
// aapt resource value: 0x7f0b013a
public const int Widget_AppCompat_CompoundButton_RadioButton = 2131427642;
// aapt resource value: 0x7f0b013b
public const int Widget_AppCompat_CompoundButton_Switch = 2131427643;
// aapt resource value: 0x7f0b013c
public const int Widget_AppCompat_DrawerArrowToggle = 2131427644;
// aapt resource value: 0x7f0b013d
public const int Widget_AppCompat_DropDownItem_Spinner = 2131427645;
// aapt resource value: 0x7f0b013e
public const int Widget_AppCompat_EditText = 2131427646;
// aapt resource value: 0x7f0b013f
public const int Widget_AppCompat_ImageButton = 2131427647;
// aapt resource value: 0x7f0b0140
public const int Widget_AppCompat_Light_ActionBar = 2131427648;
// aapt resource value: 0x7f0b0141
public const int Widget_AppCompat_Light_ActionBar_Solid = 2131427649;
// aapt resource value: 0x7f0b0142
public const int Widget_AppCompat_Light_ActionBar_Solid_Inverse = 2131427650;
// aapt resource value: 0x7f0b0143
public const int Widget_AppCompat_Light_ActionBar_TabBar = 2131427651;
// aapt resource value: 0x7f0b0144
public const int Widget_AppCompat_Light_ActionBar_TabBar_Inverse = 2131427652;
// aapt resource value: 0x7f0b0145
public const int Widget_AppCompat_Light_ActionBar_TabText = 2131427653;
// aapt resource value: 0x7f0b0146
public const int Widget_AppCompat_Light_ActionBar_TabText_Inverse = 2131427654;
// aapt resource value: 0x7f0b0147
public const int Widget_AppCompat_Light_ActionBar_TabView = 2131427655;
// aapt resource value: 0x7f0b0148
public const int Widget_AppCompat_Light_ActionBar_TabView_Inverse = 2131427656;
// aapt resource value: 0x7f0b0149
public const int Widget_AppCompat_Light_ActionButton = 2131427657;
// aapt resource value: 0x7f0b014a
public const int Widget_AppCompat_Light_ActionButton_CloseMode = 2131427658;
// aapt resource value: 0x7f0b014b
public const int Widget_AppCompat_Light_ActionButton_Overflow = 2131427659;
// aapt resource value: 0x7f0b014c
public const int Widget_AppCompat_Light_ActionMode_Inverse = 2131427660;
// aapt resource value: 0x7f0b014d
public const int Widget_AppCompat_Light_ActivityChooserView = 2131427661;
// aapt resource value: 0x7f0b014e
public const int Widget_AppCompat_Light_AutoCompleteTextView = 2131427662;
// aapt resource value: 0x7f0b014f
public const int Widget_AppCompat_Light_DropDownItem_Spinner = 2131427663;
// aapt resource value: 0x7f0b0150
public const int Widget_AppCompat_Light_ListPopupWindow = 2131427664;
// aapt resource value: 0x7f0b0151
public const int Widget_AppCompat_Light_ListView_DropDown = 2131427665;
// aapt resource value: 0x7f0b0152
public const int Widget_AppCompat_Light_PopupMenu = 2131427666;
// aapt resource value: 0x7f0b0153
public const int Widget_AppCompat_Light_PopupMenu_Overflow = 2131427667;
// aapt resource value: 0x7f0b0154
public const int Widget_AppCompat_Light_SearchView = 2131427668;
// aapt resource value: 0x7f0b0155
public const int Widget_AppCompat_Light_Spinner_DropDown_ActionBar = 2131427669;
// aapt resource value: 0x7f0b0156
public const int Widget_AppCompat_ListMenuView = 2131427670;
// aapt resource value: 0x7f0b0157
public const int Widget_AppCompat_ListPopupWindow = 2131427671;
// aapt resource value: 0x7f0b0158
public const int Widget_AppCompat_ListView = 2131427672;
// aapt resource value: 0x7f0b0159
public const int Widget_AppCompat_ListView_DropDown = 2131427673;
// aapt resource value: 0x7f0b015a
public const int Widget_AppCompat_ListView_Menu = 2131427674;
// aapt resource value: 0x7f0b009f
public const int Widget_AppCompat_NotificationActionContainer = 2131427487;
// aapt resource value: 0x7f0b00a0
public const int Widget_AppCompat_NotificationActionText = 2131427488;
// aapt resource value: 0x7f0b015b
public const int Widget_AppCompat_PopupMenu = 2131427675;
// aapt resource value: 0x7f0b015c
public const int Widget_AppCompat_PopupMenu_Overflow = 2131427676;
// aapt resource value: 0x7f0b015d
public const int Widget_AppCompat_PopupWindow = 2131427677;
// aapt resource value: 0x7f0b015e
public const int Widget_AppCompat_ProgressBar = 2131427678;
// aapt resource value: 0x7f0b015f
public const int Widget_AppCompat_ProgressBar_Horizontal = 2131427679;
// aapt resource value: 0x7f0b0160
public const int Widget_AppCompat_RatingBar = 2131427680;
// aapt resource value: 0x7f0b0161
public const int Widget_AppCompat_RatingBar_Indicator = 2131427681;
// aapt resource value: 0x7f0b0162
public const int Widget_AppCompat_RatingBar_Small = 2131427682;
// aapt resource value: 0x7f0b0163
public const int Widget_AppCompat_SearchView = 2131427683;
// aapt resource value: 0x7f0b0164
public const int Widget_AppCompat_SearchView_ActionBar = 2131427684;
// aapt resource value: 0x7f0b0165
public const int Widget_AppCompat_SeekBar = 2131427685;
// aapt resource value: 0x7f0b0166
public const int Widget_AppCompat_SeekBar_Discrete = 2131427686;
// aapt resource value: 0x7f0b0167
public const int Widget_AppCompat_Spinner = 2131427687;
// aapt resource value: 0x7f0b0168
public const int Widget_AppCompat_Spinner_DropDown = 2131427688;
// aapt resource value: 0x7f0b0169
public const int Widget_AppCompat_Spinner_DropDown_ActionBar = 2131427689;
// aapt resource value: 0x7f0b016a
public const int Widget_AppCompat_Spinner_Underlined = 2131427690;
// aapt resource value: 0x7f0b016b
public const int Widget_AppCompat_TextView_SpinnerItem = 2131427691;
// aapt resource value: 0x7f0b016c
public const int Widget_AppCompat_Toolbar = 2131427692;
// aapt resource value: 0x7f0b016d
public const int Widget_AppCompat_Toolbar_Button_Navigation = 2131427693;
// aapt resource value: 0x7f0b016f
public const int Widget_Design_AppBarLayout = 2131427695;
// aapt resource value: 0x7f0b0180
public const int Widget_Design_BottomNavigationView = 2131427712;
// aapt resource value: 0x7f0b0181
public const int Widget_Design_BottomSheet_Modal = 2131427713;
// aapt resource value: 0x7f0b0182
public const int Widget_Design_CollapsingToolbar = 2131427714;
// aapt resource value: 0x7f0b0183
public const int Widget_Design_CoordinatorLayout = 2131427715;
// aapt resource value: 0x7f0b0184
public const int Widget_Design_FloatingActionButton = 2131427716;
// aapt resource value: 0x7f0b0185
public const int Widget_Design_NavigationView = 2131427717;
// aapt resource value: 0x7f0b0186
public const int Widget_Design_ScrimInsetsFrameLayout = 2131427718;
// aapt resource value: 0x7f0b0187
public const int Widget_Design_Snackbar = 2131427719;
// aapt resource value: 0x7f0b016e
public const int Widget_Design_TabLayout = 2131427694;
// aapt resource value: 0x7f0b0188
public const int Widget_Design_TextInputLayout = 2131427720;
// aapt resource value: 0x7f0b0009
public const int Widget_MediaRouter_Light_MediaRouteButton = 2131427337;
// aapt resource value: 0x7f0b000a
public const int Widget_MediaRouter_MediaRouteButton = 2131427338;
static Style()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Style()
{
}
}
public partial class Styleable
{
public static int[] ActionBar = new int[] {
2130771997,
2130771999,
2130772000,
2130772001,
2130772002,
2130772003,
2130772004,
2130772005,
2130772006,
2130772007,
2130772008,
2130772009,
2130772010,
2130772011,
2130772012,
2130772013,
2130772014,
2130772015,
2130772016,
2130772017,
2130772018,
2130772019,
2130772020,
2130772021,
2130772022,
2130772023,
2130772024,
2130772025,
2130772089};
// aapt resource value: 10
public const int ActionBar_background = 10;
// aapt resource value: 12
public const int ActionBar_backgroundSplit = 12;
// aapt resource value: 11
public const int ActionBar_backgroundStacked = 11;
// aapt resource value: 21
public const int ActionBar_contentInsetEnd = 21;
// aapt resource value: 25
public const int ActionBar_contentInsetEndWithActions = 25;
// aapt resource value: 22
public const int ActionBar_contentInsetLeft = 22;
// aapt resource value: 23
public const int ActionBar_contentInsetRight = 23;
// aapt resource value: 20
public const int ActionBar_contentInsetStart = 20;
// aapt resource value: 24
public const int ActionBar_contentInsetStartWithNavigation = 24;
// aapt resource value: 13
public const int ActionBar_customNavigationLayout = 13;
// aapt resource value: 3
public const int ActionBar_displayOptions = 3;
// aapt resource value: 9
public const int ActionBar_divider = 9;
// aapt resource value: 26
public const int ActionBar_elevation = 26;
// aapt resource value: 0
public const int ActionBar_height = 0;
// aapt resource value: 19
public const int ActionBar_hideOnContentScroll = 19;
// aapt resource value: 28
public const int ActionBar_homeAsUpIndicator = 28;
// aapt resource value: 14
public const int ActionBar_homeLayout = 14;
// aapt resource value: 7
public const int ActionBar_icon = 7;
// aapt resource value: 16
public const int ActionBar_indeterminateProgressStyle = 16;
// aapt resource value: 18
public const int ActionBar_itemPadding = 18;
// aapt resource value: 8
public const int ActionBar_logo = 8;
// aapt resource value: 2
public const int ActionBar_navigationMode = 2;
// aapt resource value: 27
public const int ActionBar_popupTheme = 27;
// aapt resource value: 17
public const int ActionBar_progressBarPadding = 17;
// aapt resource value: 15
public const int ActionBar_progressBarStyle = 15;
// aapt resource value: 4
public const int ActionBar_subtitle = 4;
// aapt resource value: 6
public const int ActionBar_subtitleTextStyle = 6;
// aapt resource value: 1
public const int ActionBar_title = 1;
// aapt resource value: 5
public const int ActionBar_titleTextStyle = 5;
public static int[] ActionBarLayout = new int[] {
16842931};
// aapt resource value: 0
public const int ActionBarLayout_android_layout_gravity = 0;
public static int[] ActionMenuItemView = new int[] {
16843071};
// aapt resource value: 0
public const int ActionMenuItemView_android_minWidth = 0;
public static int[] ActionMenuView;
public static int[] ActionMode = new int[] {
2130771997,
2130772003,
2130772004,
2130772008,
2130772010,
2130772026};
// aapt resource value: 3
public const int ActionMode_background = 3;
// aapt resource value: 4
public const int ActionMode_backgroundSplit = 4;
// aapt resource value: 5
public const int ActionMode_closeItemLayout = 5;
// aapt resource value: 0
public const int ActionMode_height = 0;
// aapt resource value: 2
public const int ActionMode_subtitleTextStyle = 2;
// aapt resource value: 1
public const int ActionMode_titleTextStyle = 1;
public static int[] ActivityChooserView = new int[] {
2130772027,
2130772028};
// aapt resource value: 1
public const int ActivityChooserView_expandActivityOverflowButtonDrawable = 1;
// aapt resource value: 0
public const int ActivityChooserView_initialActivityCount = 0;
public static int[] AlertDialog = new int[] {
16842994,
2130772029,
2130772030,
2130772031,
2130772032,
2130772033,
2130772034};
// aapt resource value: 0
public const int AlertDialog_android_layout = 0;
// aapt resource value: 1
public const int AlertDialog_buttonPanelSideLayout = 1;
// aapt resource value: 5
public const int AlertDialog_listItemLayout = 5;
// aapt resource value: 2
public const int AlertDialog_listLayout = 2;
// aapt resource value: 3
public const int AlertDialog_multiChoiceItemLayout = 3;
// aapt resource value: 6
public const int AlertDialog_showTitle = 6;
// aapt resource value: 4
public const int AlertDialog_singleChoiceItemLayout = 4;
public static int[] AppBarLayout = new int[] {
16842964,
2130772024,
2130772227};
// aapt resource value: 0
public const int AppBarLayout_android_background = 0;
// aapt resource value: 1
public const int AppBarLayout_elevation = 1;
// aapt resource value: 2
public const int AppBarLayout_expanded = 2;
public static int[] AppBarLayoutStates = new int[] {
2130772228,
2130772229};
// aapt resource value: 0
public const int AppBarLayoutStates_state_collapsed = 0;
// aapt resource value: 1
public const int AppBarLayoutStates_state_collapsible = 1;
public static int[] AppBarLayout_Layout = new int[] {
2130772230,
2130772231};
// aapt resource value: 0
public const int AppBarLayout_Layout_layout_scrollFlags = 0;
// aapt resource value: 1
public const int AppBarLayout_Layout_layout_scrollInterpolator = 1;
public static int[] AppCompatImageView = new int[] {
16843033,
2130772035,
2130772036,
2130772037};
// aapt resource value: 0
public const int AppCompatImageView_android_src = 0;
// aapt resource value: 1
public const int AppCompatImageView_srcCompat = 1;
// aapt resource value: 2
public const int AppCompatImageView_tint = 2;
// aapt resource value: 3
public const int AppCompatImageView_tintMode = 3;
public static int[] AppCompatSeekBar = new int[] {
16843074,
2130772038,
2130772039,
2130772040};
// aapt resource value: 0
public const int AppCompatSeekBar_android_thumb = 0;
// aapt resource value: 1
public const int AppCompatSeekBar_tickMark = 1;
// aapt resource value: 2
public const int AppCompatSeekBar_tickMarkTint = 2;
// aapt resource value: 3
public const int AppCompatSeekBar_tickMarkTintMode = 3;
public static int[] AppCompatTextHelper = new int[] {
16842804,
16843117,
16843118,
16843119,
16843120,
16843666,
16843667};
// aapt resource value: 2
public const int AppCompatTextHelper_android_drawableBottom = 2;
// aapt resource value: 6
public const int AppCompatTextHelper_android_drawableEnd = 6;
// aapt resource value: 3
public const int AppCompatTextHelper_android_drawableLeft = 3;
// aapt resource value: 4
public const int AppCompatTextHelper_android_drawableRight = 4;
// aapt resource value: 5
public const int AppCompatTextHelper_android_drawableStart = 5;
// aapt resource value: 1
public const int AppCompatTextHelper_android_drawableTop = 1;
// aapt resource value: 0
public const int AppCompatTextHelper_android_textAppearance = 0;
public static int[] AppCompatTextView = new int[] {
16842804,
2130772041};
// aapt resource value: 0
public const int AppCompatTextView_android_textAppearance = 0;
// aapt resource value: 1
public const int AppCompatTextView_textAllCaps = 1;
public static int[] AppCompatTheme = new int[] {
16842839,
16842926,
2130772042,
2130772043,
2130772044,
2130772045,
2130772046,
2130772047,
2130772048,
2130772049,
2130772050,
2130772051,
2130772052,
2130772053,
2130772054,
2130772055,
2130772056,
2130772057,
2130772058,
2130772059,
2130772060,
2130772061,
2130772062,
2130772063,
2130772064,
2130772065,
2130772066,
2130772067,
2130772068,
2130772069,
2130772070,
2130772071,
2130772072,
2130772073,
2130772074,
2130772075,
2130772076,
2130772077,
2130772078,
2130772079,
2130772080,
2130772081,
2130772082,
2130772083,
2130772084,
2130772085,
2130772086,
2130772087,
2130772088,
2130772089,
2130772090,
2130772091,
2130772092,
2130772093,
2130772094,
2130772095,
2130772096,
2130772097,
2130772098,
2130772099,
2130772100,
2130772101,
2130772102,
2130772103,
2130772104,
2130772105,
2130772106,
2130772107,
2130772108,
2130772109,
2130772110,
2130772111,
2130772112,
2130772113,
2130772114,
2130772115,
2130772116,
2130772117,
2130772118,
2130772119,
2130772120,
2130772121,
2130772122,
2130772123,
2130772124,
2130772125,
2130772126,
2130772127,
2130772128,
2130772129,
2130772130,
2130772131,
2130772132,
2130772133,
2130772134,
2130772135,
2130772136,
2130772137,
2130772138,
2130772139,
2130772140,
2130772141,
2130772142,
2130772143,
2130772144,
2130772145,
2130772146,
2130772147,
2130772148,
2130772149,
2130772150,
2130772151,
2130772152,
2130772153,
2130772154,
2130772155};
// aapt resource value: 23
public const int AppCompatTheme_actionBarDivider = 23;
// aapt resource value: 24
public const int AppCompatTheme_actionBarItemBackground = 24;
// aapt resource value: 17
public const int AppCompatTheme_actionBarPopupTheme = 17;
// aapt resource value: 22
public const int AppCompatTheme_actionBarSize = 22;
// aapt resource value: 19
public const int AppCompatTheme_actionBarSplitStyle = 19;
// aapt resource value: 18
public const int AppCompatTheme_actionBarStyle = 18;
// aapt resource value: 13
public const int AppCompatTheme_actionBarTabBarStyle = 13;
// aapt resource value: 12
public const int AppCompatTheme_actionBarTabStyle = 12;
// aapt resource value: 14
public const int AppCompatTheme_actionBarTabTextStyle = 14;
// aapt resource value: 20
public const int AppCompatTheme_actionBarTheme = 20;
// aapt resource value: 21
public const int AppCompatTheme_actionBarWidgetTheme = 21;
// aapt resource value: 50
public const int AppCompatTheme_actionButtonStyle = 50;
// aapt resource value: 46
public const int AppCompatTheme_actionDropDownStyle = 46;
// aapt resource value: 25
public const int AppCompatTheme_actionMenuTextAppearance = 25;
// aapt resource value: 26
public const int AppCompatTheme_actionMenuTextColor = 26;
// aapt resource value: 29
public const int AppCompatTheme_actionModeBackground = 29;
// aapt resource value: 28
public const int AppCompatTheme_actionModeCloseButtonStyle = 28;
// aapt resource value: 31
public const int AppCompatTheme_actionModeCloseDrawable = 31;
// aapt resource value: 33
public const int AppCompatTheme_actionModeCopyDrawable = 33;
// aapt resource value: 32
public const int AppCompatTheme_actionModeCutDrawable = 32;
// aapt resource value: 37
public const int AppCompatTheme_actionModeFindDrawable = 37;
// aapt resource value: 34
public const int AppCompatTheme_actionModePasteDrawable = 34;
// aapt resource value: 39
public const int AppCompatTheme_actionModePopupWindowStyle = 39;
// aapt resource value: 35
public const int AppCompatTheme_actionModeSelectAllDrawable = 35;
// aapt resource value: 36
public const int AppCompatTheme_actionModeShareDrawable = 36;
// aapt resource value: 30
public const int AppCompatTheme_actionModeSplitBackground = 30;
// aapt resource value: 27
public const int AppCompatTheme_actionModeStyle = 27;
// aapt resource value: 38
public const int AppCompatTheme_actionModeWebSearchDrawable = 38;
// aapt resource value: 15
public const int AppCompatTheme_actionOverflowButtonStyle = 15;
// aapt resource value: 16
public const int AppCompatTheme_actionOverflowMenuStyle = 16;
// aapt resource value: 58
public const int AppCompatTheme_activityChooserViewStyle = 58;
// aapt resource value: 95
public const int AppCompatTheme_alertDialogButtonGroupStyle = 95;
// aapt resource value: 96
public const int AppCompatTheme_alertDialogCenterButtons = 96;
// aapt resource value: 94
public const int AppCompatTheme_alertDialogStyle = 94;
// aapt resource value: 97
public const int AppCompatTheme_alertDialogTheme = 97;
// aapt resource value: 1
public const int AppCompatTheme_android_windowAnimationStyle = 1;
// aapt resource value: 0
public const int AppCompatTheme_android_windowIsFloating = 0;
// aapt resource value: 102
public const int AppCompatTheme_autoCompleteTextViewStyle = 102;
// aapt resource value: 55
public const int AppCompatTheme_borderlessButtonStyle = 55;
// aapt resource value: 52
public const int AppCompatTheme_buttonBarButtonStyle = 52;
// aapt resource value: 100
public const int AppCompatTheme_buttonBarNegativeButtonStyle = 100;
// aapt resource value: 101
public const int AppCompatTheme_buttonBarNeutralButtonStyle = 101;
// aapt resource value: 99
public const int AppCompatTheme_buttonBarPositiveButtonStyle = 99;
// aapt resource value: 51
public const int AppCompatTheme_buttonBarStyle = 51;
// aapt resource value: 103
public const int AppCompatTheme_buttonStyle = 103;
// aapt resource value: 104
public const int AppCompatTheme_buttonStyleSmall = 104;
// aapt resource value: 105
public const int AppCompatTheme_checkboxStyle = 105;
// aapt resource value: 106
public const int AppCompatTheme_checkedTextViewStyle = 106;
// aapt resource value: 86
public const int AppCompatTheme_colorAccent = 86;
// aapt resource value: 93
public const int AppCompatTheme_colorBackgroundFloating = 93;
// aapt resource value: 90
public const int AppCompatTheme_colorButtonNormal = 90;
// aapt resource value: 88
public const int AppCompatTheme_colorControlActivated = 88;
// aapt resource value: 89
public const int AppCompatTheme_colorControlHighlight = 89;
// aapt resource value: 87
public const int AppCompatTheme_colorControlNormal = 87;
// aapt resource value: 84
public const int AppCompatTheme_colorPrimary = 84;
// aapt resource value: 85
public const int AppCompatTheme_colorPrimaryDark = 85;
// aapt resource value: 91
public const int AppCompatTheme_colorSwitchThumbNormal = 91;
// aapt resource value: 92
public const int AppCompatTheme_controlBackground = 92;
// aapt resource value: 44
public const int AppCompatTheme_dialogPreferredPadding = 44;
// aapt resource value: 43
public const int AppCompatTheme_dialogTheme = 43;
// aapt resource value: 57
public const int AppCompatTheme_dividerHorizontal = 57;
// aapt resource value: 56
public const int AppCompatTheme_dividerVertical = 56;
// aapt resource value: 75
public const int AppCompatTheme_dropDownListViewStyle = 75;
// aapt resource value: 47
public const int AppCompatTheme_dropdownListPreferredItemHeight = 47;
// aapt resource value: 64
public const int AppCompatTheme_editTextBackground = 64;
// aapt resource value: 63
public const int AppCompatTheme_editTextColor = 63;
// aapt resource value: 107
public const int AppCompatTheme_editTextStyle = 107;
// aapt resource value: 49
public const int AppCompatTheme_homeAsUpIndicator = 49;
// aapt resource value: 65
public const int AppCompatTheme_imageButtonStyle = 65;
// aapt resource value: 83
public const int AppCompatTheme_listChoiceBackgroundIndicator = 83;
// aapt resource value: 45
public const int AppCompatTheme_listDividerAlertDialog = 45;
// aapt resource value: 115
public const int AppCompatTheme_listMenuViewStyle = 115;
// aapt resource value: 76
public const int AppCompatTheme_listPopupWindowStyle = 76;
// aapt resource value: 70
public const int AppCompatTheme_listPreferredItemHeight = 70;
// aapt resource value: 72
public const int AppCompatTheme_listPreferredItemHeightLarge = 72;
// aapt resource value: 71
public const int AppCompatTheme_listPreferredItemHeightSmall = 71;
// aapt resource value: 73
public const int AppCompatTheme_listPreferredItemPaddingLeft = 73;
// aapt resource value: 74
public const int AppCompatTheme_listPreferredItemPaddingRight = 74;
// aapt resource value: 80
public const int AppCompatTheme_panelBackground = 80;
// aapt resource value: 82
public const int AppCompatTheme_panelMenuListTheme = 82;
// aapt resource value: 81
public const int AppCompatTheme_panelMenuListWidth = 81;
// aapt resource value: 61
public const int AppCompatTheme_popupMenuStyle = 61;
// aapt resource value: 62
public const int AppCompatTheme_popupWindowStyle = 62;
// aapt resource value: 108
public const int AppCompatTheme_radioButtonStyle = 108;
// aapt resource value: 109
public const int AppCompatTheme_ratingBarStyle = 109;
// aapt resource value: 110
public const int AppCompatTheme_ratingBarStyleIndicator = 110;
// aapt resource value: 111
public const int AppCompatTheme_ratingBarStyleSmall = 111;
// aapt resource value: 69
public const int AppCompatTheme_searchViewStyle = 69;
// aapt resource value: 112
public const int AppCompatTheme_seekBarStyle = 112;
// aapt resource value: 53
public const int AppCompatTheme_selectableItemBackground = 53;
// aapt resource value: 54
public const int AppCompatTheme_selectableItemBackgroundBorderless = 54;
// aapt resource value: 48
public const int AppCompatTheme_spinnerDropDownItemStyle = 48;
// aapt resource value: 113
public const int AppCompatTheme_spinnerStyle = 113;
// aapt resource value: 114
public const int AppCompatTheme_switchStyle = 114;
// aapt resource value: 40
public const int AppCompatTheme_textAppearanceLargePopupMenu = 40;
// aapt resource value: 77
public const int AppCompatTheme_textAppearanceListItem = 77;
// aapt resource value: 78
public const int AppCompatTheme_textAppearanceListItemSecondary = 78;
// aapt resource value: 79
public const int AppCompatTheme_textAppearanceListItemSmall = 79;
// aapt resource value: 42
public const int AppCompatTheme_textAppearancePopupMenuHeader = 42;
// aapt resource value: 67
public const int AppCompatTheme_textAppearanceSearchResultSubtitle = 67;
// aapt resource value: 66
public const int AppCompatTheme_textAppearanceSearchResultTitle = 66;
// aapt resource value: 41
public const int AppCompatTheme_textAppearanceSmallPopupMenu = 41;
// aapt resource value: 98
public const int AppCompatTheme_textColorAlertDialogListItem = 98;
// aapt resource value: 68
public const int AppCompatTheme_textColorSearchUrl = 68;
// aapt resource value: 60
public const int AppCompatTheme_toolbarNavigationButtonStyle = 60;
// aapt resource value: 59
public const int AppCompatTheme_toolbarStyle = 59;
// aapt resource value: 2
public const int AppCompatTheme_windowActionBar = 2;
// aapt resource value: 4
public const int AppCompatTheme_windowActionBarOverlay = 4;
// aapt resource value: 5
public const int AppCompatTheme_windowActionModeOverlay = 5;
// aapt resource value: 9
public const int AppCompatTheme_windowFixedHeightMajor = 9;
// aapt resource value: 7
public const int AppCompatTheme_windowFixedHeightMinor = 7;
// aapt resource value: 6
public const int AppCompatTheme_windowFixedWidthMajor = 6;
// aapt resource value: 8
public const int AppCompatTheme_windowFixedWidthMinor = 8;
// aapt resource value: 10
public const int AppCompatTheme_windowMinWidthMajor = 10;
// aapt resource value: 11
public const int AppCompatTheme_windowMinWidthMinor = 11;
// aapt resource value: 3
public const int AppCompatTheme_windowNoTitle = 3;
public static int[] BottomNavigationView = new int[] {
2130772024,
2130772270,
2130772271,
2130772272,
2130772273};
// aapt resource value: 0
public const int BottomNavigationView_elevation = 0;
// aapt resource value: 4
public const int BottomNavigationView_itemBackground = 4;
// aapt resource value: 2
public const int BottomNavigationView_itemIconTint = 2;
// aapt resource value: 3
public const int BottomNavigationView_itemTextColor = 3;
// aapt resource value: 1
public const int BottomNavigationView_menu = 1;
public static int[] BottomSheetBehavior_Layout = new int[] {
2130772232,
2130772233,
2130772234};
// aapt resource value: 1
public const int BottomSheetBehavior_Layout_behavior_hideable = 1;
// aapt resource value: 0
public const int BottomSheetBehavior_Layout_behavior_peekHeight = 0;
// aapt resource value: 2
public const int BottomSheetBehavior_Layout_behavior_skipCollapsed = 2;
public static int[] ButtonBarLayout = new int[] {
2130772156};
// aapt resource value: 0
public const int ButtonBarLayout_allowStacking = 0;
public static int[] CardView = new int[] {
16843071,
16843072,
2130771985,
2130771986,
2130771987,
2130771988,
2130771989,
2130771990,
2130771991,
2130771992,
2130771993,
2130771994,
2130771995};
// aapt resource value: 1
public const int CardView_android_minHeight = 1;
// aapt resource value: 0
public const int CardView_android_minWidth = 0;
// aapt resource value: 2
public const int CardView_cardBackgroundColor = 2;
// aapt resource value: 3
public const int CardView_cardCornerRadius = 3;
// aapt resource value: 4
public const int CardView_cardElevation = 4;
// aapt resource value: 5
public const int CardView_cardMaxElevation = 5;
// aapt resource value: 7
public const int CardView_cardPreventCornerOverlap = 7;
// aapt resource value: 6
public const int CardView_cardUseCompatPadding = 6;
// aapt resource value: 8
public const int CardView_contentPadding = 8;
// aapt resource value: 12
public const int CardView_contentPaddingBottom = 12;
// aapt resource value: 9
public const int CardView_contentPaddingLeft = 9;
// aapt resource value: 10
public const int CardView_contentPaddingRight = 10;
// aapt resource value: 11
public const int CardView_contentPaddingTop = 11;
public static int[] CollapsingToolbarLayout = new int[] {
2130771999,
2130772235,
2130772236,
2130772237,
2130772238,
2130772239,
2130772240,
2130772241,
2130772242,
2130772243,
2130772244,
2130772245,
2130772246,
2130772247,
2130772248,
2130772249};
// aapt resource value: 13
public const int CollapsingToolbarLayout_collapsedTitleGravity = 13;
// aapt resource value: 7
public const int CollapsingToolbarLayout_collapsedTitleTextAppearance = 7;
// aapt resource value: 8
public const int CollapsingToolbarLayout_contentScrim = 8;
// aapt resource value: 14
public const int CollapsingToolbarLayout_expandedTitleGravity = 14;
// aapt resource value: 1
public const int CollapsingToolbarLayout_expandedTitleMargin = 1;
// aapt resource value: 5
public const int CollapsingToolbarLayout_expandedTitleMarginBottom = 5;
// aapt resource value: 4
public const int CollapsingToolbarLayout_expandedTitleMarginEnd = 4;
// aapt resource value: 2
public const int CollapsingToolbarLayout_expandedTitleMarginStart = 2;
// aapt resource value: 3
public const int CollapsingToolbarLayout_expandedTitleMarginTop = 3;
// aapt resource value: 6
public const int CollapsingToolbarLayout_expandedTitleTextAppearance = 6;
// aapt resource value: 12
public const int CollapsingToolbarLayout_scrimAnimationDuration = 12;
// aapt resource value: 11
public const int CollapsingToolbarLayout_scrimVisibleHeightTrigger = 11;
// aapt resource value: 9
public const int CollapsingToolbarLayout_statusBarScrim = 9;
// aapt resource value: 0
public const int CollapsingToolbarLayout_title = 0;
// aapt resource value: 15
public const int CollapsingToolbarLayout_titleEnabled = 15;
// aapt resource value: 10
public const int CollapsingToolbarLayout_toolbarId = 10;
public static int[] CollapsingToolbarLayout_Layout = new int[] {
2130772250,
2130772251};
// aapt resource value: 0
public const int CollapsingToolbarLayout_Layout_layout_collapseMode = 0;
// aapt resource value: 1
public const int CollapsingToolbarLayout_Layout_layout_collapseParallaxMultiplier = 1;
public static int[] ColorStateListItem = new int[] {
16843173,
16843551,
2130772157};
// aapt resource value: 2
public const int ColorStateListItem_alpha = 2;
// aapt resource value: 1
public const int ColorStateListItem_android_alpha = 1;
// aapt resource value: 0
public const int ColorStateListItem_android_color = 0;
public static int[] CompoundButton = new int[] {
16843015,
2130772158,
2130772159};
// aapt resource value: 0
public const int CompoundButton_android_button = 0;
// aapt resource value: 1
public const int CompoundButton_buttonTint = 1;
// aapt resource value: 2
public const int CompoundButton_buttonTintMode = 2;
public static int[] CoordinatorLayout = new int[] {
2130772252,
2130772253};
// aapt resource value: 0
public const int CoordinatorLayout_keylines = 0;
// aapt resource value: 1
public const int CoordinatorLayout_statusBarBackground = 1;
public static int[] CoordinatorLayout_Layout = new int[] {
16842931,
2130772254,
2130772255,
2130772256,
2130772257,
2130772258,
2130772259};
// aapt resource value: 0
public const int CoordinatorLayout_Layout_android_layout_gravity = 0;
// aapt resource value: 2
public const int CoordinatorLayout_Layout_layout_anchor = 2;
// aapt resource value: 4
public const int CoordinatorLayout_Layout_layout_anchorGravity = 4;
// aapt resource value: 1
public const int CoordinatorLayout_Layout_layout_behavior = 1;
// aapt resource value: 6
public const int CoordinatorLayout_Layout_layout_dodgeInsetEdges = 6;
// aapt resource value: 5
public const int CoordinatorLayout_Layout_layout_insetEdge = 5;
// aapt resource value: 3
public const int CoordinatorLayout_Layout_layout_keyline = 3;
public static int[] DesignTheme = new int[] {
2130772260,
2130772261,
2130772262};
// aapt resource value: 0
public const int DesignTheme_bottomSheetDialogTheme = 0;
// aapt resource value: 1
public const int DesignTheme_bottomSheetStyle = 1;
// aapt resource value: 2
public const int DesignTheme_textColorError = 2;
public static int[] DrawerArrowToggle = new int[] {
2130772160,
2130772161,
2130772162,
2130772163,
2130772164,
2130772165,
2130772166,
2130772167};
// aapt resource value: 4
public const int DrawerArrowToggle_arrowHeadLength = 4;
// aapt resource value: 5
public const int DrawerArrowToggle_arrowShaftLength = 5;
// aapt resource value: 6
public const int DrawerArrowToggle_barLength = 6;
// aapt resource value: 0
public const int DrawerArrowToggle_color = 0;
// aapt resource value: 2
public const int DrawerArrowToggle_drawableSize = 2;
// aapt resource value: 3
public const int DrawerArrowToggle_gapBetweenBars = 3;
// aapt resource value: 1
public const int DrawerArrowToggle_spinBars = 1;
// aapt resource value: 7
public const int DrawerArrowToggle_thickness = 7;
public static int[] FloatingActionButton = new int[] {
2130772024,
2130772225,
2130772226,
2130772263,
2130772264,
2130772265,
2130772266,
2130772267};
// aapt resource value: 1
public const int FloatingActionButton_backgroundTint = 1;
// aapt resource value: 2
public const int FloatingActionButton_backgroundTintMode = 2;
// aapt resource value: 6
public const int FloatingActionButton_borderWidth = 6;
// aapt resource value: 0
public const int FloatingActionButton_elevation = 0;
// aapt resource value: 4
public const int FloatingActionButton_fabSize = 4;
// aapt resource value: 5
public const int FloatingActionButton_pressedTranslationZ = 5;
// aapt resource value: 3
public const int FloatingActionButton_rippleColor = 3;
// aapt resource value: 7
public const int FloatingActionButton_useCompatPadding = 7;
public static int[] FloatingActionButton_Behavior_Layout = new int[] {
2130772268};
// aapt resource value: 0
public const int FloatingActionButton_Behavior_Layout_behavior_autoHide = 0;
public static int[] ForegroundLinearLayout = new int[] {
16843017,
16843264,
2130772269};
// aapt resource value: 0
public const int ForegroundLinearLayout_android_foreground = 0;
// aapt resource value: 1
public const int ForegroundLinearLayout_android_foregroundGravity = 1;
// aapt resource value: 2
public const int ForegroundLinearLayout_foregroundInsidePadding = 2;
public static int[] LinearLayoutCompat = new int[] {
16842927,
16842948,
16843046,
16843047,
16843048,
2130772007,
2130772168,
2130772169,
2130772170};
// aapt resource value: 2
public const int LinearLayoutCompat_android_baselineAligned = 2;
// aapt resource value: 3
public const int LinearLayoutCompat_android_baselineAlignedChildIndex = 3;
// aapt resource value: 0
public const int LinearLayoutCompat_android_gravity = 0;
// aapt resource value: 1
public const int LinearLayoutCompat_android_orientation = 1;
// aapt resource value: 4
public const int LinearLayoutCompat_android_weightSum = 4;
// aapt resource value: 5
public const int LinearLayoutCompat_divider = 5;
// aapt resource value: 8
public const int LinearLayoutCompat_dividerPadding = 8;
// aapt resource value: 6
public const int LinearLayoutCompat_measureWithLargestChild = 6;
// aapt resource value: 7
public const int LinearLayoutCompat_showDividers = 7;
public static int[] LinearLayoutCompat_Layout = new int[] {
16842931,
16842996,
16842997,
16843137};
// aapt resource value: 0
public const int LinearLayoutCompat_Layout_android_layout_gravity = 0;
// aapt resource value: 2
public const int LinearLayoutCompat_Layout_android_layout_height = 2;
// aapt resource value: 3
public const int LinearLayoutCompat_Layout_android_layout_weight = 3;
// aapt resource value: 1
public const int LinearLayoutCompat_Layout_android_layout_width = 1;
public static int[] ListPopupWindow = new int[] {
16843436,
16843437};
// aapt resource value: 0
public const int ListPopupWindow_android_dropDownHorizontalOffset = 0;
// aapt resource value: 1
public const int ListPopupWindow_android_dropDownVerticalOffset = 1;
public static int[] MediaRouteButton = new int[] {
16843071,
16843072,
2130771984,
2130772158};
// aapt resource value: 1
public const int MediaRouteButton_android_minHeight = 1;
// aapt resource value: 0
public const int MediaRouteButton_android_minWidth = 0;
// aapt resource value: 3
public const int MediaRouteButton_buttonTint = 3;
// aapt resource value: 2
public const int MediaRouteButton_externalRouteEnabledDrawable = 2;
public static int[] MenuGroup = new int[] {
16842766,
16842960,
16843156,
16843230,
16843231,
16843232};
// aapt resource value: 5
public const int MenuGroup_android_checkableBehavior = 5;
// aapt resource value: 0
public const int MenuGroup_android_enabled = 0;
// aapt resource value: 1
public const int MenuGroup_android_id = 1;
// aapt resource value: 3
public const int MenuGroup_android_menuCategory = 3;
// aapt resource value: 4
public const int MenuGroup_android_orderInCategory = 4;
// aapt resource value: 2
public const int MenuGroup_android_visible = 2;
public static int[] MenuItem = new int[] {
16842754,
16842766,
16842960,
16843014,
16843156,
16843230,
16843231,
16843233,
16843234,
16843235,
16843236,
16843237,
16843375,
2130772171,
2130772172,
2130772173,
2130772174};
// aapt resource value: 14
public const int MenuItem_actionLayout = 14;
// aapt resource value: 16
public const int MenuItem_actionProviderClass = 16;
// aapt resource value: 15
public const int MenuItem_actionViewClass = 15;
// aapt resource value: 9
public const int MenuItem_android_alphabeticShortcut = 9;
// aapt resource value: 11
public const int MenuItem_android_checkable = 11;
// aapt resource value: 3
public const int MenuItem_android_checked = 3;
// aapt resource value: 1
public const int MenuItem_android_enabled = 1;
// aapt resource value: 0
public const int MenuItem_android_icon = 0;
// aapt resource value: 2
public const int MenuItem_android_id = 2;
// aapt resource value: 5
public const int MenuItem_android_menuCategory = 5;
// aapt resource value: 10
public const int MenuItem_android_numericShortcut = 10;
// aapt resource value: 12
public const int MenuItem_android_onClick = 12;
// aapt resource value: 6
public const int MenuItem_android_orderInCategory = 6;
// aapt resource value: 7
public const int MenuItem_android_title = 7;
// aapt resource value: 8
public const int MenuItem_android_titleCondensed = 8;
// aapt resource value: 4
public const int MenuItem_android_visible = 4;
// aapt resource value: 13
public const int MenuItem_showAsAction = 13;
public static int[] MenuView = new int[] {
16842926,
16843052,
16843053,
16843054,
16843055,
16843056,
16843057,
2130772175,
2130772176};
// aapt resource value: 4
public const int MenuView_android_headerBackground = 4;
// aapt resource value: 2
public const int MenuView_android_horizontalDivider = 2;
// aapt resource value: 5
public const int MenuView_android_itemBackground = 5;
// aapt resource value: 6
public const int MenuView_android_itemIconDisabledAlpha = 6;
// aapt resource value: 1
public const int MenuView_android_itemTextAppearance = 1;
// aapt resource value: 3
public const int MenuView_android_verticalDivider = 3;
// aapt resource value: 0
public const int MenuView_android_windowAnimationStyle = 0;
// aapt resource value: 7
public const int MenuView_preserveIconSpacing = 7;
// aapt resource value: 8
public const int MenuView_subMenuArrow = 8;
public static int[] NavigationView = new int[] {
16842964,
16842973,
16843039,
2130772024,
2130772270,
2130772271,
2130772272,
2130772273,
2130772274,
2130772275};
// aapt resource value: 0
public const int NavigationView_android_background = 0;
// aapt resource value: 1
public const int NavigationView_android_fitsSystemWindows = 1;
// aapt resource value: 2
public const int NavigationView_android_maxWidth = 2;
// aapt resource value: 3
public const int NavigationView_elevation = 3;
// aapt resource value: 9
public const int NavigationView_headerLayout = 9;
// aapt resource value: 7
public const int NavigationView_itemBackground = 7;
// aapt resource value: 5
public const int NavigationView_itemIconTint = 5;
// aapt resource value: 8
public const int NavigationView_itemTextAppearance = 8;
// aapt resource value: 6
public const int NavigationView_itemTextColor = 6;
// aapt resource value: 4
public const int NavigationView_menu = 4;
public static int[] PopupWindow = new int[] {
16843126,
16843465,
2130772177};
// aapt resource value: 1
public const int PopupWindow_android_popupAnimationStyle = 1;
// aapt resource value: 0
public const int PopupWindow_android_popupBackground = 0;
// aapt resource value: 2
public const int PopupWindow_overlapAnchor = 2;
public static int[] PopupWindowBackgroundState = new int[] {
2130772178};
// aapt resource value: 0
public const int PopupWindowBackgroundState_state_above_anchor = 0;
public static int[] RecycleListView = new int[] {
2130772179,
2130772180};
// aapt resource value: 0
public const int RecycleListView_paddingBottomNoButtons = 0;
// aapt resource value: 1
public const int RecycleListView_paddingTopNoTitle = 1;
public static int[] RecyclerView = new int[] {
16842948,
16842993,
2130771968,
2130771969,
2130771970,
2130771971};
// aapt resource value: 1
public const int RecyclerView_android_descendantFocusability = 1;
// aapt resource value: 0
public const int RecyclerView_android_orientation = 0;
// aapt resource value: 2
public const int RecyclerView_layoutManager = 2;
// aapt resource value: 4
public const int RecyclerView_reverseLayout = 4;
// aapt resource value: 3
public const int RecyclerView_spanCount = 3;
// aapt resource value: 5
public const int RecyclerView_stackFromEnd = 5;
public static int[] ScrimInsetsFrameLayout = new int[] {
2130772276};
// aapt resource value: 0
public const int ScrimInsetsFrameLayout_insetForeground = 0;
public static int[] ScrollingViewBehavior_Layout = new int[] {
2130772277};
// aapt resource value: 0
public const int ScrollingViewBehavior_Layout_behavior_overlapTop = 0;
public static int[] SearchView = new int[] {
16842970,
16843039,
16843296,
16843364,
2130772181,
2130772182,
2130772183,
2130772184,
2130772185,
2130772186,
2130772187,
2130772188,
2130772189,
2130772190,
2130772191,
2130772192,
2130772193};
// aapt resource value: 0
public const int SearchView_android_focusable = 0;
// aapt resource value: 3
public const int SearchView_android_imeOptions = 3;
// aapt resource value: 2
public const int SearchView_android_inputType = 2;
// aapt resource value: 1
public const int SearchView_android_maxWidth = 1;
// aapt resource value: 8
public const int SearchView_closeIcon = 8;
// aapt resource value: 13
public const int SearchView_commitIcon = 13;
// aapt resource value: 7
public const int SearchView_defaultQueryHint = 7;
// aapt resource value: 9
public const int SearchView_goIcon = 9;
// aapt resource value: 5
public const int SearchView_iconifiedByDefault = 5;
// aapt resource value: 4
public const int SearchView_layout = 4;
// aapt resource value: 15
public const int SearchView_queryBackground = 15;
// aapt resource value: 6
public const int SearchView_queryHint = 6;
// aapt resource value: 11
public const int SearchView_searchHintIcon = 11;
// aapt resource value: 10
public const int SearchView_searchIcon = 10;
// aapt resource value: 16
public const int SearchView_submitBackground = 16;
// aapt resource value: 14
public const int SearchView_suggestionRowLayout = 14;
// aapt resource value: 12
public const int SearchView_voiceIcon = 12;
public static int[] SnackbarLayout = new int[] {
16843039,
2130772024,
2130772278};
// aapt resource value: 0
public const int SnackbarLayout_android_maxWidth = 0;
// aapt resource value: 1
public const int SnackbarLayout_elevation = 1;
// aapt resource value: 2
public const int SnackbarLayout_maxActionInlineWidth = 2;
public static int[] Spinner = new int[] {
16842930,
16843126,
16843131,
16843362,
2130772025};
// aapt resource value: 3
public const int Spinner_android_dropDownWidth = 3;
// aapt resource value: 0
public const int Spinner_android_entries = 0;
// aapt resource value: 1
public const int Spinner_android_popupBackground = 1;
// aapt resource value: 2
public const int Spinner_android_prompt = 2;
// aapt resource value: 4
public const int Spinner_popupTheme = 4;
public static int[] SwitchCompat = new int[] {
16843044,
16843045,
16843074,
2130772194,
2130772195,
2130772196,
2130772197,
2130772198,
2130772199,
2130772200,
2130772201,
2130772202,
2130772203,
2130772204};
// aapt resource value: 1
public const int SwitchCompat_android_textOff = 1;
// aapt resource value: 0
public const int SwitchCompat_android_textOn = 0;
// aapt resource value: 2
public const int SwitchCompat_android_thumb = 2;
// aapt resource value: 13
public const int SwitchCompat_showText = 13;
// aapt resource value: 12
public const int SwitchCompat_splitTrack = 12;
// aapt resource value: 10
public const int SwitchCompat_switchMinWidth = 10;
// aapt resource value: 11
public const int SwitchCompat_switchPadding = 11;
// aapt resource value: 9
public const int SwitchCompat_switchTextAppearance = 9;
// aapt resource value: 8
public const int SwitchCompat_thumbTextPadding = 8;
// aapt resource value: 3
public const int SwitchCompat_thumbTint = 3;
// aapt resource value: 4
public const int SwitchCompat_thumbTintMode = 4;
// aapt resource value: 5
public const int SwitchCompat_track = 5;
// aapt resource value: 6
public const int SwitchCompat_trackTint = 6;
// aapt resource value: 7
public const int SwitchCompat_trackTintMode = 7;
public static int[] TabItem = new int[] {
16842754,
16842994,
16843087};
// aapt resource value: 0
public const int TabItem_android_icon = 0;
// aapt resource value: 1
public const int TabItem_android_layout = 1;
// aapt resource value: 2
public const int TabItem_android_text = 2;
public static int[] TabLayout = new int[] {
2130772279,
2130772280,
2130772281,
2130772282,
2130772283,
2130772284,
2130772285,
2130772286,
2130772287,
2130772288,
2130772289,
2130772290,
2130772291,
2130772292,
2130772293,
2130772294};
// aapt resource value: 3
public const int TabLayout_tabBackground = 3;
// aapt resource value: 2
public const int TabLayout_tabContentStart = 2;
// aapt resource value: 5
public const int TabLayout_tabGravity = 5;
// aapt resource value: 0
public const int TabLayout_tabIndicatorColor = 0;
// aapt resource value: 1
public const int TabLayout_tabIndicatorHeight = 1;
// aapt resource value: 7
public const int TabLayout_tabMaxWidth = 7;
// aapt resource value: 6
public const int TabLayout_tabMinWidth = 6;
// aapt resource value: 4
public const int TabLayout_tabMode = 4;
// aapt resource value: 15
public const int TabLayout_tabPadding = 15;
// aapt resource value: 14
public const int TabLayout_tabPaddingBottom = 14;
// aapt resource value: 13
public const int TabLayout_tabPaddingEnd = 13;
// aapt resource value: 11
public const int TabLayout_tabPaddingStart = 11;
// aapt resource value: 12
public const int TabLayout_tabPaddingTop = 12;
// aapt resource value: 10
public const int TabLayout_tabSelectedTextColor = 10;
// aapt resource value: 8
public const int TabLayout_tabTextAppearance = 8;
// aapt resource value: 9
public const int TabLayout_tabTextColor = 9;
public static int[] TextAppearance = new int[] {
16842901,
16842902,
16842903,
16842904,
16842906,
16843105,
16843106,
16843107,
16843108,
2130772041};
// aapt resource value: 5
public const int TextAppearance_android_shadowColor = 5;
// aapt resource value: 6
public const int TextAppearance_android_shadowDx = 6;
// aapt resource value: 7
public const int TextAppearance_android_shadowDy = 7;
// aapt resource value: 8
public const int TextAppearance_android_shadowRadius = 8;
// aapt resource value: 3
public const int TextAppearance_android_textColor = 3;
// aapt resource value: 4
public const int TextAppearance_android_textColorHint = 4;
// aapt resource value: 0
public const int TextAppearance_android_textSize = 0;
// aapt resource value: 2
public const int TextAppearance_android_textStyle = 2;
// aapt resource value: 1
public const int TextAppearance_android_typeface = 1;
// aapt resource value: 9
public const int TextAppearance_textAllCaps = 9;
public static int[] TextInputLayout = new int[] {
16842906,
16843088,
2130772295,
2130772296,
2130772297,
2130772298,
2130772299,
2130772300,
2130772301,
2130772302,
2130772303,
2130772304,
2130772305,
2130772306,
2130772307,
2130772308};
// aapt resource value: 1
public const int TextInputLayout_android_hint = 1;
// aapt resource value: 0
public const int TextInputLayout_android_textColorHint = 0;
// aapt resource value: 6
public const int TextInputLayout_counterEnabled = 6;
// aapt resource value: 7
public const int TextInputLayout_counterMaxLength = 7;
// aapt resource value: 9
public const int TextInputLayout_counterOverflowTextAppearance = 9;
// aapt resource value: 8
public const int TextInputLayout_counterTextAppearance = 8;
// aapt resource value: 4
public const int TextInputLayout_errorEnabled = 4;
// aapt resource value: 5
public const int TextInputLayout_errorTextAppearance = 5;
// aapt resource value: 10
public const int TextInputLayout_hintAnimationEnabled = 10;
// aapt resource value: 3
public const int TextInputLayout_hintEnabled = 3;
// aapt resource value: 2
public const int TextInputLayout_hintTextAppearance = 2;
// aapt resource value: 13
public const int TextInputLayout_passwordToggleContentDescription = 13;
// aapt resource value: 12
public const int TextInputLayout_passwordToggleDrawable = 12;
// aapt resource value: 11
public const int TextInputLayout_passwordToggleEnabled = 11;
// aapt resource value: 14
public const int TextInputLayout_passwordToggleTint = 14;
// aapt resource value: 15
public const int TextInputLayout_passwordToggleTintMode = 15;
public static int[] Toolbar = new int[] {
16842927,
16843072,
2130771999,
2130772002,
2130772006,
2130772018,
2130772019,
2130772020,
2130772021,
2130772022,
2130772023,
2130772025,
2130772205,
2130772206,
2130772207,
2130772208,
2130772209,
2130772210,
2130772211,
2130772212,
2130772213,
2130772214,
2130772215,
2130772216,
2130772217,
2130772218,
2130772219,
2130772220,
2130772221};
// aapt resource value: 0
public const int Toolbar_android_gravity = 0;
// aapt resource value: 1
public const int Toolbar_android_minHeight = 1;
// aapt resource value: 21
public const int Toolbar_buttonGravity = 21;
// aapt resource value: 23
public const int Toolbar_collapseContentDescription = 23;
// aapt resource value: 22
public const int Toolbar_collapseIcon = 22;
// aapt resource value: 6
public const int Toolbar_contentInsetEnd = 6;
// aapt resource value: 10
public const int Toolbar_contentInsetEndWithActions = 10;
// aapt resource value: 7
public const int Toolbar_contentInsetLeft = 7;
// aapt resource value: 8
public const int Toolbar_contentInsetRight = 8;
// aapt resource value: 5
public const int Toolbar_contentInsetStart = 5;
// aapt resource value: 9
public const int Toolbar_contentInsetStartWithNavigation = 9;
// aapt resource value: 4
public const int Toolbar_logo = 4;
// aapt resource value: 26
public const int Toolbar_logoDescription = 26;
// aapt resource value: 20
public const int Toolbar_maxButtonHeight = 20;
// aapt resource value: 25
public const int Toolbar_navigationContentDescription = 25;
// aapt resource value: 24
public const int Toolbar_navigationIcon = 24;
// aapt resource value: 11
public const int Toolbar_popupTheme = 11;
// aapt resource value: 3
public const int Toolbar_subtitle = 3;
// aapt resource value: 13
public const int Toolbar_subtitleTextAppearance = 13;
// aapt resource value: 28
public const int Toolbar_subtitleTextColor = 28;
// aapt resource value: 2
public const int Toolbar_title = 2;
// aapt resource value: 14
public const int Toolbar_titleMargin = 14;
// aapt resource value: 18
public const int Toolbar_titleMarginBottom = 18;
// aapt resource value: 16
public const int Toolbar_titleMarginEnd = 16;
// aapt resource value: 15
public const int Toolbar_titleMarginStart = 15;
// aapt resource value: 17
public const int Toolbar_titleMarginTop = 17;
// aapt resource value: 19
public const int Toolbar_titleMargins = 19;
// aapt resource value: 12
public const int Toolbar_titleTextAppearance = 12;
// aapt resource value: 27
public const int Toolbar_titleTextColor = 27;
public static int[] View = new int[] {
16842752,
16842970,
2130772222,
2130772223,
2130772224};
// aapt resource value: 1
public const int View_android_focusable = 1;
// aapt resource value: 0
public const int View_android_theme = 0;
// aapt resource value: 3
public const int View_paddingEnd = 3;
// aapt resource value: 2
public const int View_paddingStart = 2;
// aapt resource value: 4
public const int View_theme = 4;
public static int[] ViewBackgroundHelper = new int[] {
16842964,
2130772225,
2130772226};
// aapt resource value: 0
public const int ViewBackgroundHelper_android_background = 0;
// aapt resource value: 1
public const int ViewBackgroundHelper_backgroundTint = 1;
// aapt resource value: 2
public const int ViewBackgroundHelper_backgroundTintMode = 2;
public static int[] ViewStubCompat = new int[] {
16842960,
16842994,
16842995};
// aapt resource value: 0
public const int ViewStubCompat_android_id = 0;
// aapt resource value: 2
public const int ViewStubCompat_android_inflatedId = 2;
// aapt resource value: 1
public const int ViewStubCompat_android_layout = 1;
static Styleable()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Styleable()
{
}
}
}
}
#pragma warning restore 1591
| 31.880762
| 136
| 0.732636
|
[
"MIT"
] |
chanhong/urho-samples
|
FormsSample/FormsSample.Droid/Resources/Resource.Designer.cs
| 222,719
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace X.App.Views.user
{
public class akey : xview
{
}
}
| 14.333333
| 34
| 0.651163
|
[
"MIT"
] |
dreamzhoukui/x.rbt
|
src/Web/User/X.App/Views/user/akey.cs
| 174
|
C#
|
#region Copyright
// Copyright Hitachi Consulting
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Xigadee
{
public static partial class CorePipelineExtensions
{
/// <summary>
/// This method adds an override setting and clears the cache.
/// </summary>
/// <typeparam name="P">The pipeline type.</typeparam>
/// <param name="pipeline">The pipeline.</param>
/// <param name="key">The key.</param>
/// <param name="value"></param>
/// <returns>Returns the pipeline.</returns>
public static P ConfigurationOverrideSet<P>(this P pipeline, string key, string value)
where P : IPipeline
{
pipeline.Configuration.OverrideSettings.Add(key, value);
pipeline.Configuration.CacheFlush();
return pipeline;
}
}
}
| 34.090909
| 94
| 0.672667
|
[
"Apache-2.0"
] |
xigadee/Microservice
|
Src/Xigadee.Platform/Configuration/Pipeline/ConfigurationOverrideSet.cs
| 1,502
|
C#
|
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_UI_GraphicRaycaster_BlockingObjects : LuaObject {
static public void reg(IntPtr l) {
getEnumTable(l,"UnityEngine.UI.GraphicRaycaster.BlockingObjects");
addMember(l,0,"None");
addMember(l,1,"TwoD");
addMember(l,2,"ThreeD");
addMember(l,3,"All");
LuaDLL.lua_pop(l, 1);
}
}
| 27.266667
| 79
| 0.723716
|
[
"MIT"
] |
zhangjie0072/Learn_FairyGUI_Slua
|
Assets/Slua/LuaObject/Unity/Lua_UnityEngine_UI_GraphicRaycaster_BlockingObjects.cs
| 411
|
C#
|
namespace Pioneer.Server.Configuration;
internal class Config
{
public bool IsDebug { get; set; } = false;
public bool IsLocal { get; set; } = true;
public int Port { get; set; } = 2077;
public string Password { get; set; } = "Change Me!";
}
| 22.166667
| 56
| 0.62406
|
[
"MIT"
] |
PioneerMod/Pioneer
|
Pioneer.Server/Configuration/Config.cs
| 268
|
C#
|
using swi = System.Windows.Input;
using swf = System.Windows.Forms;
using Eto.Forms;
using Eto.Drawing;
namespace Eto.Wpf.Forms
{
public class MouseHandler : Mouse.IHandler
{
public Widget Widget { get; set; }
public void Initialize ()
{
}
public Eto.Platform Platform { get; set; }
public PointF Position
{
get { return swf.Control.MousePosition.ToEto (); }
}
public MouseButtons Buttons
{
get {
MouseButtons buttons = MouseButtons.None;
if (swi.Mouse.LeftButton == swi.MouseButtonState.Pressed)
buttons |= MouseButtons.Primary;
if (swi.Mouse.MiddleButton == swi.MouseButtonState.Pressed)
buttons |= MouseButtons.Middle;
if (swi.Mouse.RightButton == swi.MouseButtonState.Pressed)
buttons |= MouseButtons.Alternate;
return buttons;
}
}
}
}
| 21.421053
| 63
| 0.692875
|
[
"BSD-3-Clause"
] |
DavidRutten/Eto
|
Source/Eto.Wpf/Forms/MouseHandler.cs
| 814
|
C#
|
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace MasterDevs.ChromeDevTools.Protocol.Chrome.Target
{
/// <summary>
/// Creates a new empty BrowserContext. Similar to an incognito profile but you can have more than one.
/// </summary>
[Command(ProtocolName.Target.CreateBrowserContext)]
[SupportedBy("Chrome")]
public class CreateBrowserContextCommand: ICommand<CreateBrowserContextCommandResponse>
{
}
}
| 28.058824
| 104
| 0.794549
|
[
"MIT"
] |
Digitalbil/ChromeDevTools
|
source/ChromeDevTools/Protocol/Chrome/Target/CreateBrowserContextCommand.cs
| 477
|
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace RemoteTV.App.Windows
{
public sealed partial class MainPage
{
public MainPage()
{
this.InitializeComponent();
LoadApplication(new RemoteTV.App.App());
}
}
}
| 23.178571
| 52
| 0.730354
|
[
"MIT"
] |
peacecwz/RemoteTV
|
RemoteTV.App/RemoteTV.App.Windows/MainPage.xaml.cs
| 651
|
C#
|
// Copyright (c) Microsoft. All rights reserved.
namespace Microsoft.Azure.Devices.Edge.Agent.Core
{
public interface ICredentials
{
CredentialType CredentialsType { get; }
}
}
| 19.8
| 49
| 0.69697
|
[
"MIT"
] |
alextnewman/iotedge
|
edge-agent/src/Microsoft.Azure.Devices.Edge.Agent.Core/ICredentials.cs
| 198
|
C#
|
namespace BreadWinner
{
public class ConfigOptions
{
public const string ThreadPriority = "BreadWinner.ThreadPriority";
public const string WaitXForthreads = "BreadWinner.WaitXForThreads";
public const string ThrowExceptions = "BreadWinner.ThrowExceptions";
}
}
| 34
| 77
| 0.705882
|
[
"MIT"
] |
gugu91/bread-winner
|
lib/BreadWinner/Configuration/ConfigOptions.cs
| 308
|
C#
|
using System;
namespace Apos.History {
/// <summary>
/// Holds a set of actions along with their inverse.
/// Mostly used for undo and redo functionality.
/// </summary>
public class HistorySet {
/// <summary>
/// Groups undo and redo actions.
/// </summary>
public HistorySet(Action[] undos, Action[] redos) {
_undos = undos;
_redos = redos;
}
/// <summary>
/// Applies the undo actions.
/// </summary>
public void Undo() {
foreach (Action a in _undos) {
a();
}
}
/// <summary>
/// Applies the redo actions.
/// </summary>
public void Redo() {
foreach (Action a in _redos) {
a();
}
}
/// <summary>
/// Group of undo actions that should be executed together.
/// </summary>
protected Action[] _undos;
/// <summary>
/// Group of redo actions that should be executed together.
/// </summary>
protected Action[] _redos;
}
}
| 26.418605
| 67
| 0.480634
|
[
"MIT"
] |
Apostolique/Apos.History
|
Source/HistorySet.cs
| 1,138
|
C#
|
using Chilicki.Commline.Domain.Enums;
using System;
using System.ComponentModel.DataAnnotations;
namespace Chilicki.Commline.Domain.Entities
{
public class Departure
{
public long Id { get; set; }
public int RunIndex { get; set; }
public TimeSpan DepartureTime { get; set; }
public virtual DayType DayType { get; set; }
public bool IsOnNextDay { get; set; }
public bool IsBetweenDays { get; set; }
[Required]
public virtual RouteStop RouteStop { get; set; }
}
}
| 29.944444
| 56
| 0.649351
|
[
"MIT"
] |
kipic96/commline
|
Chilicki.Commline/Chilicki.Commline.Domain/Entities/Departure.cs
| 541
|
C#
|
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace SmartApartmentData.App
{
public class Program
{
public static void Main(string[] args)
{
//CreateHostBuilder(args).Build().Run();
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
}
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 25.935484
| 70
| 0.570896
|
[
"MIT"
] |
dkamau/smart-apartment-data
|
SmartApartmentData.App/Program.cs
| 804
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.269
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Plugin.effiproz {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class StdIcons {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal StdIcons() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Plugin.effiproz.StdIcons", typeof(StdIcons).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
internal static System.Drawing.Bitmap effiproz {
get {
object obj = ResourceManager.GetObject("effiproz", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
internal static System.Drawing.Bitmap effiproz32 {
get {
object obj = ResourceManager.GetObject("effiproz32", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 41.858974
| 168
| 0.596631
|
[
"MIT"
] |
dbgate/datadmin
|
Plugin.effiproz/StdIcons.Designer.cs
| 3,267
|
C#
|
using System;
///<summary>Class for que opperations</summary>
/// <typeparam name="T">param type</typeparam>
class Queue<T>
{
///<summary>Check if its a queue type</summary>
///<return>returns a Queue type</return>
public Type CheckType()
{
return typeof(T);
}
/// <summary>Class Node inside queue class</summary>
public class Node
{
public T value;
public Node next = null;
public Node(T stri)
{
value = stri;
}
}
public Node head;
public Node tail;
public int count;
///<summary>Add new node at the end</summary>
public void Enqueue(T value)
{
Node newnode = new Node(value);
if (head == null)
{
head = newnode;
tail = newnode;
}
else
{
tail.next = newnode;
tail = newnode;
}
count++;
}
///<summary>Add new node at the end</summary>
public int Count()
{
return count;
}
///<summary> deleting the firts node</summary>
public T Dequeue()
{
if (head == null)
{
Console.WriteLine("Queue is empty");
return default(T);
}
else
{
tail.value = head.value;
head = head.next;
count--;
return tail.value;
}
}
///<summary>return value firts node</summary>
public T Peek()
{
if (head == null)
{
Console.WriteLine("Queue is empty");
return default(T);
}
else
{
return head.value;
}
}
///<summary> prints the queue, starting from the head.</summary>
public void Print()
{
if (head == null)
{
Console.WriteLine("Queue is empty");
}
else
{
tail = head;
while(tail != null)
{
Console.WriteLine(tail.value);
tail = tail.next;
}
}
}
///<summary> concatenates all values in the queue only if the queue is of type String or Char</summary>
public string Concatenate()
{
if (head == null)
{
Console.WriteLine("Queue is empty");
return null;
}
else if (typeof(T) != typeof(string) && typeof(T) != typeof(char))
{
Console.WriteLine("Concatenate() is for a queue of Strings or Chars only");
return null;
}
else
{
int j = 0;
string i = "";
tail = head;
if (typeof(T) == typeof(char))
{
while(tail != null)
{
i += tail.value;
tail = tail.next;
}
}
else if (typeof(T) == typeof(string))
{
while (tail != null)
{
if(j != 0)
i += " ";
i += tail.value;
tail = tail.next;
j++;
}
}
return i;
}
}
}
| 17.874172
| 107
| 0.5113
|
[
"MIT"
] |
alzheimeer/holbertonschool-csharp
|
0x0A-csharp-generics/5-concatenate/queue.cs
| 2,701
|
C#
|
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Abstract.Parts;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Json;
namespace Contoso.Abstract.Parts
{
/// <summary>
/// JsonTypeSerializer
/// </summary>
public class JsonTypeSerializer : ITypeSerializer
{
/// <summary>
/// Reads the object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="type">The type.</param>
/// <param name="s">The s.</param>
/// <returns></returns>
public T ReadObject<T>(Type type, Stream s)
where T : class
{
if (type == null)
throw new ArgumentNullException("type");
if (s == null)
throw new ArgumentNullException("s");
var serializer = new DataContractJsonSerializer(type);
return (serializer.ReadObject(s) as T);
}
/// <summary>
/// Reads the objects.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="type">The type.</param>
/// <param name="s">The s.</param>
/// <returns></returns>
public IEnumerable<T> ReadObjects<T>(Type type, Stream s)
where T : class
{
if (type == null)
throw new ArgumentNullException("type");
if (s == null)
throw new ArgumentNullException("s");
var serializer = new DataContractJsonSerializer(type);
return (serializer.ReadObject(s) as IEnumerable<T>);
}
/// <summary>
/// Writes the object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="type">The type.</param>
/// <param name="s">The s.</param>
/// <param name="graph">The graph.</param>
public void WriteObject<T>(Type type, Stream s, T graph)
where T : class
{
if (type == null)
throw new ArgumentNullException("type");
if (s == null)
throw new ArgumentNullException("s");
if (graph == null)
throw new ArgumentNullException("graph");
var serializer = new DataContractJsonSerializer(type);
serializer.WriteObject(s, graph);
}
/// <summary>
/// Writes the objects.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="type">The type.</param>
/// <param name="s">The s.</param>
/// <param name="graphs">The graphs.</param>
public void WriteObjects<T>(Type type, Stream s, IEnumerable<T> graphs)
where T : class
{
if (type == null)
throw new ArgumentNullException("type");
if (s == null)
throw new ArgumentNullException("s");
if (graphs == null)
throw new ArgumentNullException("graphs");
var serializer = new DataContractJsonSerializer(type);
serializer.WriteObject(s, graphs);
}
}
}
| 37.947368
| 80
| 0.580444
|
[
"MIT"
] |
BclEx/BclEx-Abstract
|
src/Platforms/Contoso.Abstract.Web/Abstract/Parts/JsonTypeSerializer.cs
| 4,328
|
C#
|
using RenderingLibrary.Graphics;
using System;
using System.Collections.Generic;
using System.Text;
namespace RenderingLibrary
{
public partial class SystemManagers
{
/// <summary>
/// The font scale value. This can be used to scale all fonts globally,
/// generally in response to a font scaling value like the Android font scale setting.
/// </summary>
public static float GlobalFontScale { get; set; } = 1.0f;
public static SystemManagers Default
{
get;
set;
}
public SkiaSharp.SKCanvas Canvas { get; set; }
public RenderingLibrary.Graphics.Renderer Renderer { get; private set; }
public void Initialize()
{
//mPrimaryThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
Renderer = new Renderer();
Renderer.Initialize(this);
//SpriteManager = new SpriteManager();
//ShapeManager = new ShapeManager();
//TextManager = new TextManager();
//SpriteManager.Managers = this;
//ShapeManager.Managers = this;
//Tex
}
}
}
| 24.833333
| 94
| 0.594799
|
[
"MIT"
] |
J-Swift/Gum
|
SkiaGum/RenderingLibrary/SystemManagers.cs
| 1,194
|
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Security;
using System.Net.Test.Common;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
public abstract class HttpClientHandlerTest_Http2 : HttpClientHandlerTestBase
{
protected override Version UseVersion => HttpVersion.Version20;
public static bool SupportsAlpn => PlatformDetection.SupportsAlpn;
public HttpClientHandlerTest_Http2(ITestOutputHelper output) : base(output)
{
}
private async Task AssertProtocolErrorAsync<T>(Task task, ProtocolErrors errorCode)
where T : Exception
{
Exception e = await Assert.ThrowsAsync<T>(() => task);
string text = e.ToString();
Assert.Contains(((int)errorCode).ToString("x"), text);
Assert.Contains(
Enum.IsDefined(typeof(ProtocolErrors), errorCode) ? errorCode.ToString() : "(unknown error)",
text);
}
private Task AssertProtocolErrorAsync(Task task, ProtocolErrors errorCode)
{
return AssertProtocolErrorAsync<HttpRequestException>(task, errorCode);
}
private Task AssertProtocolErrorForIOExceptionAsync(Task task, ProtocolErrors errorCode)
{
return AssertProtocolErrorAsync<IOException>(task, errorCode);
}
private async Task<(bool, T)> IgnoreSpecificException<ExpectedException, T>(Task<T> task, string expectedExceptionContent = null) where ExpectedException : Exception
{
try
{
return (true, await task);
}
catch (ExpectedException e)
{
if (expectedExceptionContent != null)
{
if (!e.ToString().Contains(expectedExceptionContent))
{
throw;
}
}
return (false, default(T));
}
}
[Fact]
public async Task Http2_ClientPreface_Sent()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task sendTask = client.GetAsync(server.Address);
string connectionPreface = (await server.AcceptConnectionAsync()).PrefixString;
Assert.Equal(Http2LoopbackConnection.Http2Prefix, connectionPreface);
}
}
[Fact]
public async Task Http2_InitialSettings_SentAndAcked()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.AcceptConnectionAsync();
// Receive the initial client settings frame.
Frame receivedFrame = await connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
Assert.Equal(FrameType.Settings, receivedFrame.Type);
// Send the initial server settings frame.
Frame emptySettings = new Frame(0, FrameType.Settings, FrameFlags.None, 0);
await connection.WriteFrameAsync(emptySettings).ConfigureAwait(false);
// Receive the server settings frame ACK.
// This doesn't have to be the next frame, as the client is allowed to send before receiving our SETTINGS frame.
// So, loop until we see it (or the timeout expires)
while (true)
{
receivedFrame = await connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
if (receivedFrame.Type == FrameType.Settings && receivedFrame.AckFlag)
{
break;
}
}
}
}
[Fact]
public async Task Http2_DataSentBeforeServerPreface_ProtocolError()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.AcceptConnectionAsync();
// Send a frame despite not having sent the server connection preface.
DataFrame invalidFrame = new DataFrame(new byte[10], FrameFlags.Padded, 10, 1);
await connection.WriteFrameAsync(invalidFrame);
await AssertProtocolErrorAsync(sendTask, ProtocolErrors.PROTOCOL_ERROR);
}
}
[Fact]
public async Task Http2_NoResponseBody_Success()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
await connection.SendDefaultResponseAsync(streamId);
HttpResponseMessage response = await sendTask;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(0, (await response.Content.ReadAsByteArrayAsync()).Length);
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task Http2_ZeroLengthResponseBody_Success()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
await connection.SendDefaultResponseHeadersAsync(streamId);
// Send zero-length body
var frame = new DataFrame(new byte[0], FrameFlags.EndStream, 0, streamId);
await connection.WriteFrameAsync(frame);
HttpResponseMessage response = await sendTask;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(0, (await response.Content.ReadAsByteArrayAsync()).Length);
}
}
[Theory]
[InlineData("Client content", null)]
[InlineData("Client content", "Server content")]
[InlineData(null, null)]
[InlineData(null, "Server content")]
public async Task Http2ClearText_SendAsync_Success(string clientContent, string serverContent)
{
await Http2LoopbackServer.CreateClientAndServerAsync(async uri =>
{
using HttpClient client = CreateHttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri)
{
Version = UseVersion,
VersionPolicy = HttpVersionPolicy.RequestVersionExact,
Content = clientContent is null ? (HttpContent)null : new StringContent(clientContent),
};
using HttpResponseMessage response = await client.SendAsync(request);
string responseContent = await response.Content.ReadAsStringAsync();
Assert.Equal(serverContent ?? String.Empty, responseContent);
},
async server =>
{
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
Assert.IsNotType<SslStream>(connection.Stream);
HttpRequestData requestData = await connection.ReadRequestDataAsync();
string requestContent = requestData.Body is null ? (string)null : Encoding.ASCII.GetString(requestData.Body);
Assert.Equal(clientContent, requestContent);
await connection.SendResponseAsync(HttpStatusCode.OK, body: serverContent);
}, new Http2Options() { UseSsl = false });
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task Http2_ServerSendsValidSettingsValues_Success()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
// Send a bunch of valid SETTINGS values (that won't interfere with processing requests)
Http2LoopbackConnection connection = await server.EstablishConnectionAsync(
new SettingsEntry { SettingId = SettingId.HeaderTableSize, Value = 0 },
new SettingsEntry { SettingId = SettingId.HeaderTableSize, Value = 1 },
new SettingsEntry { SettingId = SettingId.HeaderTableSize, Value = 345678 },
new SettingsEntry { SettingId = SettingId.InitialWindowSize, Value = 0 },
new SettingsEntry { SettingId = SettingId.InitialWindowSize, Value = 1 },
new SettingsEntry { SettingId = SettingId.InitialWindowSize, Value = 4567890 },
new SettingsEntry { SettingId = SettingId.MaxConcurrentStreams, Value = 1 },
new SettingsEntry { SettingId = SettingId.MaxFrameSize, Value = 16384 },
new SettingsEntry { SettingId = SettingId.MaxFrameSize, Value = 16777215 },
new SettingsEntry { SettingId = SettingId.MaxHeaderListSize, Value = 0 },
new SettingsEntry { SettingId = SettingId.MaxHeaderListSize, Value = 10000000 },
new SettingsEntry { SettingId = (SettingId)5678, Value = 1234 });
int streamId = await connection.ReadRequestHeaderAsync();
await connection.SendDefaultResponseAsync(streamId);
HttpResponseMessage response = await sendTask;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[ConditionalTheory(nameof(SupportsAlpn))]
[InlineData(SettingId.MaxFrameSize, 16383, ProtocolErrors.PROTOCOL_ERROR)]
[InlineData(SettingId.MaxFrameSize, 162777216, ProtocolErrors.PROTOCOL_ERROR)]
[InlineData(SettingId.InitialWindowSize, 0x80000000, ProtocolErrors.FLOW_CONTROL_ERROR)]
public async Task Http2_ServerSendsInvalidSettingsValue_Error(SettingId settingId, uint value, ProtocolErrors expectedError)
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
// Send invalid initial SETTINGS value
Http2LoopbackConnection connection = await server.EstablishConnectionAsync(new SettingsEntry { SettingId = settingId, Value = value });
await AssertProtocolErrorAsync(sendTask, expectedError);
connection.Dispose();
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task Http2_StreamResetByServerBeforeHeadersSent_RequestFails()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
// Send a reset stream frame so that the stream moves to a terminal state.
RstStreamFrame resetStream = new RstStreamFrame(FrameFlags.None, (int)ProtocolErrors.INTERNAL_ERROR, streamId);
await connection.WriteFrameAsync(resetStream);
await AssertProtocolErrorAsync(sendTask, ProtocolErrors.INTERNAL_ERROR);
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task Http2_StreamResetByServerAfterHeadersSent_RequestFails()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
// Send response headers
await connection.SendDefaultResponseHeadersAsync(streamId);
// Send a reset stream frame so that the stream moves to a terminal state.
RstStreamFrame resetStream = new RstStreamFrame(FrameFlags.None, (int)ProtocolErrors.INTERNAL_ERROR, streamId);
await connection.WriteFrameAsync(resetStream);
await AssertProtocolErrorAsync(sendTask, ProtocolErrors.INTERNAL_ERROR);
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task Http2_StreamResetByServerAfterPartialBodySent_RequestFails()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
// Send response headers and partial response body
await connection.SendDefaultResponseHeadersAsync(streamId);
DataFrame dataFrame = new DataFrame(new byte[10], FrameFlags.None, 0, streamId);
await connection.WriteFrameAsync(dataFrame);
// Send a reset stream frame so that the stream moves to a terminal state.
RstStreamFrame resetStream = new RstStreamFrame(FrameFlags.None, (int)ProtocolErrors.INTERNAL_ERROR, streamId);
await connection.WriteFrameAsync(resetStream);
await AssertProtocolErrorAsync(sendTask, ProtocolErrors.INTERNAL_ERROR);
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task GetAsync_StreamRefused_RequestIsRetried()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
(_, Http2LoopbackConnection connection) = await EstablishConnectionAndProcessOneRequestAsync(client, server);
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
(int streamId1, HttpRequestData requestData1) = await connection.ReadAndParseRequestHeaderAsync(readBody: true);
// Send SETTINGS frame to change stream limit to 0, allowing us to send a REFUSED_STREAM error due to the new limit
await connection.ExpectSettingsAckAsync();
Frame frame = new SettingsFrame(new SettingsEntry() { SettingId = SettingId.MaxConcurrentStreams, Value = 0 });
await connection.WriteFrameAsync(frame);
// Send a RST_STREAM with error = REFUSED_STREAM, indicating the request can be retried.
frame = new RstStreamFrame(FrameFlags.None, (int)ProtocolErrors.REFUSED_STREAM, streamId1);
await connection.WriteFrameAsync(frame);
await connection.PingPong();
// Send SETTINGS frame to change stream limit to 1, allowing the request to now be processed
await connection.ExpectSettingsAckAsync();
frame = new SettingsFrame(new SettingsEntry() { SettingId = SettingId.MaxConcurrentStreams, Value = 1 });
await connection.WriteFrameAsync(frame);
// Process retried request
(int streamId2, HttpRequestData requestData2) = await connection.ReadAndParseRequestHeaderAsync(readBody: true);
await connection.SendDefaultResponseAsync(streamId2);
HttpResponseMessage response = await sendTask;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task PostAsync_StreamRefused_RequestIsRetried()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
const string Content = "Hello world";
(_, Http2LoopbackConnection connection) = await EstablishConnectionAndProcessOneRequestAsync(client, server);
Task<HttpResponseMessage> sendTask = client.PostAsync(server.Address, new StringContent(Content));
(int streamId1, HttpRequestData requestData1) = await connection.ReadAndParseRequestHeaderAsync(readBody: true);
Assert.Equal(Content, Encoding.UTF8.GetString(requestData1.Body));
// Send SETTINGS frame to change stream limit to 0, allowing us to send a REFUSED_STREAM error due to the new limit
await connection.ExpectSettingsAckAsync();
Frame frame = new SettingsFrame(new SettingsEntry() { SettingId = SettingId.MaxConcurrentStreams, Value = 0 });
await connection.WriteFrameAsync(frame);
// Send a RST_STREAM with error = REFUSED_STREAM, indicating the request can be retried.
frame = new RstStreamFrame(FrameFlags.None, (int)ProtocolErrors.REFUSED_STREAM, streamId1);
await connection.WriteFrameAsync(frame);
await connection.PingPong();
// Send SETTINGS frame to change stream limit to 1, allowing the request to now be processed
await connection.ExpectSettingsAckAsync();
frame = new SettingsFrame(new SettingsEntry() { SettingId = SettingId.MaxConcurrentStreams, Value = 1 });
await connection.WriteFrameAsync(frame);
// Process retried request
(int streamId2, HttpRequestData requestData2) = await connection.ReadAndParseRequestHeaderAsync(readBody: true);
Assert.Equal(Content, Encoding.UTF8.GetString(requestData2.Body));
await connection.SendDefaultResponseAsync(streamId2);
HttpResponseMessage response = await sendTask;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[OuterLoop("Uses delays")]
[ConditionalFact(nameof(SupportsAlpn))]
public async Task GetAsync_SettingsFrameNotSentOnNewConnection_ClientApplies100StreamLimit()
{
const int DefaultMaxConcurrentStreams = 100;
TimeSpan timeout = TimeSpan.FromSeconds(3);
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<Http2LoopbackConnection> connectionTask = AcceptConnectionAndReadSettings(server, timeout);
List<Task<HttpResponseMessage>> sendTasks = new List<Task<HttpResponseMessage>>();
for (int i = 0; i < DefaultMaxConcurrentStreams; i++)
{
sendTasks.Add(client.GetAsync(server.Address));
}
Http2LoopbackConnection connection = await connectionTask.WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
// Client sets the default MaxConcurrentStreams to 100, so accept 100 requests.
List<int> acceptedRequests = await AcceptRequests(connection, DefaultMaxConcurrentStreams).WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
Assert.Equal(DefaultMaxConcurrentStreams, acceptedRequests.Count);
// Extra request is queued on the client.
Task<HttpResponseMessage> extraSendTask = client.GetAsync(server.Address);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => connection.ReadRequestHeaderAsync()).WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
// Send SETTINGS frame to increase the default stream limit by 1, unblocking the extra request.
await connection.SendSettingsAsync(timeout, new[] { new SettingsEntry() { SettingId = SettingId.MaxConcurrentStreams, Value = DefaultMaxConcurrentStreams + 1 } }).ConfigureAwait(false);
(int extraStreamId, _) = await connection.ReadAndParseRequestHeaderAsync().WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
// Respond to all the requests.
acceptedRequests.Add(extraStreamId);
foreach (int streamId in acceptedRequests)
{
await connection.SendDefaultResponseAsync(streamId).WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
}
sendTasks.Add(extraSendTask);
await Task.WhenAll(sendTasks).WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
foreach (Task<HttpResponseMessage> sendTask in sendTasks)
{
using HttpResponseMessage response = sendTask.Result;
Assert.True(response.IsSuccessStatusCode);
}
}
}
[OuterLoop("Uses delays")]
[ConditionalFact(nameof(SupportsAlpn))]
public async Task GetAsync_ServerDelaysSendingSettingsThenSetsLowerMaxConcurrentStreamsLimitThenIncreaseIt_ClientAppliesEachLimitChangeProperly()
{
const int DefaultMaxConcurrentStreams = 100;
const int ExtraStreams = 20;
TimeSpan timeout = TimeSpan.FromSeconds(3);
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<Http2LoopbackConnection> connectionTask = AcceptConnectionAndReadSettings(server, timeout);
List<Task<HttpResponseMessage>> sendTasks = new List<Task<HttpResponseMessage>>();
for (int i = 0; i < DefaultMaxConcurrentStreams + ExtraStreams; i++)
{
sendTasks.Add(client.GetAsync(server.Address));
}
Http2LoopbackConnection connection = await connectionTask.WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
// Client sets the default MaxConcurrentStreams to 100, so accept 100 requests.
List<int> acceptedRequests = await AcceptRequests(connection, DefaultMaxConcurrentStreams + ExtraStreams).WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
Assert.Equal(DefaultMaxConcurrentStreams, acceptedRequests.Count);
// Send SETTINGS frame with MaxConcurrentStreams = 102
await connection.SendSettingsAsync(timeout, new[] { new SettingsEntry() { SettingId = SettingId.MaxConcurrentStreams, Value = DefaultMaxConcurrentStreams + 2 } }).ConfigureAwait(false);
// Increased MaxConcurrentStreams ublocks only 2 requests.
List<int> acceptedExtraRequests = await AcceptRequests(connection, ExtraStreams).WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
Assert.Equal(2, acceptedExtraRequests.Count);
acceptedRequests.AddRange(acceptedExtraRequests);
// Send SETTINGS frame with MaxConcurrentStreams = DefaultMaxConcurrentStreams + ExtraStreams
await connection.ExpectSettingsAckAsync().ConfigureAwait(false);
Frame frame = new SettingsFrame(new SettingsEntry() { SettingId = SettingId.MaxConcurrentStreams, Value = DefaultMaxConcurrentStreams + ExtraStreams });
await connection.WriteFrameAsync(frame).ConfigureAwait(false);
// Increased MaxConcurrentStreams ublocks all remaining requests.
acceptedExtraRequests = await AcceptRequests(connection, ExtraStreams - 2).WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
Assert.Equal(ExtraStreams - 2, acceptedExtraRequests.Count);
acceptedRequests.AddRange(acceptedExtraRequests);
// Respond to all the requests.
foreach (int streamId in acceptedRequests)
{
await connection.SendDefaultResponseAsync(streamId).WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
}
await Task.WhenAll(sendTasks).WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
foreach (Task<HttpResponseMessage> sendTask in sendTasks)
{
using HttpResponseMessage response = sendTask.Result;
Assert.True(response.IsSuccessStatusCode);
}
}
}
[OuterLoop("Uses delays")]
[ConditionalFact(nameof(SupportsAlpn))]
public async Task GetAsync_ServerSendSettingsWithoutMaxConcurrentStreams_ClientAppliesInfiniteLimit()
{
const int DefaultMaxConcurrentStreams = 100;
TimeSpan timeout = TimeSpan.FromSeconds(3);
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<Http2LoopbackConnection> connectionTask = AcceptConnectionAndReadSettings(server, timeout);
List<Task<HttpResponseMessage>> sendTasks = new List<Task<HttpResponseMessage>>();
for (int i = 0; i < DefaultMaxConcurrentStreams; i++)
{
sendTasks.Add(client.GetAsync(server.Address));
}
Http2LoopbackConnection connection = await connectionTask.WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
// Client sets the default MaxConcurrentStreams to 100, so accept 100 requests.
List<int> acceptedRequests = await AcceptRequests(connection, DefaultMaxConcurrentStreams).WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
Assert.Equal(DefaultMaxConcurrentStreams, acceptedRequests.Count);
// Extra request is queued on the client.
Task<HttpResponseMessage> extraSendTask = client.GetAsync(server.Address);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => connection.ReadRequestHeaderAsync()).WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
// Send SETTINGS frame without MaxConcurrentSettings value.
await connection.SendSettingsAsync(timeout, new SettingsEntry[0]).ConfigureAwait(false);
// Send 100 more requests
sendTasks.Add(extraSendTask);
for (int i = 0; i < DefaultMaxConcurrentStreams; i++)
{
sendTasks.Add(client.GetAsync(server.Address));
}
// Client sets the MaxConcurrentStreams to 'infinite', so accept 100 + 1 extra requests.
List<int> acceptedExtraRequests = await AcceptRequests(connection, DefaultMaxConcurrentStreams + 1).WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
Assert.Equal(DefaultMaxConcurrentStreams + 1, acceptedExtraRequests.Count);
// Respond to all the requests.
acceptedRequests.AddRange(acceptedExtraRequests);
foreach (int streamId in acceptedRequests)
{
await connection.SendDefaultResponseAsync(streamId).WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
}
sendTasks.Add(extraSendTask);
await Task.WhenAll(sendTasks).WaitAsync(TestHelper.PassingTestTimeout).ConfigureAwait(false);
foreach (Task<HttpResponseMessage> sendTask in sendTasks)
{
using HttpResponseMessage response = sendTask.Result;
Assert.True(response.IsSuccessStatusCode);
}
}
}
// This test is based on RFC 7540 section 6.1:
// "If a DATA frame is received whose stream identifier field is 0x0, the recipient MUST
// respond with a connection error (Section 5.4.1) of type PROTOCOL_ERROR."
[ConditionalFact(nameof(SupportsAlpn))]
public async Task DataFrame_NoStream_ConnectionError()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
await connection.ReadRequestHeaderAsync();
// Send a malformed frame (streamId is 0)
DataFrame invalidFrame = new DataFrame(new byte[10], FrameFlags.None, 0, 0);
await connection.WriteFrameAsync(invalidFrame);
// As this is a connection level error, the client should see the request fail.
await AssertProtocolErrorAsync(sendTask, ProtocolErrors.PROTOCOL_ERROR);
// The client should close the connection as this is a fatal connection level error.
Assert.Null(await connection.ReadFrameAsync(TimeSpan.FromSeconds(30)));
}
}
// This test is based on RFC 7540 section 5.1:
// "Receiving any frame other than HEADERS or PRIORITY on a stream in this state MUST
// be treated as a connection error (Section 5.4.1) of type PROTOCOL_ERROR."
[ConditionalFact(nameof(SupportsAlpn))]
public async Task DataFrame_IdleStream_ConnectionError()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
await connection.ReadRequestHeaderAsync();
// Send a data frame on stream 5, which is in the idle state.
DataFrame invalidFrame = new DataFrame(new byte[10], FrameFlags.None, 0, 5);
await connection.WriteFrameAsync(invalidFrame);
// As this is a connection level error, the client should see the request fail.
await AssertProtocolErrorAsync(sendTask, ProtocolErrors.PROTOCOL_ERROR);
// The client should close the connection as this is a fatal connection level error.
Assert.Null(await connection.ReadFrameAsync(TimeSpan.FromSeconds(30)));
}
}
// The spec does not clearly define how a client should behave when it receives unsolicited
// headers from the server on an idle stream. We fall back to treating this as a connection
// level error, as we do for other unexpected frames on idle streams.
[ConditionalFact(nameof(SupportsAlpn))]
public async Task HeadersFrame_IdleStream_ConnectionError()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
// Send a headers frame on stream 5, which is in the idle state.
await connection.SendDefaultResponseHeadersAsync(5);
// As this is a connection level error, the client should see the request fail.
await AssertProtocolErrorAsync(sendTask, ProtocolErrors.PROTOCOL_ERROR);
// The client should close the connection as this is a fatal connection level error.
Assert.Null(await connection.ReadFrameAsync(TimeSpan.FromSeconds(30)));
}
}
private async Task<Http2LoopbackConnection> AcceptConnectionAndReadSettings(Http2LoopbackServer server, TimeSpan timeout)
{
Http2LoopbackConnection connection = await server.AcceptConnectionAsync(timeout).ConfigureAwait(false);
await connection.ReadSettingsAsync().ConfigureAwait(false);
return connection;
}
private async Task<List<int>> AcceptRequests(Http2LoopbackConnection connection, int maxRequests = int.MaxValue)
{
List<int> streamIds = new List<int>();
for (int i = 0; i < maxRequests; i++)
{
try
{
streamIds.Add((await connection.ReadAndParseRequestHeaderAsync().ConfigureAwait(false)).streamId);
}
catch (OperationCanceledException)
{
return streamIds;
}
}
return streamIds;
}
private static Frame MakeSimpleHeadersFrame(int streamId, bool endHeaders = false, bool endStream = false) =>
new HeadersFrame(new byte[] { 0x88 }, // :status: 200
(endHeaders ? FrameFlags.EndHeaders : FrameFlags.None) | (endStream ? FrameFlags.EndStream : FrameFlags.None),
0, 0, 0, streamId);
private static Frame MakeSimpleContinuationFrame(int streamId, bool endHeaders = false)
{
Memory<byte> headerBlock = new byte[Frame.MaxFrameLength];
int bytesGenerated = HPackEncoder.EncodeHeader("foo", "bar", HPackFlags.None, headerBlock.Span);
return new ContinuationFrame(headerBlock.Slice(0, bytesGenerated),
(endHeaders ? FrameFlags.EndHeaders : FrameFlags.None),
0, 0, 0, streamId);
}
private static Frame MakeSimpleDataFrame(int streamId, bool endStream = false) =>
new DataFrame(new byte[] { 0x00 },
(endStream ? FrameFlags.EndStream : FrameFlags.None),
0, streamId);
[ConditionalFact(nameof(SupportsAlpn))]
public async Task ResponseStreamFrames_ContinuationBeforeHeaders_ConnectionError()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
await connection.WriteFrameAsync(MakeSimpleContinuationFrame(streamId));
// As this is a connection level error, the client should see the request fail.
await AssertProtocolErrorAsync(sendTask, ProtocolErrors.PROTOCOL_ERROR);
// The client should close the connection as this is a fatal connection level error.
Assert.Null(await connection.ReadFrameAsync(TimeSpan.FromSeconds(30)));
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task ResponseStreamFrames_DataBeforeHeaders_ConnectionError()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
await connection.WriteFrameAsync(MakeSimpleDataFrame(streamId));
// As this is a connection level error, the client should see the request fail.
await AssertProtocolErrorAsync(sendTask, ProtocolErrors.PROTOCOL_ERROR);
// The client should close the connection as this is a fatal connection level error.
Assert.Null(await connection.ReadFrameAsync(TimeSpan.FromSeconds(30)));
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task ResponseStreamFrames_HeadersAfterHeadersWithoutEndHeaders_ConnectionError()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
await connection.WriteFrameAsync(MakeSimpleHeadersFrame(streamId, endHeaders: false));
await connection.WriteFrameAsync(MakeSimpleHeadersFrame(streamId, endHeaders: false));
// As this is a connection level error, the client should see the request fail.
await AssertProtocolErrorAsync(sendTask, ProtocolErrors.PROTOCOL_ERROR);
// The client should close the connection as this is a fatal connection level error.
Assert.Null(await connection.ReadFrameAsync(TimeSpan.FromSeconds(30)));
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task ResponseStreamFrames_HeadersAfterHeadersAndContinuationWithoutEndHeaders_ConnectionError()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
await connection.WriteFrameAsync(MakeSimpleHeadersFrame(streamId, endHeaders: false));
await connection.WriteFrameAsync(MakeSimpleContinuationFrame(streamId, endHeaders: false));
await connection.WriteFrameAsync(MakeSimpleHeadersFrame(streamId, endHeaders: false));
// As this is a connection level error, the client should see the request fail.
await AssertProtocolErrorAsync(sendTask, ProtocolErrors.PROTOCOL_ERROR);
// The client should close the connection as this is a fatal connection level error.
Assert.Null(await connection.ReadFrameAsync(TimeSpan.FromSeconds(30)));
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task ResponseStreamFrames_DataAfterHeadersWithoutEndHeaders_ConnectionError()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
await connection.WriteFrameAsync(MakeSimpleHeadersFrame(streamId, endHeaders: false));
await connection.WriteFrameAsync(MakeSimpleDataFrame(streamId));
// As this is a connection level error, the client should see the request fail.
await AssertProtocolErrorAsync(sendTask, ProtocolErrors.PROTOCOL_ERROR);
// The client should close the connection as this is a fatal connection level error.
Assert.Null(await connection.ReadFrameAsync(TimeSpan.FromSeconds(30)));
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task ResponseStreamFrames_DataAfterHeadersAndContinuationWithoutEndHeaders_ConnectionError()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
await connection.WriteFrameAsync(MakeSimpleHeadersFrame(streamId, endHeaders: false));
await connection.WriteFrameAsync(MakeSimpleContinuationFrame(streamId, endHeaders: false));
await connection.WriteFrameAsync(MakeSimpleDataFrame(streamId));
// As this is a connection level error, the client should see the request fail.
await AssertProtocolErrorAsync(sendTask, ProtocolErrors.PROTOCOL_ERROR);
// The client should close the connection as this is a fatal connection level error.
Assert.Null(await connection.ReadFrameAsync(TimeSpan.FromSeconds(30)));
}
}
// This test is based on RFC 7540 section 6.8:
// "An endpoint MUST treat a GOAWAY frame with a stream identifier other than 0x0 as a
// connection error (Section 5.4.1) of type PROTOCOL_ERROR."
[ConditionalFact(nameof(SupportsAlpn))]
public async Task GoAwayFrame_NonzeroStream_ConnectionError()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
await connection.ReadRequestHeaderAsync();
// Send a GoAway frame on stream 1.
GoAwayFrame invalidFrame = new GoAwayFrame(0, (int)ProtocolErrors.ENHANCE_YOUR_CALM, new byte[0], 1);
await connection.WriteFrameAsync(invalidFrame);
// As this is a connection level error, the client should see the request fail.
await AssertProtocolErrorAsync(sendTask, ProtocolErrors.PROTOCOL_ERROR);
// The client should close the connection as this is a fatal connection level error.
Assert.Null(await connection.ReadFrameAsync(TimeSpan.FromSeconds(30)));
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task GoAwayFrame_NewRequest_NewConnection()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
server.AllowMultipleConnections = true;
Task<HttpResponseMessage> sendTask1 = client.GetAsync(server.Address);
Http2LoopbackConnection connection1 = await server.EstablishConnectionAsync();
int streamId1 = await connection1.ReadRequestHeaderAsync();
await connection1.SendGoAway(streamId1);
await connection1.SendDefaultResponseAsync(streamId1);
HttpResponseMessage response1 = await sendTask1;
Assert.Equal(HttpStatusCode.OK, response1.StatusCode);
// New connection should be established after GOAWAY
Task<HttpResponseMessage> sendTask2 = client.GetAsync(server.Address);
Http2LoopbackConnection connection2 = await server.EstablishConnectionAsync();
int streamId2 = await connection2.ReadRequestHeaderAsync();
await connection2.SendDefaultResponseAsync(streamId2);
HttpResponseMessage response2 = await sendTask2;
Assert.Equal(HttpStatusCode.OK, response2.StatusCode);
await connection1.WaitForConnectionShutdownAsync();
await connection2.WaitForConnectionShutdownAsync();
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task GoAwayFrame_ServerDisconnect_AbortStreams()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
await connection.SendGoAway(streamId);
// wait until GOAWAY received
await connection.PingPong();
// Shutdown the connection unexpectedly
await connection.WaitForConnectionShutdownAsync();
// Expect client to detect that server has disconnected and throw an exception
await Assert.ThrowsAnyAsync<HttpRequestException>(() =>
new Task[]
{
sendTask
}.WhenAllOrAnyFailed(TestHelper.PassingTestTimeoutMilliseconds));
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task GoAwayFrame_UnprocessedStreamFirstRequestFinishedFirst_RequestRestarted()
{
// This test case is similar to GoAwayFrame_UnprocessedStreamFirstRequestWaitsUntilSecondFinishes_RequestRestarted
// but is easier: we close first connection before we expect retry to happen
using (await Watchdog.CreateAsync())
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
server.AllowMultipleConnections = true;
Task<HttpResponseMessage> sendTask1 = client.GetAsync(server.Address);
Http2LoopbackConnection connection1 = await server.EstablishConnectionAsync();
int streamId1 = await connection1.ReadRequestHeaderAsync();
Task<HttpResponseMessage> sendTask2 = client.GetAsync(server.Address);
int streamId2 = await connection1.ReadRequestHeaderAsync();
// Client should try to restart on new connection when GOAWAY is sent
Task<Http2LoopbackConnection> waitForSecondConnection = server.EstablishConnectionAsync();
await connection1.SendGoAway(streamId1);
// Wait until GOAWAY received
await connection1.PingPong();
// Complete first request
await connection1.SendDefaultResponseAsync(streamId1);
HttpResponseMessage response1 = await sendTask1;
Assert.Equal(HttpStatusCode.OK, response1.StatusCode);
await connection1.WaitForConnectionShutdownAsync();
// Client should retry connection
Http2LoopbackConnection connection2 = await waitForSecondConnection;
// Complete second request
int streamId3 = await connection2.ReadRequestHeaderAsync();
await connection2.SendDefaultResponseAsync(streamId3);
HttpResponseMessage response2 = await sendTask2;
Assert.Equal(HttpStatusCode.OK, response2.StatusCode);
await connection2.WaitForConnectionShutdownAsync();
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task GoAwayFrame_UnprocessedStreamFirstRequestWaitsUntilSecondFinishes_RequestRestarted()
{
using (await Watchdog.CreateAsync())
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
server.AllowMultipleConnections = true;
Task<HttpResponseMessage> sendTask1 = client.GetAsync(server.Address);
Http2LoopbackConnection connection1 = await server.EstablishConnectionAsync();
int streamId1 = await connection1.ReadRequestHeaderAsync();
Task<HttpResponseMessage> sendTask2 = client.GetAsync(server.Address);
int streamId2 = await connection1.ReadRequestHeaderAsync();
// Client should try to restart on new connection when GOAWAY is sent
Task<Http2LoopbackConnection> waitForSecondConnection = server.EstablishConnectionAsync();
await connection1.SendGoAway(streamId1);
// Wait until GOAWAY received
await connection1.PingPong();
// Client should retry connection
Http2LoopbackConnection connection2 = await waitForSecondConnection;
// Complete second request
int streamId3 = await connection2.ReadRequestHeaderAsync();
await connection2.SendDefaultResponseAsync(streamId3);
HttpResponseMessage response2 = await sendTask2;
Assert.Equal(HttpStatusCode.OK, response2.StatusCode);
await connection2.WaitForConnectionShutdownAsync();
// Complete first request
await connection1.SendDefaultResponseAsync(streamId1);
HttpResponseMessage response1 = await sendTask1;
Assert.Equal(HttpStatusCode.OK, response1.StatusCode);
await connection1.WaitForConnectionShutdownAsync();
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task GoAwayFrame_RequestInFlight_Finished()
{
await Http2LoopbackServer.CreateClientAndServerAsync(async uri =>
{
using (HttpClient client = CreateHttpClient())
{
HttpResponseMessage response = await client.GetAsync(uri);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
byte[] responseBody = await response.Content.ReadAsByteArrayAsync();
Assert.Equal(
new byte[20]
{
5, 4, 3, 2, 1,
11, 10, 9, 8, 7, 6,
15, 14, 13, 12,
20, 19, 18, 17, 16,
},
responseBody);
}
},
async server =>
{
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
await connection.SendDefaultResponseHeadersAsync(streamId);
await connection.SendResponseBodyAsync(streamId, new byte[5] { 5, 4, 3, 2, 1 }, isFinal: false);
await connection.SendResponseBodyAsync(streamId, new byte[6] { 11, 10, 9, 8, 7, 6 }, isFinal: false);
// Signal that our request is the last thing which will be processed
await connection.SendGoAway(streamId);
// Make sure client received GOAWAY
await connection.PingPong();
await connection.SendResponseBodyAsync(streamId, new byte[4] { 15, 14, 13, 12 }, isFinal: false);
await connection.SendResponseBodyAsync(streamId, new byte[5] { 20, 19, 18, 17, 16 }, isFinal: true);
await connection.WaitForConnectionShutdownAsync();
});
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task DataFrame_TooLong_ConnectionError()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
await connection.ReadRequestHeaderAsync();
// Send a malformed frame.
DataFrame invalidFrame = new DataFrame(new byte[Frame.MaxFrameLength + 1], FrameFlags.None, 0, 0);
await connection.WriteFrameAsync(invalidFrame);
// As this is a connection level error, the client should see the request fail.
await AssertProtocolErrorAsync(sendTask, ProtocolErrors.FRAME_SIZE_ERROR);
}
}
[ConditionalTheory(nameof(SupportsAlpn))]
[InlineData(true)]
[InlineData(false)]
public async Task CompletedResponse_FrameReceived_Ignored(bool sendDataFrame)
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
connection.IgnoreWindowUpdates();
int streamId = await connection.ReadRequestHeaderAsync();
// Send response and end stream.
await connection.SendDefaultResponseHeadersAsync(streamId);
DataFrame dataFrame = new DataFrame(new byte[10], FrameFlags.EndStream, 0, streamId);
await connection.WriteFrameAsync(dataFrame);
HttpResponseMessage response = await sendTask;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Send a frame on the now-closed stream.
Frame invalidFrame = ConstructInvalidFrameForClosedStream(streamId, sendDataFrame);
await connection.WriteFrameAsync(invalidFrame);
// Pingpong to ensure the frame is processed and ignored
await connection.PingPong();
await ValidateConnection(client, server.Address, connection);
}
}
[ConditionalTheory(nameof(SupportsAlpn))]
[InlineData(true)]
[InlineData(false)]
public async Task EmptyResponse_FrameReceived_Ignored(bool sendDataFrame)
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
// Send empty response.
await connection.SendDefaultResponseAsync(streamId);
HttpResponseMessage response = await sendTask;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Send a frame on the now-closed stream.
Frame invalidFrame = ConstructInvalidFrameForClosedStream(streamId, sendDataFrame);
await connection.WriteFrameAsync(invalidFrame);
// Pingpong to ensure the frame is processed and ignored
await connection.PingPong();
await ValidateConnection(client, server.Address, connection);
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task CompletedResponse_WindowUpdateFrameReceived_Success()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
// Send empty response.
await connection.SendDefaultResponseAsync(streamId);
HttpResponseMessage response = await sendTask;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Send a frame on the now-closed stream.
WindowUpdateFrame invalidFrame = new WindowUpdateFrame(1, streamId);
await connection.WriteFrameAsync(invalidFrame);
// The client should close the connection.
await connection.WaitForConnectionShutdownAsync();
}
}
private static Frame ConstructInvalidFrameForClosedStream(int streamId, bool dataFrame)
{
if (dataFrame)
{
return new DataFrame(new byte[10], FrameFlags.None, 0, streamId);
}
else
{
byte[] headers = new byte[] { 0x88 }; // Encoding for ":status: 200"
return new HeadersFrame(headers, FrameFlags.EndHeaders, 0, 0, 0, streamId);
}
}
// Validate that connection is still usable, by sending a request and receiving a response
private static async Task<int> ValidateConnection(HttpClient client, Uri serverAddress, Http2LoopbackConnection connection)
{
Task<HttpResponseMessage> sendTask = client.GetAsync(serverAddress);
int streamId = await connection.ReadRequestHeaderAsync();
await connection.SendDefaultResponseAsync(streamId);
HttpResponseMessage response = await sendTask;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
return streamId;
}
public static IEnumerable<object[]> ValidAndInvalidProtocolErrors() =>
Enum.GetValues(typeof(ProtocolErrors))
.Cast<ProtocolErrors>()
.Where(e => e != ProtocolErrors.REFUSED_STREAM) // REFUSED_STREAM allows retry instead of abort, so skip it
.Concat(new[] { (ProtocolErrors)12345 })
.Select(p => new object[] { p });
public static IEnumerable<object[]> ValidAndInvalidProtocolErrorsAndBool()
{
foreach (object[] args in ValidAndInvalidProtocolErrors())
{
yield return args.Append(true).ToArray();
yield return args.Append(false).ToArray();
}
}
[ConditionalTheory(nameof(SupportsAlpn))]
[MemberData(nameof(ValidAndInvalidProtocolErrorsAndBool))]
public async Task ResetResponseStream_FrameReceived_Ignored(ProtocolErrors error, bool dataFrame)
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
await connection.SendDefaultResponseHeadersAsync(streamId);
// Send a reset stream frame so that stream 1 moves to a terminal state.
RstStreamFrame resetStream = new RstStreamFrame(FrameFlags.None, (int)error, streamId);
await connection.WriteFrameAsync(resetStream);
await AssertProtocolErrorAsync(sendTask, error);
// Send a frame on the now-closed stream.
Frame invalidFrame = ConstructInvalidFrameForClosedStream(streamId, dataFrame);
await connection.WriteFrameAsync(invalidFrame);
// Pingpong to ensure the frame is processed and ignored
await connection.PingPong();
await ValidateConnection(client, server.Address, connection);
}
}
private static async Task<(int, Http2LoopbackConnection)> EstablishConnectionAndProcessOneRequestAsync(HttpClient client, Http2LoopbackServer server)
{
int streamId = -1;
// Establish connection and send initial request/response to ensure connection is available for subsequent use
Http2LoopbackConnection connection = null;
await new[]
{
Task.Run(async () =>
{
using (HttpResponseMessage response = await client.GetAsync(server.Address))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(0, (await response.Content.ReadAsByteArrayAsync()).Length);
}
}),
Task.Run(async () =>
{
connection = await server.EstablishConnectionAsync();
streamId = await connection.ReadRequestHeaderAsync();
await connection.SendDefaultResponseAsync(streamId);
})
}.WhenAllOrAnyFailed(TestHelper.PassingTestTimeoutMilliseconds);
return (streamId, connection);
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task GoAwayFrame_NoPendingStreams_ConnectionClosed()
{
using (await Watchdog.CreateAsync())
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
(int streamId, Http2LoopbackConnection connection) = await EstablishConnectionAndProcessOneRequestAsync(client, server);
// Send GOAWAY.
GoAwayFrame goAwayFrame = new GoAwayFrame(streamId, 0, new byte[0], 0);
await connection.WriteFrameAsync(goAwayFrame);
// The client should close the connection.
await connection.WaitForConnectionShutdownAsync();
// New request should cause a new connection
await EstablishConnectionAndProcessOneRequestAsync(client, server);
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task GoAwayFrame_AllPendingStreamsValid_RequestsSucceedAndConnectionClosed()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
(_, Http2LoopbackConnection connection) = await EstablishConnectionAndProcessOneRequestAsync(client, server);
// Issue three requests
Task<HttpResponseMessage> sendTask1 = client.GetAsync(server.Address);
Task<HttpResponseMessage> sendTask2 = client.GetAsync(server.Address);
Task<HttpResponseMessage> sendTask3 = client.GetAsync(server.Address);
// Receive three requests
int streamId1 = await connection.ReadRequestHeaderAsync();
int streamId2 = await connection.ReadRequestHeaderAsync();
int streamId3 = await connection.ReadRequestHeaderAsync();
Assert.True(streamId1 < streamId2);
Assert.True(streamId2 < streamId3);
// Send various partial responses
// First response: Don't send anything yet
// Second response: Send headers, no body yet
await connection.SendDefaultResponseHeadersAsync(streamId2);
// Third response: Send headers, partial body
await connection.SendDefaultResponseHeadersAsync(streamId3);
await connection.SendResponseDataAsync(streamId3, new byte[5], endStream: false);
// Send a GOAWAY frame that indicates that we will process all three streams
GoAwayFrame goAwayFrame = new GoAwayFrame(streamId3, 0, new byte[0], 0);
await connection.WriteFrameAsync(goAwayFrame);
// Finish sending responses
await connection.SendDefaultResponseHeadersAsync(streamId1);
await connection.SendResponseDataAsync(streamId1, new byte[10], endStream: true);
await connection.SendResponseDataAsync(streamId2, new byte[10], endStream: true);
await connection.SendResponseDataAsync(streamId3, new byte[5], endStream: true);
// We will not send any more frames, so send EOF now, and ensure the client handles this properly.
connection.ShutdownSend();
// Receive all responses
HttpResponseMessage response1 = await sendTask1;
Assert.Equal(HttpStatusCode.OK, response1.StatusCode);
Assert.Equal(10, (await response1.Content.ReadAsByteArrayAsync()).Length);
HttpResponseMessage response2 = await sendTask2;
Assert.Equal(HttpStatusCode.OK, response2.StatusCode);
Assert.Equal(10, (await response2.Content.ReadAsByteArrayAsync()).Length);
HttpResponseMessage response3 = await sendTask3;
Assert.Equal(HttpStatusCode.OK, response3.StatusCode);
Assert.Equal(10, (await response3.Content.ReadAsByteArrayAsync()).Length);
// Now that all pending responses have been sent, the client should close the connection.
await connection.WaitForConnectionShutdownAsync();
// New request should cause a new connection
await EstablishConnectionAndProcessOneRequestAsync(client, server);
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task GoAwayFrame_AbortAllPendingStreams_StreamFailWithExpectedException()
{
using (await Watchdog.CreateAsync())
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
client.BaseAddress = server.Address;
server.AllowMultipleConnections = true;
(_, Http2LoopbackConnection connection) = await EstablishConnectionAndProcessOneRequestAsync(client, server);
// Issue three requests, we want to make sure the specific task is related with specific stream
Task<HttpResponseMessage> sendTask1 = client.GetAsync("request1");
int streamId1 = await connection.ReadRequestHeaderAsync();
Task<HttpResponseMessage> sendTask2 = client.GetAsync("request2");
int streamId2 = await connection.ReadRequestHeaderAsync();
Task<HttpResponseMessage> sendTask3 = client.GetAsync("request3");
int streamId3 = await connection.ReadRequestHeaderAsync();
Assert.InRange(streamId1, 1, streamId2 - 1);
Assert.InRange(streamId2, streamId1 + 1, streamId3 - 1);
Assert.InRange(streamId3, streamId2 + 1, Int32.MaxValue);
// Send various partial responses
// First response: Don't send anything yet, request should be retried on the new connection
// Second response: Send headers, no body yet - request should fail
await connection.SendDefaultResponseHeadersAsync(streamId2);
// Third response: Send headers, partial body - request should fail
await connection.SendDefaultResponseHeadersAsync(streamId3);
await connection.SendResponseDataAsync(streamId3, new byte[5], endStream: false);
// Ensure all sent frames are received by client
await connection.PingPong();
// Send a GOAWAY frame that indicates that we have not processed any of the requests
await connection.SendGoAway(0, ProtocolErrors.ENHANCE_YOUR_CALM);
Http2LoopbackConnection newConnection = await server.EstablishConnectionAsync();
HeadersFrame retriedFrame = await newConnection.ReadRequestHeaderFrameAsync();
int retriedStreamId = retriedFrame.StreamId;
Assert.InRange(retriedStreamId, 1, Int32.MaxValue);
string headerData = Encoding.UTF8.GetString(retriedFrame.Data.Span);
await newConnection.SendDefaultResponseHeadersAsync(retriedStreamId);
await newConnection.SendResponseDataAsync(retriedStreamId, new byte[3], endStream: true);
Assert.Contains("request1", headerData);
HttpResponseMessage response1 = await sendTask1;
Assert.Equal(HttpStatusCode.OK, response1.StatusCode);
await newConnection.ShutdownIgnoringErrorsAsync(retriedStreamId, ProtocolErrors.ENHANCE_YOUR_CALM);
await AssertProtocolErrorAsync(sendTask2, ProtocolErrors.ENHANCE_YOUR_CALM);
await AssertProtocolErrorAsync(sendTask3, ProtocolErrors.ENHANCE_YOUR_CALM);
await connection.WaitForConnectionShutdownAsync();
}
}
private static async Task<int> ReadToEndOfStream(Http2LoopbackConnection connection, int streamId)
{
int bytesReceived = 0;
while (true)
{
Frame frame = await connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
Assert.Equal(streamId, frame.StreamId);
Assert.Equal(FrameType.Data, frame.Type);
bytesReceived += frame.Length;
if (frame.Flags == FrameFlags.EndStream)
{
break;
}
Assert.Equal(FrameFlags.None, frame.Flags);
Assert.True(frame.Length > 0);
}
return bytesReceived;
}
[OuterLoop("Uses Task.Delay")]
[ConditionalFact(nameof(SupportsAlpn))]
public async Task Http2_FlowControl_ClientDoesNotExceedWindows()
{
const int InitialWindowSize = 65535;
const int ContentSize = 100_000;
var content = new ByteAtATimeContent(ContentSize);
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> clientTask = client.PostAsync(server.Address, content);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
Frame frame = await connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
int streamId = frame.StreamId;
Assert.Equal(FrameType.Headers, frame.Type);
Assert.Equal(FrameFlags.EndHeaders, frame.Flags);
// Receive up to initial window size
int bytesReceived = 0;
while (bytesReceived < InitialWindowSize)
{
frame = await connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
Assert.Equal(streamId, frame.StreamId);
Assert.Equal(FrameType.Data, frame.Type);
Assert.Equal(FrameFlags.None, frame.Flags);
Assert.True(frame.Length > 0);
bytesReceived += frame.Length;
}
Assert.Equal(InitialWindowSize, bytesReceived);
// Issue another read. It shouldn't complete yet. Wait a brief period of time to ensure it doesn't complete.
Task<Frame> readFrameTask = connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
await Task.Delay(500);
Assert.False(readFrameTask.IsCompleted);
// Increase connection window by one. This should still not complete the read.
await connection.WriteFrameAsync(new WindowUpdateFrame(1, 0));
await Task.Delay(500);
Assert.False(readFrameTask.IsCompleted);
// Increase stream window by two. This should complete the read with a single byte.
await connection.WriteFrameAsync(new WindowUpdateFrame(2, streamId));
frame = await readFrameTask;
Assert.Equal(1, frame.Length);
bytesReceived++;
// Issue another read and ensure it doesn't complete yet.
readFrameTask = connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
await Task.Delay(500);
Assert.False(readFrameTask.IsCompleted);
// Increase connection window by two. This should complete the read with a single byte.
await connection.WriteFrameAsync(new WindowUpdateFrame(2, 0));
frame = await readFrameTask;
Assert.Equal(1, frame.Length);
bytesReceived++;
// Issue another read and ensure it doesn't complete yet.
readFrameTask = connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
await Task.Delay(500);
Assert.False(readFrameTask.IsCompleted);
// Increase connection window to allow exactly the remaining request size. This should still not complete the read.
await connection.WriteFrameAsync(new WindowUpdateFrame(ContentSize - bytesReceived - 1, 0));
await Task.Delay(500);
Assert.False(readFrameTask.IsCompleted);
// Increase stream window to allow exactly the remaining request size. This should allow the rest of the request to be sent.
await connection.WriteFrameAsync(new WindowUpdateFrame(ContentSize - bytesReceived, streamId));
frame = await readFrameTask;
Assert.Equal(streamId, frame.StreamId);
Assert.Equal(FrameType.Data, frame.Type);
Assert.Equal(FrameFlags.None, frame.Flags);
Assert.True(frame.Length > 0);
bytesReceived += frame.Length;
// Read to end of stream
bytesReceived += await ReadToEndOfStream(connection, streamId);
Assert.Equal(ContentSize, bytesReceived);
await connection.SendDefaultResponseAsync(streamId);
HttpResponseMessage response = await clientTask;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[OuterLoop("Uses Task.Delay")]
[ConditionalFact(nameof(SupportsAlpn))]
public async Task Http2_InitialWindowSize_ClientDoesNotExceedWindows()
{
const int DefaultInitialWindowSize = 65535;
const int ContentSize = DefaultInitialWindowSize + 1000;
var content = new ByteAtATimeContent(ContentSize);
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> clientTask = client.PostAsync(server.Address, content);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
// Bump connection window so it won't block the client.
await connection.WriteFrameAsync(new WindowUpdateFrame(ContentSize - DefaultInitialWindowSize, 0));
Frame frame = await connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
int streamId = frame.StreamId;
Assert.Equal(FrameType.Headers, frame.Type);
Assert.Equal(FrameFlags.EndHeaders, frame.Flags);
// Receive up to initial window size
int bytesReceived = 0;
while (bytesReceived < DefaultInitialWindowSize)
{
frame = await connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
Assert.Equal(streamId, frame.StreamId);
Assert.Equal(FrameType.Data, frame.Type);
Assert.Equal(FrameFlags.None, frame.Flags);
Assert.True(frame.Length > 0);
bytesReceived += frame.Length;
}
Assert.Equal(DefaultInitialWindowSize, bytesReceived);
// Issue another read. It shouldn't complete yet. Wait a brief period of time to ensure it doesn't complete.
Task<Frame> readFrameTask = connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
await Task.Delay(500);
Assert.False(readFrameTask.IsCompleted);
// Change SETTINGS_INITIAL_WINDOW_SIZE to 0. This will make the client's credit go negative.
await connection.ExpectSettingsAckAsync();
await connection.WriteFrameAsync(new SettingsFrame(new SettingsEntry { SettingId = SettingId.InitialWindowSize, Value = 0 }));
await Task.Delay(500);
Assert.False(readFrameTask.IsCompleted);
// Increase stream window by one. Client credit will still be negative.
await connection.WriteFrameAsync(new WindowUpdateFrame(1, streamId));
await Task.Delay(500);
Assert.False(readFrameTask.IsCompleted);
// Change SETTINGS_INITIAL_WINDOW_SIZE to 1. Client credit will still be negative.
await connection.ExpectSettingsAckAsync();
await connection.WriteFrameAsync(new SettingsFrame(new SettingsEntry { SettingId = SettingId.InitialWindowSize, Value = 1 }));
await Task.Delay(500);
Assert.False(readFrameTask.IsCompleted);
// Increase stream window so client credit will be 0.
await connection.WriteFrameAsync(new WindowUpdateFrame(DefaultInitialWindowSize - 2, streamId));
await Task.Delay(500);
Assert.False(readFrameTask.IsCompleted);
// Increase stream window by one, so client can now send a single byte.
await connection.WriteFrameAsync(new WindowUpdateFrame(1, streamId));
frame = await readFrameTask;
Assert.Equal(FrameType.Data, frame.Type);
Assert.Equal(1, frame.Length);
bytesReceived++;
// Issue another read and ensure it doesn't complete yet.
readFrameTask = connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
await Task.Delay(500);
Assert.False(readFrameTask.IsCompleted);
// Increase SETTINGS_INITIAL_WINDOW_SIZE to 2, so client can now send a single byte.
await connection.ExpectSettingsAckAsync();
await connection.WriteFrameAsync(new SettingsFrame(new SettingsEntry { SettingId = SettingId.InitialWindowSize, Value = 2 }));
frame = await readFrameTask;
Assert.Equal(FrameType.Data, frame.Type);
Assert.Equal(1, frame.Length);
bytesReceived++;
// Issue another read and ensure it doesn't complete yet.
readFrameTask = connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
await Task.Delay(500);
Assert.False(readFrameTask.IsCompleted);
// Increase SETTINGS_INITIAL_WINDOW_SIZE to be enough that the client can send the rest of the content.
await connection.ExpectSettingsAckAsync();
await connection.WriteFrameAsync(new SettingsFrame(new SettingsEntry { SettingId = SettingId.InitialWindowSize, Value = ContentSize - (DefaultInitialWindowSize - 1) }));
frame = await readFrameTask;
Assert.Equal(streamId, frame.StreamId);
Assert.Equal(FrameType.Data, frame.Type);
Assert.Equal(FrameFlags.None, frame.Flags);
Assert.True(frame.Length > 0);
bytesReceived += frame.Length;
// Read to end of stream
bytesReceived += await ReadToEndOfStream(connection, streamId);
Assert.Equal(ContentSize, bytesReceived);
await connection.SendDefaultResponseAsync(streamId);
HttpResponseMessage response = await clientTask;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
public static IEnumerable<object[]> KeepAliveTestDataSource()
{
yield return new object[] { Timeout.InfiniteTimeSpan, HttpKeepAlivePingPolicy.Always, false };
yield return new object[] { TimeSpan.FromSeconds(1), HttpKeepAlivePingPolicy.WithActiveRequests, false };
yield return new object[] { TimeSpan.FromSeconds(1), HttpKeepAlivePingPolicy.Always, false };
yield return new object[] { TimeSpan.FromSeconds(1), HttpKeepAlivePingPolicy.WithActiveRequests, true };
}
[OuterLoop("Significant delay.")]
[MemberData(nameof(KeepAliveTestDataSource))]
[ConditionalTheory(nameof(SupportsAlpn))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/41929")]
public async Task Http2_PingKeepAlive(TimeSpan keepAlivePingDelay, HttpKeepAlivePingPolicy keepAlivePingPolicy, bool expectRequestFail)
{
TimeSpan pingTimeout = TimeSpan.FromSeconds(5);
// Simulate failure by delaying the pong, otherwise send it immediately.
TimeSpan pongDelay = expectRequestFail ? pingTimeout * 2 : TimeSpan.Zero;
// Pings are send only if KeepAlivePingDelay is not infinite.
bool expectStreamPing = keepAlivePingDelay != Timeout.InfiniteTimeSpan;
// Pings (regardless ongoing communication) are send only if sending is on and policy is set to always.
bool expectPingWithoutStream = expectStreamPing && keepAlivePingPolicy == HttpKeepAlivePingPolicy.Always;
TaskCompletionSource serverFinished = new TaskCompletionSource();
await Http2LoopbackServer.CreateClientAndServerAsync(
async uri =>
{
SocketsHttpHandler handler = new SocketsHttpHandler()
{
KeepAlivePingTimeout = pingTimeout,
KeepAlivePingPolicy = keepAlivePingPolicy,
KeepAlivePingDelay = keepAlivePingDelay
};
handler.SslOptions.RemoteCertificateValidationCallback = delegate { return true; };
using HttpClient client = new HttpClient(handler);
client.DefaultRequestVersion = HttpVersion.Version20;
// Warmup request to create connection.
await client.GetStringAsync(uri);
// Request under the test scope.
if (expectRequestFail)
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStringAsync(uri));
// As stream is closed we don't want to continue with sending data.
return;
}
else
{
await client.GetStringAsync(uri);
}
// Let connection live until server finishes.
try
{
await serverFinished.Task.WaitAsync(pingTimeout * 3);
}
catch (TimeoutException) { }
},
async server =>
{
using Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
Task<PingFrame> receivePingTask = expectStreamPing ? connection.ExpectPingFrameAsync() : null;
// Warmup the connection.
int streamId1 = await connection.ReadRequestHeaderAsync();
await connection.SendDefaultResponseAsync(streamId1);
// Request under the test scope.
int streamId2 = await connection.ReadRequestHeaderAsync();
// Test ping with active stream.
if (!expectStreamPing)
{
await Assert.ThrowsAsync<OperationCanceledException>(() => connection.ReadPingAsync(pingTimeout));
}
else
{
PingFrame ping;
if (receivePingTask != null && receivePingTask.IsCompleted)
{
ping = await receivePingTask;
}
else
{
ping = await connection.ReadPingAsync(pingTimeout);
}
if (pongDelay > TimeSpan.Zero)
{
await Task.Delay(pongDelay);
}
await connection.SendPingAckAsync(ping.Data);
}
// Send response and close the stream.
if (expectRequestFail)
{
await Assert.ThrowsAsync<IOException>(() => connection.SendDefaultResponseAsync(streamId2));
// As stream is closed we don't want to continue with sending data.
return;
}
await connection.SendDefaultResponseAsync(streamId2);
// Test ping with no active stream.
if (expectPingWithoutStream)
{
PingFrame ping = await connection.ReadPingAsync(pingTimeout);
await connection.SendPingAckAsync(ping.Data);
}
else
{
// If the pings were recently coming, just give the connection time to clear up streams
// and still accept one stray ping.
if (expectStreamPing)
{
try
{
await connection.ReadPingAsync(pingTimeout);
}
catch (OperationCanceledException) { } // if it failed once, it will fail again
}
await Assert.ThrowsAsync<OperationCanceledException>(() => connection.ReadPingAsync(pingTimeout));
}
serverFinished.SetResult();
await connection.WaitForClientDisconnectAsync(true);
});
}
[OuterLoop("Uses Task.Delay")]
[ConditionalFact(nameof(SupportsAlpn))]
public async Task Http2_MaxConcurrentStreams_LimitEnforced()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
connection.IgnoreWindowUpdates();
// Process first request and send response.
int streamId = await connection.ReadRequestHeaderAsync();
await connection.SendDefaultResponseAsync(streamId);
HttpResponseMessage response = await sendTask;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Change MaxConcurrentStreams setting and wait for ack.
// (We don't want to send any new requests until we receive the ack, otherwise we may have a timing issue.)
SettingsFrame settingsFrame = new SettingsFrame(new SettingsEntry { SettingId = SettingId.MaxConcurrentStreams, Value = 0 });
await connection.WriteFrameAsync(settingsFrame);
Frame settingsAckFrame = await connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
Assert.Equal(FrameType.Settings, settingsAckFrame.Type);
Assert.Equal(FrameFlags.Ack, settingsAckFrame.Flags);
// Issue two more requests. We shouldn't send either of them.
sendTask = client.GetAsync(server.Address);
Task<HttpResponseMessage> sendTask2 = client.GetAsync(server.Address);
// Issue another read. It shouldn't complete yet. Wait a brief period of time to ensure it doesn't complete.
Task<Frame> readFrameTask = connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
await Task.Delay(500);
Assert.False(readFrameTask.IsCompleted);
// Change MaxConcurrentStreams again to allow a single request to come through.
await connection.ExpectSettingsAckAsync();
settingsFrame = new SettingsFrame(new SettingsEntry { SettingId = SettingId.MaxConcurrentStreams, Value = 1 });
await connection.WriteFrameAsync(settingsFrame);
// First request should be sent
Frame frame = await readFrameTask;
Assert.Equal(FrameType.Headers, frame.Type);
streamId = frame.StreamId;
// Issue another read. Second request should not be sent yet.
readFrameTask = connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
await Task.Delay(500);
Assert.False(readFrameTask.IsCompleted);
// Send response for first request
await connection.SendDefaultResponseAsync(streamId);
response = await sendTask;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Second request should be sent now
frame = await readFrameTask;
Assert.Equal(FrameType.Headers, frame.Type);
streamId = frame.StreamId;
// Send response for second request
await connection.SendDefaultResponseAsync(streamId);
response = await sendTask;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[OuterLoop("Uses Task.Delay")]
[ConditionalFact(nameof(SupportsAlpn))]
public async Task Http2_WaitingForStream_Cancellation()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
connection.IgnoreWindowUpdates();
// Process first request and send response.
int streamId = await connection.ReadRequestHeaderAsync();
await connection.SendDefaultResponseAsync(streamId);
HttpResponseMessage response = await sendTask;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Change MaxConcurrentStreams setting and wait for ack.
// (We don't want to send any new requests until we receive the ack, otherwise we may have a timing issue.)
SettingsFrame settingsFrame = new SettingsFrame(new SettingsEntry { SettingId = SettingId.MaxConcurrentStreams, Value = 0 });
await connection.WriteFrameAsync(settingsFrame);
Frame settingsAckFrame = await connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
Assert.Equal(FrameType.Settings, settingsAckFrame.Type);
Assert.Equal(FrameFlags.Ack, settingsAckFrame.Flags);
// Issue a new request, so that we can cancel it while it waits for a stream.
var cts = new CancellationTokenSource();
sendTask = client.GetAsync(server.Address, cts.Token);
// Make sure that the request makes it to the point where it's waiting for a connection.
// It's possible that we'll still initiate a cancellation before it makes it to the queue,
// but it should still behave in the same way if so.
await Task.Delay(500);
Stopwatch stopwatch = Stopwatch.StartNew();
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await sendTask);
// Ensure that the cancellation occurs promptly
stopwatch.Stop();
Assert.True(stopwatch.ElapsedMilliseconds < 30000);
// As the client has not allocated a stream ID when the corresponding request is cancelled,
// we do not send a RST stream frame.
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task Http2_WaitingOnWindowCredit_Cancellation()
{
// The goal of this test is to get the client into the state where it has sent the headers,
// but is waiting on window credit before it will send the body. We then issue a cancellation
// to ensure the request is cancelled as expected.
const int InitialWindowSize = 65535;
const int ContentSize = InitialWindowSize + 1;
HttpClientHandler handler = CreateHttpClientHandler();
handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
var content = new ByteAtATimeContent(ContentSize);
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient(handler))
{
var cts = new CancellationTokenSource();
Task<HttpResponseMessage> clientTask = client.PostAsync(server.Address, content, cts.Token);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
Frame frame = await connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
int streamId = frame.StreamId;
Assert.Equal(FrameType.Headers, frame.Type);
Assert.Equal(FrameFlags.EndHeaders, frame.Flags);
// Receive up to initial window size
int bytesReceived = 0;
while (bytesReceived < InitialWindowSize)
{
frame = await connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
Assert.Equal(streamId, frame.StreamId);
Assert.Equal(FrameType.Data, frame.Type);
Assert.Equal(FrameFlags.None, frame.Flags);
Assert.True(frame.Length > 0);
bytesReceived += frame.Length;
}
// The client is waiting for more credit in order to send the last byte of the
// request body. Test cancellation at this point.
Stopwatch stopwatch = Stopwatch.StartNew();
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await clientTask);
// Ensure that the cancellation occurs promptly
stopwatch.Stop();
Assert.True(stopwatch.ElapsedMilliseconds < 30000);
// The server should receive a RstStream frame.
frame = await connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
Assert.Equal(FrameType.RstStream, frame.Type);
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task Http2_PendingSend_Cancellation()
{
// The goal of this test is to get the client into the state where it is sending content,
// but the send pends because the TCP window is full.
const int InitialWindowSize = 65535;
const int ContentSize = InitialWindowSize * 2; // Double the default TCP window size.
var content = new ByteArrayContent(TestHelper.GenerateRandomContent(ContentSize));
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
var cts = new CancellationTokenSource();
Task<HttpResponseMessage> clientTask = client.PostAsync(server.Address, content, cts.Token);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
Frame frame = await connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
int streamId = frame.StreamId;
Assert.Equal(FrameType.Headers, frame.Type);
Assert.Equal(FrameFlags.EndHeaders, frame.Flags);
// Increase the size of the HTTP/2 Window, so that it is large enough to fill the
// TCP window when we do not perform any reads on the server side.
await connection.WriteFrameAsync(new WindowUpdateFrame(InitialWindowSize, streamId));
// Give the client time to read the window update frame, and for the write to pend.
await Task.Delay(1000);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await clientTask);
}
}
[ConditionalTheory(nameof(SupportsAlpn))]
[OuterLoop("Uses Task.Delay")]
[InlineData(false)]
[InlineData(true)]
public async Task Http2_PendingSend_SendsReset(bool waitForData)
{
var cts = new CancellationTokenSource();
var rstReceived = new TaskCompletionSource<bool>();
string content = new string('*', 300);
var stream = new CustomContent.SlowTestStream(Encoding.UTF8.GetBytes(content), null, count: 60);
await Http2LoopbackServer.CreateClientAndServerAsync(async url =>
{
using (HttpClient client = CreateHttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Version = new Version(2,0);
request.Content = new CustomContent(stream);
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await client.SendAsync(request, cts.Token));
// Wait until the RST_STREAM for the previous request is received before the next request starts.
await rstReceived.Task.WaitAsync(TimeSpan.FromSeconds(60));
// Send another request to verify that connection is still functional.
request = new HttpRequestMessage(HttpMethod.Get, url);
request.Version = new Version(2,0);
await client.SendAsync(request);
}
},
async server =>
{
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
(int streamId, HttpRequestData requestData) = await connection.ReadAndParseRequestHeaderAsync(readBody : false);
int frameCount = 0;
Frame frame;
do
{
if (frameCount == (waitForData ? 1 : 0)) {
// Cancel client after receiving Headers or part of request body.
cts.Cancel();
}
frame = await connection.ReadFrameAsync(TestHelper.PassingTestTimeout);
Assert.NotNull(frame); // We should get Rst before closing connection.
Assert.Equal(0, (int)(frame.Flags & FrameFlags.EndStream));
frameCount++;
} while (frame.Type != FrameType.RstStream);
Assert.Equal(1, frame.StreamId);
rstReceived.SetResult(true);
frame = null;
(streamId, requestData) = await connection.ReadAndParseRequestHeaderAsync();
await connection.SendResponseHeadersAsync(streamId, endStream: false, HttpStatusCode.OK);
await connection.SendResponseBodyAsync(streamId, Encoding.ASCII.GetBytes($"Http2_PendingSend_SendsReset(waitForData: {waitForData})"), isFinal: false);
// Wait for any lingering frames or extra reset frames.
try
{
frame = await connection.ReadFrameAsync(TimeSpan.FromMilliseconds(1000));
}
catch (System.OperationCanceledException) { };
Assert.Null(frame); // Make sure we do not get any frames after getting Rst.
await connection.SendResponseBodyAsync(streamId, Encoding.ASCII.GetBytes("final"), isFinal: true);
await connection.WaitForConnectionShutdownAsync();
});
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Http2_PendingReceive_SendsReset(bool doRead)
{
var cts = new CancellationTokenSource();
var doCancel = new TaskCompletionSource();
HttpResponseMessage response = null;
using (HttpClient client = CreateHttpClient())
{
await Http2LoopbackServer.CreateClientAndServerAsync(async url =>
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Version = new Version(2,0);
response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token);
using (Stream stream = await response.Content.ReadAsStreamAsync())
{
byte[] buffer = new byte[100];
if (doRead)
{
// Start reading response as variation.
_ = await stream.ReadAsync(buffer, cts.Token);
}
doCancel.SetResult();
_output.WriteLine($"{DateTime.Now} cancellation requested.");
// Keep reading response.
if (doRead)
{
try
{
while (true)
{
_ = await stream.ReadAsync(buffer, cts.Token);
}
}
catch (OperationCanceledException) { };
}
}
},
async server =>
{
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
(int streamId, HttpRequestData requestData) = await connection.ReadAndParseRequestHeaderAsync(readBody : false);
_output.WriteLine($"{DateTime.Now} Connection established");
await connection.SendResponseHeadersAsync(streamId, endStream: false, HttpStatusCode.OK);
// Start streaming response
DataFrame dataFrame = new DataFrame(new byte[100], FrameFlags.None, 0, streamId);
await connection.WriteFrameAsync(dataFrame);
// Wait for client to start processing response and cancel it.
await doCancel.Task;
cts.Cancel();
_output.WriteLine($"{DateTime.Now} HttpRequest was canceled");
Frame frame;
do
{
frame = await connection.ReadFrameAsync(TestHelper.PassingTestTimeout);
Assert.NotNull(frame); // We should get Rst before closing connection.
Assert.Equal(0, (int)(frame.Flags & FrameFlags.EndStream));
} while (frame.Type != FrameType.RstStream);
});
}
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task Http2Connection_Should_Wrap_HttpContent_InvalidOperationException()
{
// test for https://github.com/dotnet/runtime/issues/30187
var throwingContent = new ThrowingContent(() => new InvalidOperationException());
var tcs = new TaskCompletionSource();
await Http2LoopbackServer.CreateClientAndServerAsync(async url =>
{
using (HttpClient client = CreateHttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Version = new Version(2, 0);
request.Content = throwingContent;
HttpRequestException exn = await Assert.ThrowsAnyAsync<HttpRequestException>(async () => await client.SendAsync(request));
Assert.IsType<InvalidOperationException>(exn.InnerException);
await tcs.Task; // prevent disposal of client until server has completed operations
}
},
async server =>
{
await server.EstablishConnectionAsync();
tcs.SetResult();
});
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task Http2Connection_Should_Not_Wrap_HttpContent_CustomException()
{
// Assert existing HttpConnection behaviour in which custom HttpContent exception types are surfaced as-is
// c.f. https://github.com/dotnet/runtime/issues/30187#issuecomment-510569836
var throwingContent = new ThrowingContent(() => new CustomException());
var tcs = new TaskCompletionSource();
await Http2LoopbackServer.CreateClientAndServerAsync(async url =>
{
using (HttpClient client = CreateHttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Version = new Version(2, 0);
request.Content = throwingContent;
await Assert.ThrowsAnyAsync<CustomException>(async () => await client.SendAsync(request));
await tcs.Task; // prevent disposal of client until server has completed operations
}
},
async server =>
{
await server.EstablishConnectionAsync();
tcs.SetResult();
});
}
private class CustomException : Exception { }
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task PostAsyncExpect100Continue_SendRequest_Ok(bool send100Continue)
{
await Http2LoopbackServer.CreateClientAndServerAsync(async url =>
{
using (HttpClient client = CreateHttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Version = new Version(2,0);
request.Content = new StringContent(new string('*', 3000));
request.Headers.ExpectContinue = true;
request.Headers.Add("x-test", $"PostAsyncExpect100Continue_SendRequest_Ok({send100Continue}");
HttpResponseMessage response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
},
async server =>
{
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
(int streamId, HttpRequestData requestData) = await connection.ReadAndParseRequestHeaderAsync(readBody : false);
Assert.Equal("100-continue", requestData.GetSingleHeaderValue("Expect"));
if (send100Continue)
{
await connection.SendResponseHeadersAsync(streamId, endStream: false, HttpStatusCode.Continue);
}
await connection.ReadBodyAsync();
await connection.SendResponseHeadersAsync(streamId, endStream: false, HttpStatusCode.OK);
await connection.SendResponseBodyAsync(streamId, Encoding.ASCII.GetBytes("OK"));
await connection.ShutdownIgnoringErrorsAsync(streamId);
});
}
[Fact]
public async Task PostAsyncExpect100Continue_NonSuccessResponse_RequestBodyNotSent()
{
string responseContent = "no no!";
await Http2LoopbackServer.CreateClientAndServerAsync(async url =>
{
using (var handler = new SocketsHttpHandler())
using (HttpClient client = CreateHttpClient(handler))
{
handler.SslOptions.RemoteCertificateValidationCallback = delegate { return true; };
// Increase default Expect: 100-continue timeout to ensure that we don't accidentally fire the timer and send the request body.
handler.Expect100ContinueTimeout = TimeSpan.FromSeconds(300);
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Version = new Version(2,0);
request.VersionPolicy = HttpVersionPolicy.RequestVersionExact;
request.Content = new StringContent(new string('*', 3000));
request.Headers.ExpectContinue = true;
request.Headers.Add("x-test", "PostAsyncExpect100Continue_NonSuccessResponse_RequestBodyNotSent");
HttpResponseMessage response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal(responseContent, await response.Content.ReadAsStringAsync());
}
},
async server =>
{
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
(int streamId, HttpRequestData requestData) = await connection.ReadAndParseRequestHeaderAsync(readBody : false);
Assert.Equal("100-continue", requestData.GetSingleHeaderValue("Expect"));
// Reject content with 403.
await connection.SendResponseHeadersAsync(streamId, endStream: false, HttpStatusCode.Forbidden);
await connection.SendResponseBodyAsync(streamId, Encoding.ASCII.GetBytes(responseContent));
// Client should send empty request body
byte[] requestBody = await connection.ReadBodyAsync(expectEndOfStream:true);
Assert.Null(requestBody);
await connection.ShutdownIgnoringErrorsAsync(streamId);
});
}
class DuplexContent : HttpContent
{
private TaskCompletionSource<Stream> _waitForStream;
private TaskCompletionSource _waitForCompletion;
public DuplexContent()
{
_waitForStream = new TaskCompletionSource<Stream>(TaskCreationOptions.RunContinuationsAsynchronously);
}
protected override bool TryComputeLength(out long length)
{
length = 0;
return false;
}
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
_waitForCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_waitForStream.SetResult(stream);
await _waitForCompletion.Task;
}
public Task<Stream> WaitForStreamAsync()
{
return _waitForStream.Task;
}
public void Complete()
{
_waitForCompletion.SetResult();
}
public void Fail(Exception e)
{
_waitForCompletion.SetException(e);
}
}
private async Task SendAndReceiveResponseDataAsync(Memory<byte> data, Stream responseStream, Http2LoopbackConnection connection, int streamId)
{
byte[] readBuffer = new byte[data.Length];
await connection.SendResponseDataAsync(streamId, data, endStream: false);
int bytesRead = await responseStream.ReadAsync(readBuffer);
Assert.True(data.Span.SequenceEqual(readBuffer));
}
private async Task SendAndReceiveResponseEOFAsync(Stream responseStream, Http2LoopbackConnection connection, int streamId)
{
byte[] readBuffer = new byte[1];
await connection.SendResponseDataAsync(streamId, new byte[] { }, endStream: true);
int bytesRead = await responseStream.ReadAsync(readBuffer);
Assert.Equal(0, bytesRead);
// Another read should still give EOF
bytesRead = await responseStream.ReadAsync(readBuffer);
Assert.Equal(0, bytesRead);
// Dispose the response stream, to ensure that this doesn't affect the request stream
responseStream.Dispose();
// Attempting to read now should throw ObjectDisposedException
await Assert.ThrowsAsync<ObjectDisposedException>(async () => { await responseStream.ReadAsync(readBuffer); });
}
private async Task SendAndReceiveRequestDataAsync(Memory<byte> data, Stream requestStream, Http2LoopbackConnection connection, int streamId)
{
await requestStream.WriteAsync(data);
await requestStream.FlushAsync();
DataFrame dataFrame = (DataFrame)await connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
Assert.True(data.Span.SequenceEqual(dataFrame.Data.Span));
}
private async Task SendAndReceiveRequestEOFAsync(DuplexContent duplexContent, Stream requestStream, Http2LoopbackConnection connection, int streamId)
{
duplexContent.Complete();
DataFrame dataFrame = (DataFrame)await connection.ReadFrameAsync(TimeSpan.FromSeconds(30));
Assert.True(dataFrame.EndStreamFlag);
Assert.Equal(0, dataFrame.Data.Length);
// Attempting to write now should throw ObjectDisposedException
await Assert.ThrowsAsync<ObjectDisposedException>(async () => { await requestStream.WriteAsync(new byte[1]); });
}
[Fact]
public async Task PostAsyncDuplex_ClientSendsEndStream_Success()
{
byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
Http2LoopbackConnection connection;
using (HttpClient client = CreateHttpClient())
{
var duplexContent = new DuplexContent();
var request = new HttpRequestMessage(HttpMethod.Post, server.Address);
request.Version = new Version(2, 0);
request.Content = duplexContent;
Task<HttpResponseMessage> responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
connection = await server.EstablishConnectionAsync();
// Client should have sent the request headers, and the request stream should now be available
Stream requestStream = await duplexContent.WaitForStreamAsync();
// Flush the content stream. Otherwise, the request headers are not guaranteed to be sent.
await requestStream.FlushAsync();
(int streamId, _) = await connection.ReadAndParseRequestHeaderAsync(readBody: false);
// Send data to the server, even before we've received response headers.
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
// Send response headers
await connection.SendResponseHeadersAsync(streamId, endStream: false);
HttpResponseMessage response = await responseTask;
Stream responseStream = await response.Content.ReadAsStreamAsync();
// Send some data back and forth
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
// Complete sending the request body
await SendAndReceiveRequestEOFAsync(duplexContent, requestStream, connection, streamId);
// Send more data to the client
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
// Complete sending the response body
await SendAndReceiveResponseEOFAsync(responseStream, connection, streamId);
}
// On handler dispose, client should shutdown the connection without sending additional frames.
await connection.WaitForClientDisconnectAsync();
}
}
[Fact]
public async Task PostAsyncDuplex_ServerSendsEndStream_Success()
{
byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
Http2LoopbackConnection connection;
using (HttpClient client = CreateHttpClient())
{
var duplexContent = new DuplexContent();
var request = new HttpRequestMessage(HttpMethod.Post, server.Address);
request.Version = new Version(2, 0);
request.Content = duplexContent;
Task<HttpResponseMessage> responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
connection = await server.EstablishConnectionAsync();
// Client should have sent the request headers, and the request stream should now be available
Stream requestStream = await duplexContent.WaitForStreamAsync();
// Flush the content stream. Otherwise, the request headers are not guaranteed to be sent.
await requestStream.FlushAsync();
(int streamId, _) = await connection.ReadAndParseRequestHeaderAsync(readBody: false);
// Send data to the server, even before we've received response headers.
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
// Send response headers
await connection.SendResponseHeadersAsync(streamId, endStream: false);
HttpResponseMessage response = await responseTask;
Stream responseStream = await response.Content.ReadAsStreamAsync();
// Send some data back and forth
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
// Complete sending the response body
await SendAndReceiveResponseEOFAsync(responseStream, connection, streamId);
// Send more data to the server
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
// Complete sending the request body
await SendAndReceiveRequestEOFAsync(duplexContent, requestStream, connection, streamId);
}
// On handler dispose, client should shutdown the connection without sending additional frames.
await connection.WaitForClientDisconnectAsync();
}
}
[Fact]
public async Task PostAsyncDuplex_RequestContentException_ResetsStream()
{
byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
Http2LoopbackConnection connection;
using (HttpClient client = CreateHttpClient())
{
var duplexContent = new DuplexContent();
var request = new HttpRequestMessage(HttpMethod.Post, server.Address);
request.Version = new Version(2, 0);
request.Content = duplexContent;
Task<HttpResponseMessage> responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
connection = await server.EstablishConnectionAsync();
// Client should have sent the request headers, and the request stream should now be available
Stream requestStream = await duplexContent.WaitForStreamAsync();
// Flush the content stream. Otherwise, the request headers are not guaranteed to be sent.
await requestStream.FlushAsync();
(int streamId, _) = await connection.ReadAndParseRequestHeaderAsync(readBody: false);
// Send data to the server, even before we've received response headers.
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
// Send response headers
await connection.SendResponseHeadersAsync(streamId, endStream: false);
HttpResponseMessage response = await responseTask;
Stream responseStream = await response.Content.ReadAsStreamAsync();
// Send some data back and forth
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
// Throw an exception from the request content.
Exception e = new ArithmeticException();
duplexContent.Fail(e);
// Client should set RST_STREAM.
await connection.ReadRstStreamAsync(streamId);
// Trying to read on the response stream should fail now, and client should ignore any data received
await Assert.ThrowsAsync<IOException>(async () => await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId));
}
// On handler dispose, client should shutdown the connection without sending additional frames.
await connection.WaitForClientDisconnectAsync();
}
}
[Fact]
public async Task PostAsyncDuplex_RequestContentExceptionAfterResponseEndReceivedButBeforeConsumed_ResetsStreamAndThrowsOnResponseStreamRead()
{
byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
Http2LoopbackConnection connection;
using (HttpClient client = CreateHttpClient())
{
var duplexContent = new DuplexContent();
var request = new HttpRequestMessage(HttpMethod.Post, server.Address);
request.Version = new Version(2, 0);
request.Content = duplexContent;
Task<HttpResponseMessage> responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
connection = await server.EstablishConnectionAsync();
// Client should have sent the request headers, and the request stream should now be available
Stream requestStream = await duplexContent.WaitForStreamAsync();
// Flush the content stream. Otherwise, the request headers are not guaranteed to be sent.
await requestStream.FlushAsync();
(int streamId, _) = await connection.ReadAndParseRequestHeaderAsync(readBody: false);
// Send data to the server, even before we've received response headers.
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
// Send response headers
await connection.SendResponseHeadersAsync(streamId, endStream: false);
HttpResponseMessage response = await responseTask;
Stream responseStream = await response.Content.ReadAsStreamAsync();
// Send some data back and forth
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
// Send data on response stream and complete it, but don't read it on the client yet
await connection.SendResponseDataAsync(streamId, contentBytes, endStream: true);
// Pingpong to ensure it's processed by client
await connection.PingPong();
// Throw an exception from the request content.
Exception e = new ArithmeticException();
duplexContent.Fail(e);
// Client should set RST_STREAM.
await connection.ReadRstStreamAsync(streamId);
// Trying to read on the response stream should fail now, and client should ignore any data received
await Assert.ThrowsAsync<IOException>(async () => await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId));
}
// On handler dispose, client should shutdown the connection without sending additional frames.
await connection.WaitForClientDisconnectAsync();
}
}
[OuterLoop("Uses Task.Delay")]
[Fact]
public async Task PostAsyncDuplex_CancelledBeforeResponseHeadersReceived_ResetsStream()
{
byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
Http2LoopbackConnection connection;
using (HttpClient client = CreateHttpClient())
{
var duplexContent = new DuplexContent();
var request = new HttpRequestMessage(HttpMethod.Post, server.Address);
request.Version = new Version(2, 0);
request.Content = duplexContent;
var cancellationTokenSource = new CancellationTokenSource();
Task<HttpResponseMessage> responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationTokenSource.Token);
connection = await server.EstablishConnectionAsync();
// Client should have sent the request headers, and the request stream should now be available
Stream requestStream = await duplexContent.WaitForStreamAsync();
// Flush the content stream. Otherwise, the request headers are not guaranteed to be sent.
await requestStream.FlushAsync();
(int streamId, _) = await connection.ReadAndParseRequestHeaderAsync(readBody: false);
// Send data to the server, even before we've received response headers.
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
// Cancel the request
cancellationTokenSource.Cancel();
// Cancellation may not propagate immediately. So wait a brief time to try to ensure it propagates.
await Task.Delay(3000);
// Attempting to write on the request body should now fail with OperationCanceledException.
Exception e = await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId); });
// Propagate the exception to the request stream serialization task.
// This allows the request processing to complete.
duplexContent.Fail(e);
// Client should set RST_STREAM.
await connection.ReadRstStreamAsync(streamId);
// Request should fail.
await Assert.ThrowsAsync<TaskCanceledException>(() => responseTask);
}
// On handler dispose, client should shutdown the connection without sending additional frames.
await connection.WaitForClientDisconnectAsync();
}
}
[Fact]
public async Task PostAsyncDuplex_ServerResetsStream_Throws()
{
byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
Http2LoopbackConnection connection;
using (HttpClient client = CreateHttpClient())
{
var duplexContent = new DuplexContent();
var request = new HttpRequestMessage(HttpMethod.Post, server.Address);
request.Version = new Version(2, 0);
request.Content = duplexContent;
Task<HttpResponseMessage> responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
connection = await server.EstablishConnectionAsync();
// Client should have sent the request headers, and the request stream should now be available
Stream requestStream = await duplexContent.WaitForStreamAsync();
// Flush the content stream. Otherwise, the request headers are not guaranteed to be sent.
await requestStream.FlushAsync();
(int streamId, _) = await connection.ReadAndParseRequestHeaderAsync(readBody: false);
// Send data to the server, even before we've received response headers.
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
// Send response headers
await connection.SendResponseHeadersAsync(streamId, endStream: false);
HttpResponseMessage response = await responseTask;
Stream responseStream = await response.Content.ReadAsStreamAsync();
// Send some data back and forth
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
// Send RST_STREAM to client.
await connection.WriteFrameAsync(new RstStreamFrame(FrameFlags.None, (int)ProtocolErrors.ENHANCE_YOUR_CALM, streamId));
// Trying to read on the response stream should fail now, and client should ignore any data received
await AssertProtocolErrorForIOExceptionAsync(SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId), ProtocolErrors.ENHANCE_YOUR_CALM);
// Attempting to write on the request body should now fail with OperationCanceledException.
Exception e = await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId); });
// Propagate the exception to the request stream serialization task.
// This allows the request processing to complete.
duplexContent.Fail(e);
}
// On handler dispose, client should shutdown the connection without sending additional frames.
await connection.WaitForClientDisconnectAsync();
}
}
[OuterLoop("Uses Task.Delay")]
[Fact]
public async Task PostAsyncDuplex_DisposeResponseBodyBeforeEnd_ResetsStreamAndThrowsOnRequestStreamWriteAndResponseStreamRead()
{
byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
Http2LoopbackConnection connection;
using (HttpClient client = CreateHttpClient())
{
var duplexContent = new DuplexContent();
var request = new HttpRequestMessage(HttpMethod.Post, server.Address);
request.Version = new Version(2, 0);
request.Content = duplexContent;
Task<HttpResponseMessage> responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
connection = await server.EstablishConnectionAsync();
// Client should have sent the request headers, and the request stream should now be available
Stream requestStream = await duplexContent.WaitForStreamAsync();
// Flush the content stream. Otherwise, the request headers are not guaranteed to be sent.
await requestStream.FlushAsync();
(int streamId, _) = await connection.ReadAndParseRequestHeaderAsync(readBody: false);
// Send data to the server, even before we've received response headers.
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
// Send response headers
await connection.SendResponseHeadersAsync(streamId, endStream: false);
HttpResponseMessage response = await responseTask;
Stream responseStream = await response.Content.ReadAsStreamAsync();
// Send some data back and forth
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
// Dispose the response stream.
responseStream.Dispose();
// Trying to read on the response stream should fail now, and client should ignore any data received
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId));
// Cancellation on the request body may not propagate immediately. So wait a brief time to try to ensure it propagates.
await Task.Delay(500);
// Attempting to write on the request body should now fail with OperationCanceledException.
Exception e = await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId); });
// Propagate the exception to the request stream serialization task.
// This allows the request processing to complete.
duplexContent.Fail(e);
// Client should set RST_STREAM.
await connection.ReadRstStreamAsync(streamId);
}
// On handler dispose, client should shutdown the connection without sending additional frames.
await connection.WaitForClientDisconnectAsync();
}
}
[OuterLoop("Uses Task.Delay")]
[Fact]
public async Task PostAsyncDuplex_DisposeResponseBodyAfterEndReceivedButBeforeConsumed_ResetsStreamAndThrowsOnRequestStreamWriteAndResponseStreamRead()
{
byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
Http2LoopbackConnection connection;
using (HttpClient client = CreateHttpClient())
{
var duplexContent = new DuplexContent();
var request = new HttpRequestMessage(HttpMethod.Post, server.Address);
request.Version = new Version(2, 0);
request.Content = duplexContent;
Task<HttpResponseMessage> responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
connection = await server.EstablishConnectionAsync();
// Client should have sent the request headers, and the request stream should now be available
Stream requestStream = await duplexContent.WaitForStreamAsync();
// Flush the content stream. Otherwise, the request headers are not guaranteed to be sent.
await requestStream.FlushAsync();
(int streamId, _) = await connection.ReadAndParseRequestHeaderAsync(readBody: false);
// Send data to the server, even before we've received response headers.
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
// Send response headers
await connection.SendResponseHeadersAsync(streamId, endStream: false);
HttpResponseMessage response = await responseTask;
Stream responseStream = await response.Content.ReadAsStreamAsync();
// Send some data back and forth
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
// Send data on response stream and completed it, but don't read it on the client yet
await connection.SendResponseDataAsync(streamId, contentBytes, endStream: true);
// Pingpong to ensure it's processed by client
await connection.PingPong();
// Dispose the response stream.
responseStream.Dispose();
// Trying to read on the response stream should fail now, and client should ignore any data received
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId));
// Cancellation on the request body may not propagate immediately. So wait a brief time to try to ensure it propagates.
await Task.Delay(500);
// Attempting to write on the request body should now fail with OperationCanceledException.
Exception e = await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId); });
// Propagate the exception to the request stream serialization task.
// This allows the request processing to complete.
duplexContent.Fail(e);
// Client should set RST_STREAM.
await connection.ReadRstStreamAsync(streamId);
}
// On handler dispose, client should shutdown the connection without sending additional frames.
await connection.WaitForClientDisconnectAsync();
}
}
[OuterLoop("Uses Task.Delay")]
[Fact]
public async Task PostAsyncDuplex_FinishRequestBodyAndDisposeResponseBodyAfterEndReceivedButBeforeConsumed_DoesNotResetStream()
{
byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
Http2LoopbackConnection connection;
using (HttpClient client = CreateHttpClient())
{
var duplexContent = new DuplexContent();
var request = new HttpRequestMessage(HttpMethod.Post, server.Address);
request.Version = new Version(2, 0);
request.Content = duplexContent;
Task<HttpResponseMessage> responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
connection = await server.EstablishConnectionAsync();
// Client should have sent the request headers, and the request stream should now be available
Stream requestStream = await duplexContent.WaitForStreamAsync();
// Flush the content stream. Otherwise, the request headers are not guaranteed to be sent.
await requestStream.FlushAsync();
(int streamId, _) = await connection.ReadAndParseRequestHeaderAsync(readBody: false);
// Send data to the server, even before we've received response headers.
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
// Send response headers
await connection.SendResponseHeadersAsync(streamId, endStream: false);
HttpResponseMessage response = await responseTask;
Stream responseStream = await response.Content.ReadAsStreamAsync();
// Send some data back and forth
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
// Complete request stream.
await SendAndReceiveRequestEOFAsync(duplexContent, requestStream, connection, streamId);
// Send data on response stream and completed it, but don't read it on the client yet
await connection.SendResponseDataAsync(streamId, contentBytes, endStream: true);
// Pingpong to ensure it's processed by client
await connection.PingPong();
// Dispose the response stream.
responseStream.Dispose();
// Trying to read on the response stream should fail now, and client should ignore any data received
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await SendAndReceiveResponseDataAsync(contentBytes, responseStream, connection, streamId));
// Client should NOT send RST_STREAM. The stream was completed succesfully, but the remaining response data was discarded.
}
// On handler dispose, client should shutdown the connection without sending additional frames.
await connection.WaitForClientDisconnectAsync();
}
}
[Fact]
public async Task PostAsyncDuplex_ServerCompletesResponseBodyThenResetsStreamWithNoError_SuccessAndRequestBodyCancelled()
{
// Per section 8.1 of the RFC:
// Receiving RST_STREAM with NO_ERROR after receiving EndStream on the response body is a special case.
// We should stop sending the request body, but treat the request as successful and
// return the completed response body to the user.
byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
Http2LoopbackConnection connection;
using (HttpClient client = CreateHttpClient())
{
var duplexContent = new DuplexContent();
var request = new HttpRequestMessage(HttpMethod.Post, server.Address);
request.Version = new Version(2, 0);
request.Content = duplexContent;
Task<HttpResponseMessage> responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
connection = await server.EstablishConnectionAsync();
// Client should have sent the request headers, and the request stream should now be available
Stream requestStream = await duplexContent.WaitForStreamAsync();
// Flush the content stream. Otherwise, the request headers are not guaranteed to be sent.
await requestStream.FlushAsync();
(int streamId, _) = await connection.ReadAndParseRequestHeaderAsync(readBody: false);
// Send data to the server, even before we've received response headers.
await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId);
// Send response headers
await connection.SendResponseHeadersAsync(streamId, endStream: false);
HttpResponseMessage response = await responseTask;
Stream responseStream = await response.Content.ReadAsStreamAsync();
// Send response body and complete response
await connection.SendResponseDataAsync(streamId, contentBytes, endStream: true);
// Send RST_STREAM to client with error = NO_ERROR.
await connection.WriteFrameAsync(new RstStreamFrame(FrameFlags.None, (int)ProtocolErrors.NO_ERROR, streamId));
// Ensure client has processed the RST_STREAM.
await connection.PingPong();
// Attempting to write on the request body should now fail with OperationCanceledException.
Exception e = await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { await SendAndReceiveRequestDataAsync(contentBytes, requestStream, connection, streamId); });
// Propagate the exception to the request stream serialization task.
// This allows the request processing to complete.
duplexContent.Fail(e);
// We should receive the response body and EOF.
byte[] readBuffer = new byte[contentBytes.Length];
int bytesRead = await responseStream.ReadAsync(readBuffer);
Assert.True(contentBytes.SequenceEqual(readBuffer));
bytesRead = await responseStream.ReadAsync(readBuffer);
Assert.Equal(0, bytesRead);
}
// On handler dispose, client should shutdown the connection without sending additional frames.
await connection.WaitForClientDisconnectAsync();
}
}
[Fact]
public async Task PostAsyncNonDuplex_ServerCompletesResponseBodyThenResetsStreamWithNoError_SuccessAndRequestBodyCancelled()
{
// Per section 8.1 of the RFC:
// Receiving RST_STREAM with NO_ERROR after receiving EndStream on the response body is a special case.
// We should stop sending the request body, but treat the request as successful and
// return the completed response body to the user.
byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
Http2LoopbackConnection connection;
using (HttpClient client = CreateHttpClient())
{
// We want non-duplex content, so use ByteArrayContent,
// but make it large enough to ensure that the content can't be fully sent because of flow control limitations.
// This allows us to validate that the content is actually canceled, not just fully sent and completed.
const int ContentSize = 100_000;
var requestContent = new ByteArrayContent(TestHelper.GenerateRandomContent(ContentSize));
var request = new HttpRequestMessage(HttpMethod.Post, server.Address);
request.Version = new Version(2, 0);
request.Content = requestContent;
Task<HttpResponseMessage> responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
connection = await server.EstablishConnectionAsync();
(int streamId, _) = await connection.ReadAndParseRequestHeaderAsync(readBody: false);
// Send full response
await connection.SendResponseHeadersAsync(streamId, endStream: false);
await connection.SendResponseDataAsync(streamId, contentBytes, endStream: true);
// Send RST_STREAM to client with error = NO_ERROR.
await connection.WriteFrameAsync(new RstStreamFrame(FrameFlags.None, (int)ProtocolErrors.NO_ERROR, streamId));
// Response should now complete successfully
HttpResponseMessage response = await responseTask;
Assert.Equal("Hello world", await response.Content.ReadAsStringAsync());
}
// On handler dispose, client should shutdown the connection. Ignore any request stream frames already sent.
await connection.WaitForClientDisconnectAsync(ignoreUnexpectedFrames: true);
}
}
[Theory]
[InlineData(true, HttpStatusCode.Forbidden)]
[InlineData(false, HttpStatusCode.Forbidden)]
[InlineData(true, HttpStatusCode.OK)]
[InlineData(false, HttpStatusCode.OK)]
[OuterLoop("Uses Task.Delay")]
public async Task SendAsync_ConcurentSendReceive_Ok(bool shouldWaitForRequestBody, HttpStatusCode responseCode)
{
string requestContent = new string('*', 300);
const string responseContent = "SendAsync_ConcurentSendReceive_Ok";
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
Http2LoopbackConnection connection;
using (HttpClient client = CreateHttpClient())
{
var duplexContent = new DuplexContent();
var request = new HttpRequestMessage(HttpMethod.Post, server.Address);
request.Version = new Version(2, 0);
request.Content = duplexContent;
Task<HttpResponseMessage> responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
connection = await server.EstablishConnectionAsync();
// Client should have sent the request headers, and the request stream should now be available
Stream requestStream = await duplexContent.WaitForStreamAsync();
// Flush the content stream. Otherwise, the request headers are not guaranteed to be sent.
await requestStream.FlushAsync();
(int streamId, HttpRequestData requestData) = await connection.ReadAndParseRequestHeaderAsync(readBody : false);
// Client finished sending request headers and we received them.
// Send request body.
await requestStream.WriteAsync(Encoding.UTF8.GetBytes(requestContent));
duplexContent.Complete();
if (shouldWaitForRequestBody)
{
// Read body first before sending back any response in non-duplex variant.
await connection.ReadBodyAsync();
}
// Send response headers
await connection.SendResponseHeadersAsync(streamId, endStream: false, responseCode);
HttpResponseMessage response = await responseTask;
Assert.Equal(responseCode, response.StatusCode);
await connection.SendResponseDataAsync(streamId, Encoding.ASCII.GetBytes(responseContent), endStream: false);
if (!shouldWaitForRequestBody)
{
// In duplex case response is sent before reading request body.
await connection.ReadBodyAsync();
}
// Send trailing headers for good measure and close stream.
var headers = new HttpHeaderData[] { new HttpHeaderData("x-last", "done") };
await connection.SendResponseHeadersAsync(streamId, endStream: true, isTrailingHeader : true, headers: headers);
// Finish reading response body and verify it for all cases.
string responseBody = await response.Content.ReadAsStringAsync();
Assert.Equal(responseContent, responseBody);
}
// On handler dispose, client should shutdown the connection without sending additional frames.
await connection.WaitForClientDisconnectAsync();
}
}
[Fact]
[OuterLoop("Uses Task.Delay")]
public async Task SendAsync_ConcurentSendReceive_Fail()
{
TaskCompletionSource<bool> tsc = new TaskCompletionSource<bool>();
string requestContent = new string('*', 300);
const string responseContent = "SendAsync_ConcurentSendReceive_Fail";
var stream = new CustomContent.SlowTestStream(Encoding.UTF8.GetBytes(requestContent), tsc, trigger : 1, count : 50);
bool stopSending = false;
await Http2LoopbackServer.CreateClientAndServerAsync(async url =>
{
using (HttpClient client = CreateHttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Version = new Version(2,0);
request.Content = new CustomContent(stream);
// This should fail either while getting response headers or while reading response body.
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
// Wait for request body start streaming.
await tsc.Task.ConfigureAwait(false);
// and inject distinct exception on request stream.
stream.SetException(new ArithmeticException("Injected test exception"));
HttpRequestException e = await Assert.ThrowsAsync<HttpRequestException>(() => response.Content.ReadAsStringAsync());
Assert.IsType<IOException>(e.InnerException);
stopSending = true;
}
},
async server =>
{
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
(int streamId, HttpRequestData requestData) = await connection.ReadAndParseRequestHeaderAsync(readBody : false);
await connection.SendResponseHeadersAsync(streamId, endStream: false, HttpStatusCode.OK);
// Wait for client so start sending body.
await tsc.Task.ConfigureAwait(false);
int maxCount = 120;
while (!stopSending && maxCount != 0)
{
try
{
await connection.SendResponseDataAsync(streamId, Encoding.ASCII.GetBytes(responseContent), endStream: false);
}
catch (IOException)
{
// When client sets stopSending, client will be disposed and sending may fail.
Assert.True(stopSending);
break;
}
await Task.Delay(500);
maxCount --;
}
// We should not reach retry limit without failing.
Assert.NotEqual(0, maxCount);
try
{
await connection.SendGoAway(streamId);
await connection.WaitForConnectionShutdownAsync();
}
catch { };
});
}
[Fact]
[OuterLoop("Waits for seconds for events that shouldn't happen")]
public async Task SendAsync_StreamContentRequestBody_WaitsForRequestBodyToComplete()
{
var waitToSendRequestBody = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var sendAsyncCompleted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
// Create a content stream that will wait for a signal before it dribbles out some request content.
int sent = 0;
var stream = new DelegateStream(
canReadFunc: () => true,
readAsyncFunc: async (buffer, offset, count, token) =>
{
await waitToSendRequestBody.Task;
return sent++ < 10 ? 1 : 0;
});
await Http2LoopbackServer.CreateClientAndServerAsync(async url =>
{
using (HttpClient client = CreateHttpClient())
{
// Connect to the server and SendAsync.
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Version = new Version(2, 0);
request.Content = new StreamContent(stream);
Task<HttpResponseMessage> sendAsyncTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
// Wait a bit, and confirm SendAsync hasn't completed yet (because the request content can't have finished yet).
await Task.Delay(1000);
Assert.False(sendAsyncTask.IsCompleted);
// Now let the request content go. The SendAsync task should complete quickly.
waitToSendRequestBody.SetResult();
using (HttpResponseMessage r = await sendAsyncTask)
{
// Wake up the server.
sendAsyncCompleted.SetResult();
}
}
},
async server =>
{
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
(int streamId, HttpRequestData requestData) = await connection.ReadAndParseRequestHeaderAsync().ConfigureAwait(false);
await connection.SendResponseHeadersAsync(streamId);
await sendAsyncCompleted.Task;
await connection.WaitForConnectionShutdownAsync();
});
}
[ConditionalFact(nameof(SupportsAlpn))]
public async Task Http2_ProtocolMismatch_Throws()
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
using (HttpClient client = CreateHttpClient())
{
// Create HTTP/1.1 loopback server and advertise HTTP2 via ALPN.
await LoopbackServer.CreateServerAsync(async (server, uri) =>
{
// Convert http to https as we are going to negotiate TLS.
Task<string> requestTask = client.GetStringAsync(uri.ToString().Replace("http://", "https://"));
await server.AcceptConnectionAsync(async connection =>
{
// negotiate TLS with ALPN H/2
var sslStream = new SslStream(connection.Stream, false, delegate { return true; });
SslServerAuthenticationOptions options = new SslServerAuthenticationOptions();
options.ServerCertificate = Net.Test.Common.Configuration.Certificates.GetServerCertificate();
options.ApplicationProtocols = new List<SslApplicationProtocol>() { SslApplicationProtocol.Http2 };
options.ApplicationProtocols.Add(SslApplicationProtocol.Http2);
// Negotiate TLS.
await sslStream.AuthenticateAsServerAsync(options, CancellationToken.None).ConfigureAwait(false);
// Send back HTTP/1.1 response
await sslStream.WriteAsync(Encoding.ASCII.GetBytes("HTTP/1.1 400 Unrecognized request\r\n\r\n"), CancellationToken.None);
});
Exception e = await Assert.ThrowsAsync<HttpRequestException>(() => requestTask);
Assert.NotNull(e.InnerException);
Assert.False(e.InnerException is ObjectDisposedException);
});
}
}
// rfc7540 8.1.2.3.
[ConditionalFact(nameof(SupportsAlpn))]
public async Task Http2GetAsync_MultipleStatusHeaders_Throws()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
IList<HttpHeaderData> headers = new HttpHeaderData[] { new HttpHeaderData(":status", "300"), new HttpHeaderData("x-test", "Http2GetAsync_MultipleStatusHeaders_Throws") };
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
await connection.SendResponseHeadersAsync(streamId, endStream : true, headers: headers);
await Assert.ThrowsAsync<HttpRequestException>(() => sendTask);
}
}
// rfc7540 8.1.2.3.
[ConditionalFact(nameof(SupportsAlpn))]
public async Task Http2GetAsync_StatusHeaderNotFirst_Throws()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
IList<HttpHeaderData> headers = new HttpHeaderData[] { new HttpHeaderData("x-test", "Http2GetAsync_StatusHeaderNotFirst_Throws"), new HttpHeaderData(":status", "200") };
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
await connection.SendResponseHeadersAsync(streamId, endStream : true, isTrailingHeader : true, headers: headers);
await Assert.ThrowsAsync<HttpRequestException>(() => sendTask);
}
}
// rfc7540 8.1.2.3.
[ConditionalFact(nameof(SupportsAlpn))]
public async Task Http2GetAsync_TrailigPseudo_Throw()
{
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
using (HttpClient client = CreateHttpClient())
{
IList<HttpHeaderData> headers = new HttpHeaderData[] { new HttpHeaderData(":path", "http"), new HttpHeaderData("x-test", "Http2GetAsync_TrailigPseudo_Throw") };
Task<HttpResponseMessage> sendTask = client.GetAsync(server.Address);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
await connection.SendDefaultResponseHeadersAsync(streamId);
await connection.SendResponseDataAsync(streamId, Encoding.ASCII.GetBytes("hello"), endStream: false);
await connection.SendResponseHeadersAsync(streamId, endStream : true, isTrailingHeader : true, headers: headers);
await Assert.ThrowsAsync<HttpRequestException>(() => sendTask);
}
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
public async Task Http2SendAsync_LargeHeaders_CorrectlyWritten(int continuationCount)
{
// Intentionally larger than 2x16K in total because that's the limit that will trigger a CONTINUATION frame in HTTP2.
string largeHeaderValue = new string('a', 1024);
int count = continuationCount * 16 + 1;
await Http2LoopbackServer.CreateClientAndServerAsync(async uri =>
{
using HttpClient client = CreateHttpClient();
var message = new HttpRequestMessage(HttpMethod.Get, uri) { Version = UseVersion };
for (int i = 0; i < count; i++)
{
message.Headers.TryAddWithoutValidation("large-header" + i, largeHeaderValue);
}
var response = await client.SendAsync(TestAsync, message).ConfigureAwait(false);
},
async server =>
{
// Primes the connection, i.e. forces it to exchange SETTINGS whose ACK sometimes flushed the headers as well.
// See: https://github.com/dotnet/runtime/issues/860 for repro description.
(Http2LoopbackConnection connection, SettingsFrame clientSettings) = await server.EstablishConnectionGetSettingsAsync();
// Read individual frames and assert number of CONTINUATIONs.
int receivedContinuations = 0;
int streamId = 0;
await foreach (Frame frame in connection.ReadRequestHeadersFrames())
{
if (frame.Type == FrameType.Headers)
{
streamId = ((HeadersFrame)frame).StreamId;
}
if (frame.Type == FrameType.Continuation)
{
++receivedContinuations;
}
}
Assert.Equal(continuationCount, receivedContinuations);
await connection.SendResponseAsync(HttpStatusCode.OK, requestId: streamId);
});
}
[Fact]
public async Task InboundWindowSize_Exceeded_Throw()
{
var semaphore = new SemaphoreSlim(0);
await Http2LoopbackServer.CreateClientAndServerAsync(
async uri =>
{
// An exception will be thrown by either GetAsync or ReadAsStringAsync once
// the inbound window size has been exceeded. Which one depends on how quickly
// ProcessIncomingFramesAsync() can read data off the socket.
Exception requestException = await Assert.ThrowsAsync<HttpRequestException>(async () =>
{
using HttpClient client = CreateHttpClient();
using HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead);
// Keep client open until server is done.
await semaphore.WaitAsync(10000);
await response.Content.ReadAsStringAsync();
});
// A Http2ConnectionException will be present somewhere in the inner exceptions.
// Its location depends on which method threw the exception.
while (requestException?.GetType().FullName.Equals("System.Net.Http.Http2ConnectionException") == false)
{
requestException = requestException.InnerException;
}
Assert.NotNull(requestException);
Assert.Contains("FLOW_CONTROL_ERROR", requestException.Message);
},
async server =>
{
try
{
(Http2LoopbackConnection connection, SettingsFrame clientSettings) = await server.EstablishConnectionGetSettingsAsync();
SettingsEntry clientWindowSizeSetting = clientSettings.Entries.SingleOrDefault(x => x.SettingId == SettingId.InitialWindowSize);
int clientWindowSize = clientWindowSizeSetting.SettingId == SettingId.InitialWindowSize ? (int)clientWindowSizeSetting.Value : 65535;
// Exceed the window size by 1 byte.
++clientWindowSize;
int streamId = await connection.ReadRequestHeaderAsync();
// Write the response.
await connection.SendDefaultResponseHeadersAsync(streamId);
byte[] buffer = new byte[4096];
int totalSent = 0;
while (totalSent < clientWindowSize)
{
int sendSize = Math.Min(buffer.Length, clientWindowSize - totalSent);
ReadOnlyMemory<byte> sendBuf = buffer.AsMemory(0, sendSize);
await connection.SendResponseDataAsync(streamId, sendBuf, endStream: false);
totalSent += sendSize;
}
// Try to read a frame. Should get null if connection reset or RST_STREAM if stream reset.
// If client is misbehaving, we'll get an OperationCanceledException due to timeout.
try
{
Frame clientFrame = await connection.ReadFrameAsync(TimeSpan.FromSeconds(5));
Assert.True(clientFrame == null || (clientFrame.Type == FrameType.RstStream && clientFrame.StreamId == streamId),
"Unexpected frame received from HttpClient; Expected either RST_STREAM or connection reset.");
}
catch (OperationCanceledException ex)
{
Assert.True(ex == null, "Stream unexpectedly left open by HttpClient; Expected either RST_STREAM or connection reset.");
}
}
finally
{
// Shut down client.
semaphore.Release();
}
});
}
[Fact]
[OuterLoop("Uses Task.Delay")]
public async Task SocketSendQueueFull_RequestCanceled_ThrowsOperationCanceled()
{
TaskCompletionSource clientComplete = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await Http2LoopbackServer.CreateClientAndServerAsync(
async uri =>
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
using HttpClient client = CreateHttpClient();
// Post a large request, large enough to fill the socket send buffer
Task postTask = client.PostAsync(uri, new StringContent(new string('a', 16 * 1024 * 1024)), cancellationTokenSource.Token);
// Wait a while to hopefully ensure that the send buffer has been completely filled
await Task.Delay(3000);
Assert.False(postTask.IsCompleted);
// Ensure that the request can be cancelled
cancellationTokenSource.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => postTask);
// Allow server to exit
clientComplete.SetResult();
},
async server =>
{
// Establish the connection and ensure client is not blocked on windows
Http2LoopbackConnection connection = await server.EstablishConnectionAsync(new SettingsEntry { SettingId = SettingId.InitialWindowSize, Value = 128 * 1024 * 1024 });
await connection.WriteFrameAsync(new WindowUpdateFrame(128 * 1024 * 1024, 0));
// Now, don't process any frames. Let the client's send buffer fill up.
// When the client is done, it will signal us.
await clientComplete.Task;
});
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task MaxResponseHeadersLength_Exact_Success(bool huffmanEncode)
{
await Http2LoopbackServer.CreateClientAndServerAsync(
async uri =>
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.MaxResponseHeadersLength = 1;
using HttpClient client = CreateHttpClient(handler);
using HttpResponseMessage response = await client.GetAsync(uri);
},
async server =>
{
Http2LoopbackConnection con = await server.EstablishConnectionAsync();
int streamId = await con.ReadRequestHeaderAsync();
await con.SendResponseHeadersAsync(streamId, isTrailingHeader: true, headers: new[]
{
// 1000 + other strings = 1024
new HttpHeaderData(":status", "200", huffmanEncoded: huffmanEncode),
new HttpHeaderData("padding-header", new string(' ', 1000), huffmanEncoded: huffmanEncode)
});
await con.ShutdownIgnoringErrorsAsync(streamId);
});
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task MaxResponseHeadersLength_Exceeded_Throws(bool huffmanEncode)
{
await Http2LoopbackServer.CreateClientAndServerAsync(
async uri =>
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.MaxResponseHeadersLength = 1;
using HttpClient client = CreateHttpClient(handler);
Exception e = await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(uri));
Assert.Contains((handler.MaxResponseHeadersLength * 1024).ToString(), e.ToString());
},
async server =>
{
Http2LoopbackConnection con = await server.EstablishConnectionAsync();
int streamId = await con.ReadRequestHeaderAsync();
await con.SendResponseHeadersAsync(streamId, isTrailingHeader: true, headers: new[]
{
// 1001 + other strings = 1025
new HttpHeaderData(":status", "200", huffmanEncoded: huffmanEncode),
new HttpHeaderData("padding-header", new string(' ', 1001), huffmanEncoded: huffmanEncode)
});
await con.ShutdownIgnoringErrorsAsync(streamId);
});
}
[Fact]
public async Task MaxResponseHeadersLength_Malicious_Throws()
{
await Http2LoopbackServer.CreateClientAndServerAsync(
async uri =>
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.MaxResponseHeadersLength = 1;
using HttpClient client = CreateHttpClient(handler);
Exception e = await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(uri));
Assert.Contains((handler.MaxResponseHeadersLength * 1024).ToString(), e.ToString());
},
async server =>
{
Http2LoopbackConnection con = await server.EstablishConnectionAsync();
int streamId = await con.ReadRequestHeaderAsync();
// A small malicious/corrupt payload that expands into two 1GB strings. We don't want HPackDecoder to allocate buffers when they exceed MaxResponseHeadersLength.
byte[] headerData = new byte[] { 0x88, 0x00, 0x7F, 0x81, 0xFF, 0xFF, 0xFF, 0x03, 0x70, 0x6C, 0x61, 0x69, 0x6E, 0x2D, 0x74, 0x65, 0x78, 0x74, 0x7F, 0x81, 0xFF, 0xFF, 0xFF, 0x03, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61 };
HeadersFrame frame = new HeadersFrame(headerData, FrameFlags.EndHeaders | FrameFlags.EndStream, 0, 0, 0, streamId);
await con.WriteFrameAsync(frame);
await con.ShutdownIgnoringErrorsAsync(streamId);
});
}
[Fact]
public async Task DynamicTableSizeUpdate_Exceeds_Settings_Throws()
{
await Http2LoopbackServer.CreateClientAndServerAsync(
async uri =>
{
using HttpClient client = CreateHttpClient();
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(uri));
},
async server =>
{
(Http2LoopbackConnection con, SettingsFrame settings) = await server.EstablishConnectionGetSettingsAsync();
int streamId = await con.ReadRequestHeaderAsync();
int headerTableSize = settings.GetHeaderTableSize();
byte[] headerData = new byte[16];
int headersLen = HPackEncoder.EncodeDynamicTableSizeUpdate(headerTableSize + 1, headerData);
HeadersFrame frame = new HeadersFrame(headerData.AsMemory(0, headersLen), FrameFlags.EndHeaders | FrameFlags.EndStream, 0, 0, 0, streamId);
await con.WriteFrameAsync(frame);
await con.ShutdownIgnoringErrorsAsync(streamId);
});
}
[Fact]
public async Task DynamicTable_Reuse_Concat()
{
await Http2LoopbackServer.CreateClientAndServerAsync(
async uri =>
{
using HttpClient client = CreateHttpClient();
using HttpResponseMessage response = await client.GetAsync(uri);
Assert.True(response.Headers.TryGetValues("my-header", out IEnumerable<string> values));
Assert.True(values.SequenceEqual(new[] { "foo", "bar" }));
},
async server =>
{
byte[] frameData = new byte[16 * 1024];
Http2LoopbackConnection con = await server.EstablishConnectionAsync();
int streamId = await con.ReadRequestHeaderAsync();
int pos = 0;
pos += HPackEncoder.EncodeHeader(":status", "200", HPackFlags.None, frameData.AsSpan(pos));
pos += HPackEncoder.EncodeHeader("my-header", "foo", HPackFlags.NewIndexed, frameData.AsSpan(pos));
pos += HPackEncoder.EncodeHeader(HPackEncoder.SmallestDynamicIndex, "bar", HPackFlags.None, frameData.AsSpan(pos));
await con.WriteFrameAsync(new HeadersFrame(frameData.AsMemory(0, pos), FrameFlags.EndHeaders | FrameFlags.EndStream, 0, 0, 0, streamId));
// Close out connection.
await con.ShutdownIgnoringErrorsAsync(streamId);
});
}
[Fact]
public async Task DynamicTable_Resize_Success()
{
await Http2LoopbackServer.CreateClientAndServerAsync(
async uri =>
{
using HttpClient client = CreateHttpClient();
// First request should initialize our dynamic table.
using (HttpResponseMessage response = await client.GetAsync(uri))
{
IEnumerable<string> values;
Assert.True(response.Headers.TryGetValues("header-that-gos", out values));
Assert.Equal("bar", Assert.Single(values));
Assert.True(response.Headers.TryGetValues("header-that-stays", out values));
Assert.Equal("foo", Assert.Single(values));
}
// Second request should reset the dynamic table.
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.True(response.Headers.TryGetValues("new-header", out IEnumerable<string> values));
Assert.Equal("baz", Assert.Single(values));
}
// Third request should use the reset values.
using (HttpResponseMessage response = await client.GetAsync(uri))
{
IEnumerable<string> values;
Assert.True(response.Headers.TryGetValues("header-that-stays", out values));
Assert.Equal("foo", Assert.Single(values));
Assert.True(response.Headers.TryGetValues("new-header", out values));
Assert.Equal("baz", Assert.Single(values));
}
},
async server =>
{
Http2LoopbackConnection con = await server.EstablishConnectionAsync();
byte[] frameData = new byte[16 * 1024];
// First stream, create dynamic indexes.
// header-that-goes: 63, header-that-stays: 62
int streamId = await con.ReadRequestHeaderAsync();
int pos = 0;
pos += HPackEncoder.EncodeHeader(":status", "200", HPackFlags.None, frameData.AsSpan(pos));
pos += HPackEncoder.EncodeHeader("header-that-gos", "bar", HPackFlags.NewIndexed, frameData.AsSpan(pos));
pos += HPackEncoder.EncodeHeader("header-that-stays", "foo", HPackFlags.NewIndexed, frameData.AsSpan(pos));
await con.WriteFrameAsync(new HeadersFrame(frameData.AsMemory(0, pos), FrameFlags.EndHeaders | FrameFlags.EndStream, 0, 0, 0, streamId));
// Second stream, resize the table so that the header-that-gos is removed from table, and add a new header.
// 1) resize: header-that-stays: 62
// 2) add new header: header-that-stays:63, new-header:62
streamId = await con.ReadRequestHeaderAsync();
pos = 0;
pos += HPackEncoder.EncodeDynamicTableSizeUpdate("header-that-staysfoo".Length + HttpHeaderData.RfcOverhead, frameData.AsSpan(pos));
pos += HPackEncoder.EncodeDynamicTableSizeUpdate(4096, frameData.AsSpan(pos));
pos += HPackEncoder.EncodeHeader(":status", "200", HPackFlags.None, frameData.AsSpan(pos));
pos += HPackEncoder.EncodeHeader("new-header", "baz", HPackFlags.NewIndexed, frameData.AsSpan(pos));
await con.WriteFrameAsync(new HeadersFrame(frameData.AsMemory(0, pos), FrameFlags.EndHeaders | FrameFlags.EndStream, 0, 0, 0, streamId));
// Third stream, use the dynamic table established in previous stream.
streamId = await con.ReadRequestHeaderAsync();
pos = 0;
pos += HPackEncoder.EncodeHeader(":status", "200", HPackFlags.None, frameData.AsSpan(pos));
pos += HPackEncoder.EncodeHeader(HPackEncoder.SmallestDynamicIndex + 1, frameData.AsSpan(pos)); // header-that-stays:foo
pos += HPackEncoder.EncodeHeader(HPackEncoder.SmallestDynamicIndex, frameData.AsSpan(pos)); // new-header:baz
await con.WriteFrameAsync(new HeadersFrame(frameData.AsMemory(0, pos), FrameFlags.EndHeaders | FrameFlags.EndStream, 0, 0, 0, streamId));
// Close out connection.
await con.ShutdownIgnoringErrorsAsync(streamId);
});
}
[Theory]
[MemberData(nameof(DynamicTable_Data))]
public async Task DynamicTable_Receipt_Success(IEnumerable<HttpHeaderData> headers)
{
await Http2LoopbackServer.CreateClientAndServerAsync(
async uri =>
{
using HttpClient client = CreateHttpClient();
// First request should initialize our dynamic table.
using (HttpResponseMessage response = await client.GetAsync(uri))
{
AssertExpectedHeaders(response);
}
// Second request should use the dynamic table.
using (HttpResponseMessage response = await client.GetAsync(uri))
{
AssertExpectedHeaders(response);
}
},
async server =>
{
(Http2LoopbackConnection con, SettingsFrame settings) = await server.EstablishConnectionGetSettingsAsync();
Debug.Assert(settings.GetHeaderTableSize() >= 4096, "Data for this theory requires a header table size of at least 4096.");
// First stream, create dynamic indexes.
int streamId = await con.ReadRequestHeaderAsync();
byte[] frameData = new byte[16 * 1024];
int pos = 0;
foreach (HttpHeaderData header in headers)
{
pos += HPackEncoder.EncodeHeader(header.Name, header.Value, HPackFlags.NewIndexed, frameData.AsSpan(pos));
}
await con.WriteFrameAsync(new HeadersFrame(frameData.AsMemory(0, pos), FrameFlags.EndHeaders | FrameFlags.EndStream, 0, 0, 0, streamId));
// Second stream, send headers using indexes only.
streamId = await con.ReadRequestHeaderAsync();
pos = 0;
for (int i = HPackEncoder.LargestStaticIndex + headers.Count(); i > HPackEncoder.LargestStaticIndex; --i)
{
pos += HPackEncoder.EncodeHeader(i, frameData.AsSpan(pos));
}
await con.WriteFrameAsync(new HeadersFrame(frameData.AsMemory(0, pos), FrameFlags.EndHeaders | FrameFlags.EndStream, 0, 0, 0, streamId));
// Close out connection.
await con.ShutdownIgnoringErrorsAsync(streamId);
});
void AssertExpectedHeaders(HttpResponseMessage response)
{
var expected = headers.Select(x => (name: x.Name.ToLowerInvariant(), value: x.Value.ToLowerInvariant()));
var actual = response.Headers.SelectMany(x => x.Value, (kvp, v) => (name: kvp.Key.ToLowerInvariant(), value: v.ToLowerInvariant()));
Assert.Empty(actual.Except(expected));
}
}
public static IEnumerable<object[]> DynamicTable_Data()
{
yield return new object[] { GenerateHeadersWithStatus200(512) };
yield return new object[] { GenerateHeadersWithStatus200(4096) };
}
/// <summary>
/// Generates headers to an exact dynamic table size.
/// </summary>
private static IEnumerable<HttpHeaderData> GenerateHeadersWithStatus200(int targetSize)
{
Debug.Assert(targetSize > 64, $"{nameof(targetSize)} must be more than 64 to account for a status 200 and padding headers.");
const string NamePrefix = "hn-";
const string ValuePrefix = "hv-";
// Add status 200 and remove its length and overhead.
targetSize -= ":status200".Length + HttpHeaderData.RfcOverhead;
yield return new HttpHeaderData(":status", "200");
for (int i = 0; targetSize > 0; ++i)
{
string s = i.ToString(CultureInfo.InvariantCulture);
string name = NamePrefix + s;
string value;
int left = targetSize - name.Length - HttpHeaderData.RfcOverhead;
if (left < 64)
{
// At this point, we pad out to reach the remaining size.
value = ValuePrefix + s.PadLeft(left - ValuePrefix.Length, '0');
}
else
{
value = ValuePrefix + s;
}
yield return new HttpHeaderData(name, value);
targetSize -= name.Length + value.Length + HttpHeaderData.RfcOverhead;
}
Debug.Assert(targetSize == 0); // Ensure we perfectly filled the target size.
}
}
}
| 50.86838
| 258
| 0.610034
|
[
"MIT"
] |
BreyerW/runtime
|
src/libraries/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.Http2.cs
| 194,012
|
C#
|
using System;
using System.Collections.Generic;
using System.Reflection;
namespace My.IoC.Core
{
/// <summary>
/// Find suitable constructors from which to sort and select.
/// </summary>
public interface IConstructorFinder
{
/// <summary>
/// Finds suitable constructors on the target type.
/// </summary>
/// <param name="targetType">Type to search for constructors.</param>
/// <returns>A list of suitable constructors.</returns>
List<ConstructorInfo> FindConstructors(Type targetType);
}
}
| 27.095238
| 77
| 0.648506
|
[
"MIT"
] |
jingyiliu/My.WinformMvc
|
My.IoC/IoC/Core/IConstructorFinder.cs
| 571
|
C#
|
using System;
namespace BlueMilk.IoC
{
public class BlueMilkException : Exception
{
public BlueMilkException(string message) : base(message)
{
}
public BlueMilkException(string message, Exception innerException) : base(message, innerException)
{
}
}
}
| 20.933333
| 106
| 0.633758
|
[
"MIT"
] |
JasperFx/bluemilk
|
src/BlueMilk/IoC/BlueMilkException.cs
| 316
|
C#
|
using ofreact;
using ofreact.Diagnostics;
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Platform;
using osu.Framework.Statistics;
namespace osu.Framework.Declarative
{
/// <summary>
/// Renders a <see cref="Game"/> inside a suitable platform-specific <see cref="GameHost"/> and bootstraps the ofreact scene graph.
/// </summary>
public class ofGame : ofRootNode
{
public GameHost Host { get; }
/// <summary>
/// Creates a new <see cref="ofGame"/> with the given host name.
/// </summary>
public ofGame(string name) : this(Framework.Host.GetSuitableHost(name)) { }
/// <summary>
/// Creates a new <see cref="ofGame"/> using the given host.
/// </summary>
public ofGame(GameHost host)
{
Host = host;
if (IsDiagnosticsEnabled)
Diagnostics = new GameRenderDiagnostics();
}
sealed class GameRenderDiagnostics : RenderDiagnostics
{
public readonly GlobalStatistic<int> NodesRenderedStatistic = GlobalStatistics.Get<int>(nameof(ofreact), nameof(NodesRendered));
public readonly GlobalStatistic<int> NodesSkippedStatistic = GlobalStatistics.Get<int>(nameof(ofreact), nameof(NodesSkipped));
public readonly GlobalStatistic<int> NodesInvalidatedStatistic = GlobalStatistics.Get<int>(nameof(ofreact), nameof(NodesInvalidated));
public readonly GlobalStatistic<int> NodesDisposedStatistic = GlobalStatistics.Get<int>(nameof(ofreact), nameof(NodesDisposed));
public readonly GlobalStatistic<int> EffectsInvokedStatistic = GlobalStatistics.Get<int>(nameof(ofreact), nameof(EffectsInvoked));
public override void OnNodeRendering(ofNode node)
{
base.OnNodeRendering(node);
NodesRenderedStatistic.Value = NodesRendered.Count;
}
public override void OnNodeRenderSkipped(ofNode node)
{
base.OnNodeRenderSkipped(node);
NodesSkippedStatistic.Value = NodesSkipped.Count;
}
public override void OnNodeInvalidated(ofNode node)
{
base.OnNodeInvalidated(node);
NodesInvalidatedStatistic.Value = NodesInvalidated.Count;
}
public override void OnNodeDisposed(ofNode node)
{
base.OnNodeDisposed(node);
NodesDisposedStatistic.Value = NodesDisposed.Count;
}
public override void OnEffectInvoking(EffectInfo effect)
{
base.OnEffectInvoking(effect);
EffectsInvokedStatistic.Value = EffectsInvoked.Count;
}
public override void Clear()
{
base.Clear();
NodesRenderedStatistic.Value = 0;
NodesSkippedStatistic.Value = 0;
NodesInvalidatedStatistic.Value = 0;
NodesDisposedStatistic.Value = 0;
EffectsInvokedStatistic.Value = 0;
}
}
public override RenderResult RenderElement(ofElement element)
{
using var game = new InternalGame(this, element);
Host.Run(game);
return RenderResult.Rendered;
}
void RenderInternal(ofElement element) => base.RenderElement(element);
public override void Dispose()
{
base.Dispose();
Host.Dispose();
}
sealed class InternalGame : Game
{
readonly ofGame _game;
readonly ofElement _element;
public InternalGame(ofGame game, ofElement element)
{
_game = game;
_element = element;
}
DependencyContainer _dependencies;
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
=> _dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
[Resolved]
FrameworkConfigManager Config { get; set; }
[BackgroundDependencyLoader]
void Load()
{
_dependencies.CacheAs<Game>(this);
_dependencies.Cache(new ofElementBootstrapper.NodeConnector(_game));
}
protected override void Update()
{
base.Update();
_game.RenderInternal(new ofPortal(this)
{
new ofContext<GameHost>(value: Host)
{
new ofContext<FrameworkConfigManager>(value: Config)
{
_element
}
}
});
}
}
}
}
| 34.291667
| 146
| 0.575132
|
[
"MIT"
] |
chiyadev/ofreact
|
osu.Framework.Declarative/ofGame.cs
| 4,938
|
C#
|
namespace Rate.Areas.HelpPage.ModelDescriptions
{
public class KeyValuePairModelDescription : ModelDescription
{
public ModelDescription KeyModelDescription { get; set; }
public ModelDescription ValueModelDescription { get; set; }
}
}
| 29.222222
| 67
| 0.737643
|
[
"MIT"
] |
jcnavarro/rateflicks
|
Rate.API/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs
| 263
|
C#
|
using Core.DataAccess.EntityFramework;
using DataAccess.Abstract;
using DataAccess.Concrete.EntityFramework.Contexts;
using Entities;
using Entities.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace DataAccess.Concrete.EntityFramework
{
public class EfTableDal : EfEntityRepositoryBase<Table, CoffeiSoftContext>, ITableDal
{
public List<TableDetailsDto> getTableDetails(Expression<Func<Table, bool>> filter = null)
{
using (CoffeiSoftContext contexts = new CoffeiSoftContext())
{
var result = from p in filter == null ? contexts.Table : contexts.Table.Where(filter)
join tl in contexts.Table_Location on p.tableLocationId equals tl.id
join tn in contexts.Table_Name on p.tableNameId equals tn.id
select new TableDetailsDto
{
id = p.id,
tableName = tn.tableName,
tableLocationName = tl.TableLocationName,
tableCapacity = p.tableCapacity,
isActive = p.isActive
};
return result.ToList();
}
}
}
}
| 39.771429
| 101
| 0.564655
|
[
"MIT"
] |
ugurkurekci/CoffeiSoft
|
DataAccess/Concrete/EntityFramework/EfTableDal.cs
| 1,394
|
C#
|
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.ServiceBus;
using Microsoft.Azure.Commands.ServiceBus.Models;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.Internal.Resources.Utilities.Models;
namespace Microsoft.Azure.Commands.ServiceBus.Commands.GeoDR
{
/// <summary>
/// 'Get-AzureServicebusGeoDRConfigurations' CmdletRetrieves Alias(Disaster Recovery configuration) for primary or secondary namespace
/// </summary>
[Cmdlet(VerbsCommon.Get, ServicebusDRConfigurationVerb, DefaultParameterSetName = GeoDRParameterSet), OutputType(typeof(List<PSServiceBusDRConfigurationAttributes>))]
public class GetServiceBusGeoDRConfiguration : AzureServiceBusCmdletBase
{
[Parameter(Mandatory = true, ParameterSetName = GeoDRParameterSet, ValueFromPipelineByPropertyName = true, Position = 0, HelpMessage = "Resource Group Name")]
[ValidateNotNullOrEmpty]
[ResourceGroupCompleter]
public string ResourceGroupName { get; set; }
[Parameter(Mandatory = true, ParameterSetName = GeoDRParameterSet, ValueFromPipelineByPropertyName = true, Position = 1, HelpMessage = "Namespace Name")]
[ValidateNotNullOrEmpty]
public string Namespace { get; set; }
[Parameter(Mandatory = true, ParameterSetName = NamespaceInputObjectParameterSet, ValueFromPipeline = true, Position = 0, HelpMessage = "Namespace Object")]
[ValidateNotNullOrEmpty]
public PSNamespaceAttributes InputObject { get; set; }
[Parameter(Mandatory = true, ParameterSetName = ResourceIdParameterSet, ValueFromPipelineByPropertyName = true, Position = 0, HelpMessage = "Namespace Resource Id")]
[ValidateNotNullOrEmpty]
public string ResourceId { get; set; }
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "DR Configuration Name")]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
public override void ExecuteCmdlet()
{
ResourceIdentifier getParamGeoDR = new ResourceIdentifier();
if (ParameterSetName == NamespaceInputObjectParameterSet)
{
getParamGeoDR = GetResourceDetailsFromId(InputObject.Id);
if (getParamGeoDR.ResourceGroupName != null && getParamGeoDR.ResourceName != null)
{
if (!string.IsNullOrEmpty(Name))
{
PSServiceBusDRConfigurationAttributes drConfiguration = Client.GetServiceBusDRConfiguration(getParamGeoDR.ResourceGroupName, getParamGeoDR.ResourceName, Name);
WriteObject(drConfiguration);
}
else
{
IEnumerable<PSServiceBusDRConfigurationAttributes> drConfigurationList = Client.ListAllServiceBusDRConfiguration(getParamGeoDR.ResourceGroupName, getParamGeoDR.ResourceName);
WriteObject(drConfigurationList.ToList(), true);
}
}
}
if (ParameterSetName == ResourceIdParameterSet)
{
getParamGeoDR = GetResourceDetailsFromId(ResourceId);
if (getParamGeoDR.ResourceGroupName != null && getParamGeoDR.ResourceName != null)
{
if (!string.IsNullOrEmpty(Name))
{
PSServiceBusDRConfigurationAttributes drConfiguration = Client.GetServiceBusDRConfiguration(getParamGeoDR.ResourceGroupName, getParamGeoDR.ResourceName, Name);
WriteObject(drConfiguration);
}
else
{
IEnumerable<PSServiceBusDRConfigurationAttributes> drConfigurationList = Client.ListAllServiceBusDRConfiguration(getParamGeoDR.ResourceGroupName, getParamGeoDR.ResourceName);
WriteObject(drConfigurationList.ToList(), true);
}
}
}
if (ParameterSetName == GeoDRParameterSet)
{
if (!string.IsNullOrEmpty(Name))
{
// Get a DRConfiguration
PSServiceBusDRConfigurationAttributes drConfiguration = Client.GetServiceBusDRConfiguration(ResourceGroupName, Namespace, Name);
WriteObject(drConfiguration);
}
else
{
// Get all DRConfigurations
IEnumerable<PSServiceBusDRConfigurationAttributes> drConfigurationList = Client.ListAllServiceBusDRConfiguration(ResourceGroupName, Namespace);
WriteObject(drConfigurationList.ToList(), true);
}
}
}
}
}
| 52.554545
| 199
| 0.627573
|
[
"MIT"
] |
AzureDataBox/azure-powershell
|
src/ResourceManager/ServiceBus/Commands.ServiceBus/Cmdlets/DRConfig/GetAzureServiceBusGeoDRConfiguration.cs
| 5,674
|
C#
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace MikuMikuLibrary.IO.Sections
{
public class SectionInfo
{
private readonly Dictionary<SectionInfo, SubSectionInfo> mSubSectionInfos =
new Dictionary<SectionInfo, SubSectionInfo>();
public Type SectionType { get; }
public string Signature { get; }
public Type DataType { get; }
public bool IsBinaryFile { get; }
public IReadOnlyDictionary<SectionInfo, SubSectionInfo> SubSectionInfos => mSubSectionInfos;
public ISection Create( SectionMode mode, object obj = null )
{
return ( ISection ) Activator.CreateInstance( SectionType, mode, obj );
}
internal SectionInfo( Type sectionType )
{
SectionType = sectionType;
var attribute = sectionType.GetCustomAttribute<SectionAttribute>();
if ( attribute == null )
throw new ArgumentException( "Section type is missing section attribute", nameof( sectionType ) );
Signature = attribute.Signature;
for ( var type = sectionType.BaseType; type != null; type = type.BaseType )
{
var genericTypeDefinition = type.GetGenericTypeDefinition();
if ( type.IsGenericType && type.GetGenericTypeDefinition() == typeof( Section<> ) )
{
DataType = type.GetGenericArguments()[ 0 ];
break;
}
}
if ( DataType == null )
DataType = attribute.DataType;
IsBinaryFile = typeof( IBinaryFile ).IsAssignableFrom( DataType );
foreach ( var propertyInfo in sectionType.GetProperties() )
{
var subSectionAttribute = propertyInfo.GetCustomAttribute<SubSectionAttribute>();
if ( subSectionAttribute == null )
continue;
var subSectionInfo = new SubSectionInfo( propertyInfo );
mSubSectionInfos.Add( subSectionInfo.SectionInfo, subSectionInfo );
}
}
}
[AttributeUsage( AttributeTargets.Class )]
public class SectionAttribute : Attribute
{
public string Signature { get; }
public Type DataType { get; }
public SectionAttribute( string signature )
{
Signature = signature;
}
public SectionAttribute( string signature, Type dataType ) : this( signature )
{
DataType = dataType;
}
}
public class SubSectionInfo
{
public PropertyInfo PropertyInfo { get; }
public SectionInfo SectionInfo { get; }
public int Priority { get; }
public bool IsListType { get; }
public bool IsSectionType { get; }
public void ProcessPropertyForReading( ISection section, object obj )
{
if ( IsListType )
{
var list = PropertyInfo.GetValue( obj ) as IList;
list.Add( IsSectionType ? section : section.Data );
}
else
{
PropertyInfo.SetValue( obj, IsSectionType ? section : section.Data );
}
}
public IEnumerable<ISection> ProcessPropertyForWriting( object obj )
{
var value = PropertyInfo.GetValue( obj );
if ( value != null )
{
if ( IsListType )
{
var list = value as IList;
if ( IsSectionType )
foreach ( var item in list )
yield return ( ISection ) item;
else
foreach ( var item in list )
yield return SectionInfo.Create( SectionMode.Write, item );
}
else
{
if ( IsSectionType )
yield return ( ISection ) value;
else
yield return SectionInfo.Create( SectionMode.Write, value );
}
}
}
internal SubSectionInfo( PropertyInfo propertyInfo )
{
var subSectionAttribute = propertyInfo.GetCustomAttribute<SubSectionAttribute>();
Type genericType = null;
for ( var type = propertyInfo.PropertyType; type != null; type = type.BaseType )
if ( type.IsGenericType && type.GetGenericTypeDefinition() == typeof( List<> ) )
{
genericType = type.GetGenericArguments()[ 0 ];
break;
}
if ( genericType != null )
{
IsListType = true;
IsSectionType = typeof( ISection ).IsAssignableFrom( genericType );
if ( IsSectionType )
SectionInfo = SectionRegistry.GetOrRegisterSectionInfo( genericType );
else
SectionInfo = SectionRegistry.GetOrRegisterSectionInfo( subSectionAttribute.SectionType );
}
else
{
IsSectionType = typeof( ISection ).IsAssignableFrom( propertyInfo.PropertyType );
if ( IsSectionType )
SectionInfo = SectionRegistry.GetOrRegisterSectionInfo( propertyInfo.PropertyType );
else
SectionInfo = SectionRegistry.GetOrRegisterSectionInfo( subSectionAttribute.SectionType );
}
PropertyInfo = propertyInfo;
Priority = subSectionAttribute.Priority;
}
}
[AttributeUsage( AttributeTargets.Property )]
public class SubSectionAttribute : Attribute
{
public int Priority { get; }
public Type SectionType { get; }
public SubSectionAttribute( [CallerLineNumber] int priority = int.MaxValue )
{
Priority = priority;
}
public SubSectionAttribute( Type sectionType, [CallerLineNumber] int priority = int.MaxValue ) :
this( priority )
{
SectionType = sectionType;
}
}
}
| 34.822222
| 114
| 0.551691
|
[
"MIT"
] |
nastys/MikuMikuLibrary
|
MikuMikuLibrary/IO/Sections/SectionInfo.cs
| 6,270
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.