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 |
|---|---|---|---|---|---|---|---|---|
namespace SPICA.WinForms
{
partial class FrmMain
{
/// <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.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmMain));
this.TopMenu = new System.Windows.Forms.MenuStrip();
this.MenuFileRoot = new System.Windows.Forms.ToolStripMenuItem();
this.MenuOpenFile = new System.Windows.Forms.ToolStripMenuItem();
this.MenuMergeFiles = new System.Windows.Forms.ToolStripMenuItem();
this.MenuBatchExport = new System.Windows.Forms.ToolStripMenuItem();
this.MenuOptionsRoot = new System.Windows.Forms.ToolStripMenuItem();
this.MenuRenderer = new System.Windows.Forms.ToolStripMenuItem();
this.MenuShowGrid = new System.Windows.Forms.ToolStripMenuItem();
this.MenuShowAxis = new System.Windows.Forms.ToolStripMenuItem();
this.MenuShowSkeleton = new System.Windows.Forms.ToolStripMenuItem();
this.MenuShowInfo = new System.Windows.Forms.ToolStripMenuItem();
this.MenuWireframeMode = new System.Windows.Forms.ToolStripMenuItem();
this.MenuUserInterface = new System.Windows.Forms.ToolStripMenuItem();
this.MenuShowSide = new System.Windows.Forms.ToolStripMenuItem();
this.MenuHelpRoot = new System.Windows.Forms.ToolStripMenuItem();
this.AnimControlsPanel = new System.Windows.Forms.Panel();
this.AnimSeekBar = new SPICA.WinForms.GUI.SUIAnimSeekBar();
this.AnimButtonPrev = new SPICA.WinForms.GUI.SUIIconButton();
this.AnimButtonSlowDown = new SPICA.WinForms.GUI.SUIIconButton();
this.AnimButtonPlayBackward = new SPICA.WinForms.GUI.SUIIconButton();
this.AnimButtonPlayForward = new SPICA.WinForms.GUI.SUIIconButton();
this.AnimButtonPause = new SPICA.WinForms.GUI.SUIIconButton();
this.AnimButtonStop = new SPICA.WinForms.GUI.SUIIconButton();
this.AnimButtonSpeedUp = new SPICA.WinForms.GUI.SUIIconButton();
this.AnimButtonNext = new SPICA.WinForms.GUI.SUIIconButton();
this.LblAnimSpeed = new System.Windows.Forms.Label();
this.LblAnimLoopMode = new System.Windows.Forms.Label();
this.Animator = new System.Windows.Forms.Timer(this.components);
this.TabIcons = new System.Windows.Forms.ImageList(this.components);
this.MainContainer = new System.Windows.Forms.SplitContainer();
this.SideTabs = new SPICA.WinForms.GUI.SUITabControl();
this.TabPageModels = new System.Windows.Forms.TabPage();
this.ModelsList = new SPICA.WinForms.GUI.SUIList();
this.TabPageTextures = new System.Windows.Forms.TabPage();
this.TexturesList = new SPICA.WinForms.GUI.SUIList();
this.TexturePreview = new System.Windows.Forms.PictureBox();
this.TextureInfo = new System.Windows.Forms.Label();
this.TabPageCameras = new System.Windows.Forms.TabPage();
this.CamerasList = new SPICA.WinForms.GUI.SUIList();
this.TabPageLights = new System.Windows.Forms.TabPage();
this.LightsList = new SPICA.WinForms.GUI.SUIList();
this.TabPageSklAnims = new System.Windows.Forms.TabPage();
this.SklAnimsList = new SPICA.WinForms.GUI.SUIList();
this.TabPageMatAnims = new System.Windows.Forms.TabPage();
this.MatAnimsList = new SPICA.WinForms.GUI.SUIList();
this.TabPageVisAnims = new System.Windows.Forms.TabPage();
this.VisAnimsList = new SPICA.WinForms.GUI.SUIList();
this.TabPageCamAnims = new System.Windows.Forms.TabPage();
this.CamAnimsList = new SPICA.WinForms.GUI.SUIList();
this.TabPageLUTs = new System.Windows.Forms.TabPage();
this.LUTsList = new SPICA.WinForms.GUI.SUIList();
this.SideIcons = new System.Windows.Forms.ToolStrip();
this.ToolButtonExport = new System.Windows.Forms.ToolStripButton();
this.ToolButtonImport = new System.Windows.Forms.ToolStripButton();
this.ToolButtonRemove = new System.Windows.Forms.ToolStripButton();
this.TBtnOpen = new System.Windows.Forms.ToolStripButton();
this.TBtnMerge = new System.Windows.Forms.ToolStripButton();
this.TBtnSave = new System.Windows.Forms.ToolStripButton();
this.MenuSeparatorShowHideJustIgnore = new System.Windows.Forms.ToolStripSeparator();
this.TBtnShowGrid = new System.Windows.Forms.ToolStripButton();
this.TBtnShowAxis = new System.Windows.Forms.ToolStripButton();
this.TBtnShowBones = new System.Windows.Forms.ToolStripButton();
this.TBtnShowInfo = new System.Windows.Forms.ToolStripButton();
this.TBtnShowSide = new System.Windows.Forms.ToolStripButton();
this.TopIcons = new System.Windows.Forms.ToolStrip();
this.TopMenu.SuspendLayout();
this.AnimControlsPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.MainContainer)).BeginInit();
this.MainContainer.Panel2.SuspendLayout();
this.MainContainer.SuspendLayout();
this.SideTabs.SuspendLayout();
this.TabPageModels.SuspendLayout();
this.TabPageTextures.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.TexturePreview)).BeginInit();
this.TabPageCameras.SuspendLayout();
this.TabPageLights.SuspendLayout();
this.TabPageSklAnims.SuspendLayout();
this.TabPageMatAnims.SuspendLayout();
this.TabPageVisAnims.SuspendLayout();
this.TabPageCamAnims.SuspendLayout();
this.TabPageLUTs.SuspendLayout();
this.SideIcons.SuspendLayout();
this.TopIcons.SuspendLayout();
this.SuspendLayout();
//
// TopMenu
//
this.TopMenu.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(73)))), ((int)(((byte)(66)))), ((int)(((byte)(61)))));
this.TopMenu.ForeColor = System.Drawing.Color.White;
this.TopMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.MenuFileRoot,
this.MenuOptionsRoot,
this.MenuHelpRoot});
this.TopMenu.Location = new System.Drawing.Point(0, 0);
this.TopMenu.Name = "TopMenu";
this.TopMenu.Size = new System.Drawing.Size(944, 24);
this.TopMenu.TabIndex = 1;
//
// MenuFileRoot
//
this.MenuFileRoot.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.MenuOpenFile,
this.MenuMergeFiles,
this.MenuBatchExport});
this.MenuFileRoot.Name = "MenuFileRoot";
this.MenuFileRoot.Size = new System.Drawing.Size(37, 20);
this.MenuFileRoot.Text = "&File";
//
// MenuOpenFile
//
this.MenuOpenFile.Name = "MenuOpenFile";
this.MenuOpenFile.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
this.MenuOpenFile.Size = new System.Drawing.Size(162, 22);
this.MenuOpenFile.Text = "&Open...";
this.MenuOpenFile.Click += new System.EventHandler(this.MenuOpenFile_Click);
//
// MenuMergeFiles
//
this.MenuMergeFiles.Name = "MenuMergeFiles";
this.MenuMergeFiles.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.M)));
this.MenuMergeFiles.Size = new System.Drawing.Size(162, 22);
this.MenuMergeFiles.Text = "&Merge...";
this.MenuMergeFiles.Click += new System.EventHandler(this.MenuMergeFiles_Click);
//
// MenuBatchExport
//
this.MenuBatchExport.Name = "MenuBatchExport";
this.MenuBatchExport.Size = new System.Drawing.Size(162, 22);
this.MenuBatchExport.Text = "&Batch export...";
this.MenuBatchExport.Click += new System.EventHandler(this.MenuBatchExport_Click);
//
// MenuOptionsRoot
//
this.MenuOptionsRoot.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.MenuRenderer,
this.MenuUserInterface});
this.MenuOptionsRoot.Name = "MenuOptionsRoot";
this.MenuOptionsRoot.Size = new System.Drawing.Size(61, 20);
this.MenuOptionsRoot.Text = "&Options";
//
// MenuRenderer
//
this.MenuRenderer.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.MenuShowGrid,
this.MenuShowAxis,
this.MenuShowSkeleton,
this.MenuShowInfo,
this.MenuWireframeMode});
this.MenuRenderer.Name = "MenuRenderer";
this.MenuRenderer.Size = new System.Drawing.Size(146, 22);
this.MenuRenderer.Text = "&Renderer";
//
// MenuShowGrid
//
this.MenuShowGrid.Name = "MenuShowGrid";
this.MenuShowGrid.Size = new System.Drawing.Size(167, 22);
this.MenuShowGrid.Text = "Show &grid";
this.MenuShowGrid.Click += new System.EventHandler(this.MenuShowGrid_Click);
//
// MenuShowAxis
//
this.MenuShowAxis.Name = "MenuShowAxis";
this.MenuShowAxis.Size = new System.Drawing.Size(167, 22);
this.MenuShowAxis.Text = "Show &axis";
this.MenuShowAxis.Click += new System.EventHandler(this.MenuShowAxis_Click);
//
// MenuShowSkeleton
//
this.MenuShowSkeleton.Name = "MenuShowSkeleton";
this.MenuShowSkeleton.Size = new System.Drawing.Size(167, 22);
this.MenuShowSkeleton.Text = "Show &skeleton";
//
// MenuShowInfo
//
this.MenuShowInfo.Name = "MenuShowInfo";
this.MenuShowInfo.Size = new System.Drawing.Size(167, 22);
this.MenuShowInfo.Text = "Show &model info.";
//
// MenuWireframeMode
//
this.MenuWireframeMode.Name = "MenuWireframeMode";
this.MenuWireframeMode.Size = new System.Drawing.Size(167, 22);
this.MenuWireframeMode.Text = "&Wireframe mode";
//
// MenuUserInterface
//
this.MenuUserInterface.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.MenuShowSide});
this.MenuUserInterface.Name = "MenuUserInterface";
this.MenuUserInterface.Size = new System.Drawing.Size(146, 22);
this.MenuUserInterface.Text = "&User interface";
//
// MenuShowSide
//
this.MenuShowSide.Name = "MenuShowSide";
this.MenuShowSide.Size = new System.Drawing.Size(161, 22);
this.MenuShowSide.Text = "Show &side menu";
this.MenuShowSide.Click += new System.EventHandler(this.MenuShowSide_Click);
//
// MenuHelpRoot
//
this.MenuHelpRoot.Name = "MenuHelpRoot";
this.MenuHelpRoot.Size = new System.Drawing.Size(44, 20);
this.MenuHelpRoot.Text = "&Help";
//
// AnimControlsPanel
//
this.AnimControlsPanel.Controls.Add(this.AnimSeekBar);
this.AnimControlsPanel.Controls.Add(this.AnimButtonPrev);
this.AnimControlsPanel.Controls.Add(this.AnimButtonSlowDown);
this.AnimControlsPanel.Controls.Add(this.AnimButtonPlayBackward);
this.AnimControlsPanel.Controls.Add(this.AnimButtonPlayForward);
this.AnimControlsPanel.Controls.Add(this.AnimButtonPause);
this.AnimControlsPanel.Controls.Add(this.AnimButtonStop);
this.AnimControlsPanel.Controls.Add(this.AnimButtonSpeedUp);
this.AnimControlsPanel.Controls.Add(this.AnimButtonNext);
this.AnimControlsPanel.Controls.Add(this.LblAnimSpeed);
this.AnimControlsPanel.Controls.Add(this.LblAnimLoopMode);
this.AnimControlsPanel.Dock = System.Windows.Forms.DockStyle.Bottom;
this.AnimControlsPanel.Location = new System.Drawing.Point(0, 531);
this.AnimControlsPanel.Name = "AnimControlsPanel";
this.AnimControlsPanel.Padding = new System.Windows.Forms.Padding(1, 1, 1, 2);
this.AnimControlsPanel.Size = new System.Drawing.Size(944, 30);
this.AnimControlsPanel.TabIndex = 4;
//
// AnimSeekBar
//
this.AnimSeekBar.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(53)))), ((int)(((byte)(48)))));
this.AnimSeekBar.CursorColor = System.Drawing.Color.FromArgb(((int)(((byte)(241)))), ((int)(((byte)(209)))), ((int)(((byte)(134)))));
this.AnimSeekBar.Dock = System.Windows.Forms.DockStyle.Fill;
this.AnimSeekBar.ForeColor = System.Drawing.Color.Gainsboro;
this.AnimSeekBar.Location = new System.Drawing.Point(1, 1);
this.AnimSeekBar.Maximum = 0F;
this.AnimSeekBar.Name = "AnimSeekBar";
this.AnimSeekBar.Size = new System.Drawing.Size(630, 27);
this.AnimSeekBar.TabIndex = 8;
this.AnimSeekBar.Value = 0F;
this.AnimSeekBar.Seek += new System.EventHandler(this.AnimSeekBar_Seek);
this.AnimSeekBar.MouseUp += new System.Windows.Forms.MouseEventHandler(this.AnimSeekBar_MouseUp);
//
// AnimButtonPrev
//
this.AnimButtonPrev.Dock = System.Windows.Forms.DockStyle.Right;
this.AnimButtonPrev.Icon = ((System.Drawing.Bitmap)(resources.GetObject("AnimButtonPrev.Icon")));
this.AnimButtonPrev.Location = new System.Drawing.Point(631, 1);
this.AnimButtonPrev.Name = "AnimButtonPrev";
this.AnimButtonPrev.Size = new System.Drawing.Size(28, 27);
this.AnimButtonPrev.TabIndex = 9;
this.AnimButtonPrev.Click += new System.EventHandler(this.AnimButtonPrev_Click);
//
// AnimButtonSlowDown
//
this.AnimButtonSlowDown.Dock = System.Windows.Forms.DockStyle.Right;
this.AnimButtonSlowDown.Icon = ((System.Drawing.Bitmap)(resources.GetObject("AnimButtonSlowDown.Icon")));
this.AnimButtonSlowDown.Location = new System.Drawing.Point(659, 1);
this.AnimButtonSlowDown.Name = "AnimButtonSlowDown";
this.AnimButtonSlowDown.Size = new System.Drawing.Size(28, 27);
this.AnimButtonSlowDown.TabIndex = 10;
this.AnimButtonSlowDown.Click += new System.EventHandler(this.AnimButtonSlowDown_Click);
//
// AnimButtonPlayBackward
//
this.AnimButtonPlayBackward.Dock = System.Windows.Forms.DockStyle.Right;
this.AnimButtonPlayBackward.Icon = ((System.Drawing.Bitmap)(resources.GetObject("AnimButtonPlayBackward.Icon")));
this.AnimButtonPlayBackward.Location = new System.Drawing.Point(687, 1);
this.AnimButtonPlayBackward.Name = "AnimButtonPlayBackward";
this.AnimButtonPlayBackward.Size = new System.Drawing.Size(28, 27);
this.AnimButtonPlayBackward.TabIndex = 7;
this.AnimButtonPlayBackward.Click += new System.EventHandler(this.AnimButtonPlayBackward_Click);
//
// AnimButtonPlayForward
//
this.AnimButtonPlayForward.Dock = System.Windows.Forms.DockStyle.Right;
this.AnimButtonPlayForward.Icon = ((System.Drawing.Bitmap)(resources.GetObject("AnimButtonPlayForward.Icon")));
this.AnimButtonPlayForward.Location = new System.Drawing.Point(715, 1);
this.AnimButtonPlayForward.Name = "AnimButtonPlayForward";
this.AnimButtonPlayForward.Size = new System.Drawing.Size(28, 27);
this.AnimButtonPlayForward.TabIndex = 6;
this.AnimButtonPlayForward.Click += new System.EventHandler(this.AnimButtonPlayForward_Click);
//
// AnimButtonPause
//
this.AnimButtonPause.Dock = System.Windows.Forms.DockStyle.Right;
this.AnimButtonPause.Icon = ((System.Drawing.Bitmap)(resources.GetObject("AnimButtonPause.Icon")));
this.AnimButtonPause.Location = new System.Drawing.Point(743, 1);
this.AnimButtonPause.Name = "AnimButtonPause";
this.AnimButtonPause.Size = new System.Drawing.Size(28, 27);
this.AnimButtonPause.TabIndex = 5;
this.AnimButtonPause.Click += new System.EventHandler(this.AnimButtonPause_Click);
//
// AnimButtonStop
//
this.AnimButtonStop.Dock = System.Windows.Forms.DockStyle.Right;
this.AnimButtonStop.Icon = ((System.Drawing.Bitmap)(resources.GetObject("AnimButtonStop.Icon")));
this.AnimButtonStop.Location = new System.Drawing.Point(771, 1);
this.AnimButtonStop.Name = "AnimButtonStop";
this.AnimButtonStop.Size = new System.Drawing.Size(28, 27);
this.AnimButtonStop.TabIndex = 4;
this.AnimButtonStop.Click += new System.EventHandler(this.AnimButtonStop_Click);
//
// AnimButtonSpeedUp
//
this.AnimButtonSpeedUp.Dock = System.Windows.Forms.DockStyle.Right;
this.AnimButtonSpeedUp.Icon = ((System.Drawing.Bitmap)(resources.GetObject("AnimButtonSpeedUp.Icon")));
this.AnimButtonSpeedUp.Location = new System.Drawing.Point(799, 1);
this.AnimButtonSpeedUp.Name = "AnimButtonSpeedUp";
this.AnimButtonSpeedUp.Size = new System.Drawing.Size(28, 27);
this.AnimButtonSpeedUp.TabIndex = 3;
this.AnimButtonSpeedUp.Click += new System.EventHandler(this.AnimButtonSpeedUp_Click);
//
// AnimButtonNext
//
this.AnimButtonNext.Dock = System.Windows.Forms.DockStyle.Right;
this.AnimButtonNext.Icon = ((System.Drawing.Bitmap)(resources.GetObject("AnimButtonNext.Icon")));
this.AnimButtonNext.Location = new System.Drawing.Point(827, 1);
this.AnimButtonNext.Name = "AnimButtonNext";
this.AnimButtonNext.Size = new System.Drawing.Size(28, 27);
this.AnimButtonNext.TabIndex = 2;
this.AnimButtonNext.Click += new System.EventHandler(this.AnimButtonNext_Click);
//
// LblAnimSpeed
//
this.LblAnimSpeed.Dock = System.Windows.Forms.DockStyle.Right;
this.LblAnimSpeed.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.LblAnimSpeed.Location = new System.Drawing.Point(855, 1);
this.LblAnimSpeed.Name = "LblAnimSpeed";
this.LblAnimSpeed.Size = new System.Drawing.Size(44, 27);
this.LblAnimSpeed.TabIndex = 1;
this.LblAnimSpeed.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// LblAnimLoopMode
//
this.LblAnimLoopMode.Dock = System.Windows.Forms.DockStyle.Right;
this.LblAnimLoopMode.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.LblAnimLoopMode.Location = new System.Drawing.Point(899, 1);
this.LblAnimLoopMode.Name = "LblAnimLoopMode";
this.LblAnimLoopMode.Size = new System.Drawing.Size(44, 27);
this.LblAnimLoopMode.TabIndex = 0;
this.LblAnimLoopMode.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// Animator
//
this.Animator.Interval = 16;
this.Animator.Tick += new System.EventHandler(this.Animator_Tick);
//
// TabIcons
//
this.TabIcons.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("TabIcons.ImageStream")));
this.TabIcons.TransparentColor = System.Drawing.Color.Transparent;
this.TabIcons.Images.SetKeyName(0, "sui_cube.png");
this.TabIcons.Images.SetKeyName(1, "sui_eye.png");
this.TabIcons.Images.SetKeyName(2, "sui_camera.png");
this.TabIcons.Images.SetKeyName(3, "sui_lightbulb.png");
this.TabIcons.Images.SetKeyName(4, "sui_bone_film.png");
this.TabIcons.Images.SetKeyName(5, "sui_rainbow_film.png");
this.TabIcons.Images.SetKeyName(6, "sui_transparent_film.png");
this.TabIcons.Images.SetKeyName(7, "sui_cam_film.png");
//
// MainContainer
//
this.MainContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.MainContainer.Location = new System.Drawing.Point(0, 54);
this.MainContainer.Name = "MainContainer";
//
// MainContainer.Panel2
//
this.MainContainer.Panel2.Controls.Add(this.SideTabs);
this.MainContainer.Panel2.Controls.Add(this.SideIcons);
this.MainContainer.Size = new System.Drawing.Size(944, 477);
this.MainContainer.SplitterDistance = 698;
this.MainContainer.TabIndex = 0;
//
// SideTabs
//
this.SideTabs.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(53)))), ((int)(((byte)(48)))));
this.SideTabs.Controls.Add(this.TabPageModels);
this.SideTabs.Controls.Add(this.TabPageTextures);
this.SideTabs.Controls.Add(this.TabPageCameras);
this.SideTabs.Controls.Add(this.TabPageLights);
this.SideTabs.Controls.Add(this.TabPageSklAnims);
this.SideTabs.Controls.Add(this.TabPageMatAnims);
this.SideTabs.Controls.Add(this.TabPageVisAnims);
this.SideTabs.Controls.Add(this.TabPageCamAnims);
this.SideTabs.Controls.Add(this.TabPageLUTs);
this.SideTabs.Dock = System.Windows.Forms.DockStyle.Fill;
this.SideTabs.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.SideTabs.ForegroundColor = System.Drawing.Color.White;
this.SideTabs.ImageList = this.TabIcons;
this.SideTabs.ItemSize = new System.Drawing.Size(24, 24);
this.SideTabs.Location = new System.Drawing.Point(0, 31);
this.SideTabs.Multiline = true;
this.SideTabs.Name = "SideTabs";
this.SideTabs.SelectedForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(188)))), ((int)(((byte)(183)))), ((int)(((byte)(123)))));
this.SideTabs.SelectedIndex = 0;
this.SideTabs.ShowToolTips = true;
this.SideTabs.Size = new System.Drawing.Size(242, 446);
this.SideTabs.SizeMode = System.Windows.Forms.TabSizeMode.Fixed;
this.SideTabs.TabIndex = 0;
//
// TabPageModels
//
this.TabPageModels.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(53)))), ((int)(((byte)(48)))));
this.TabPageModels.Controls.Add(this.ModelsList);
this.TabPageModels.ImageKey = "sui_cube.png";
this.TabPageModels.Location = new System.Drawing.Point(4, 28);
this.TabPageModels.Name = "TabPageModels";
this.TabPageModels.Padding = new System.Windows.Forms.Padding(3);
this.TabPageModels.Size = new System.Drawing.Size(234, 414);
this.TabPageModels.TabIndex = 0;
this.TabPageModels.ToolTipText = "Models";
//
// ModelsList
//
this.ModelsList.BackColor = System.Drawing.Color.Transparent;
this.ModelsList.BarColor = System.Drawing.Color.White;
this.ModelsList.BarColorHover = System.Drawing.Color.FromArgb(((int)(((byte)(188)))), ((int)(((byte)(183)))), ((int)(((byte)(123)))));
this.ModelsList.Dock = System.Windows.Forms.DockStyle.Fill;
this.ModelsList.ForeColor = System.Drawing.Color.White;
this.ModelsList.ItemHeight = 16;
this.ModelsList.Location = new System.Drawing.Point(3, 3);
this.ModelsList.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.ModelsList.MultiSelect = true;
this.ModelsList.Name = "ModelsList";
this.ModelsList.SelectedIndex = -1;
this.ModelsList.SelectionColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(134)))), ((int)(((byte)(106)))));
this.ModelsList.Size = new System.Drawing.Size(228, 408);
this.ModelsList.TabIndex = 0;
this.ModelsList.SelectedIndexChanged += new System.EventHandler(this.ModelsList_SelectedIndexChanged);
//
// TabPageTextures
//
this.TabPageTextures.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(53)))), ((int)(((byte)(48)))));
this.TabPageTextures.Controls.Add(this.TexturesList);
this.TabPageTextures.Controls.Add(this.TexturePreview);
this.TabPageTextures.Controls.Add(this.TextureInfo);
this.TabPageTextures.ImageKey = "sui_eye.png";
this.TabPageTextures.Location = new System.Drawing.Point(4, 28);
this.TabPageTextures.Name = "TabPageTextures";
this.TabPageTextures.Padding = new System.Windows.Forms.Padding(3);
this.TabPageTextures.Size = new System.Drawing.Size(234, 414);
this.TabPageTextures.TabIndex = 1;
this.TabPageTextures.ToolTipText = "Textures";
//
// TexturesList
//
this.TexturesList.BackColor = System.Drawing.Color.Transparent;
this.TexturesList.BarColor = System.Drawing.Color.White;
this.TexturesList.BarColorHover = System.Drawing.Color.FromArgb(((int)(((byte)(188)))), ((int)(((byte)(183)))), ((int)(((byte)(123)))));
this.TexturesList.Dock = System.Windows.Forms.DockStyle.Fill;
this.TexturesList.ForeColor = System.Drawing.Color.White;
this.TexturesList.ItemHeight = 16;
this.TexturesList.Location = new System.Drawing.Point(3, 3);
this.TexturesList.Margin = new System.Windows.Forms.Padding(3, 5, 3, 5);
this.TexturesList.MultiSelect = false;
this.TexturesList.Name = "TexturesList";
this.TexturesList.SelectedIndex = -1;
this.TexturesList.SelectionColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(134)))), ((int)(((byte)(106)))));
this.TexturesList.Size = new System.Drawing.Size(228, 199);
this.TexturesList.TabIndex = 2;
this.TexturesList.SelectedIndexChanged += new System.EventHandler(this.TexturesList_SelectedIndexChanged);
//
// TexturePreview
//
this.TexturePreview.Dock = System.Windows.Forms.DockStyle.Bottom;
this.TexturePreview.Location = new System.Drawing.Point(3, 202);
this.TexturePreview.Name = "TexturePreview";
this.TexturePreview.Size = new System.Drawing.Size(228, 192);
this.TexturePreview.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.TexturePreview.TabIndex = 1;
this.TexturePreview.TabStop = false;
//
// TextureInfo
//
this.TextureInfo.Dock = System.Windows.Forms.DockStyle.Bottom;
this.TextureInfo.Location = new System.Drawing.Point(3, 394);
this.TextureInfo.Name = "TextureInfo";
this.TextureInfo.Size = new System.Drawing.Size(228, 17);
this.TextureInfo.TabIndex = 0;
//
// TabPageCameras
//
this.TabPageCameras.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(53)))), ((int)(((byte)(48)))));
this.TabPageCameras.Controls.Add(this.CamerasList);
this.TabPageCameras.ImageKey = "sui_camera.png";
this.TabPageCameras.Location = new System.Drawing.Point(4, 28);
this.TabPageCameras.Name = "TabPageCameras";
this.TabPageCameras.Size = new System.Drawing.Size(234, 414);
this.TabPageCameras.TabIndex = 4;
this.TabPageCameras.ToolTipText = "Cameras";
//
// CamerasList
//
this.CamerasList.BackColor = System.Drawing.Color.Transparent;
this.CamerasList.BarColor = System.Drawing.Color.White;
this.CamerasList.BarColorHover = System.Drawing.Color.FromArgb(((int)(((byte)(188)))), ((int)(((byte)(183)))), ((int)(((byte)(123)))));
this.CamerasList.Dock = System.Windows.Forms.DockStyle.Fill;
this.CamerasList.ForeColor = System.Drawing.Color.White;
this.CamerasList.ItemHeight = 16;
this.CamerasList.Location = new System.Drawing.Point(0, 0);
this.CamerasList.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.CamerasList.MultiSelect = false;
this.CamerasList.Name = "CamerasList";
this.CamerasList.SelectedIndex = -1;
this.CamerasList.SelectionColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(134)))), ((int)(((byte)(106)))));
this.CamerasList.Size = new System.Drawing.Size(234, 414);
this.CamerasList.TabIndex = 0;
this.CamerasList.Selected += new System.EventHandler(this.CamerasList_Selected);
//
// TabPageLights
//
this.TabPageLights.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(53)))), ((int)(((byte)(48)))));
this.TabPageLights.Controls.Add(this.LightsList);
this.TabPageLights.ImageIndex = 3;
this.TabPageLights.Location = new System.Drawing.Point(4, 28);
this.TabPageLights.Name = "TabPageLights";
this.TabPageLights.Padding = new System.Windows.Forms.Padding(3);
this.TabPageLights.Size = new System.Drawing.Size(234, 414);
this.TabPageLights.TabIndex = 7;
this.TabPageLights.ToolTipText = "Lights";
//
// LightsList
//
this.LightsList.BackColor = System.Drawing.Color.Transparent;
this.LightsList.BarColor = System.Drawing.Color.White;
this.LightsList.BarColorHover = System.Drawing.Color.FromArgb(((int)(((byte)(188)))), ((int)(((byte)(183)))), ((int)(((byte)(123)))));
this.LightsList.Dock = System.Windows.Forms.DockStyle.Fill;
this.LightsList.ForeColor = System.Drawing.Color.White;
this.LightsList.ItemHeight = 16;
this.LightsList.Location = new System.Drawing.Point(3, 3);
this.LightsList.Margin = new System.Windows.Forms.Padding(3, 5, 3, 5);
this.LightsList.MultiSelect = true;
this.LightsList.Name = "LightsList";
this.LightsList.SelectedIndex = -1;
this.LightsList.SelectionColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(134)))), ((int)(((byte)(106)))));
this.LightsList.Size = new System.Drawing.Size(228, 408);
this.LightsList.TabIndex = 1;
this.LightsList.Selected += new System.EventHandler(this.LightsList_Selected);
//
// TabPageSklAnims
//
this.TabPageSklAnims.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(53)))), ((int)(((byte)(48)))));
this.TabPageSklAnims.Controls.Add(this.SklAnimsList);
this.TabPageSklAnims.ImageKey = "sui_bone_film.png";
this.TabPageSklAnims.Location = new System.Drawing.Point(4, 28);
this.TabPageSklAnims.Name = "TabPageSklAnims";
this.TabPageSklAnims.Padding = new System.Windows.Forms.Padding(3);
this.TabPageSklAnims.Size = new System.Drawing.Size(234, 414);
this.TabPageSklAnims.TabIndex = 2;
this.TabPageSklAnims.ToolTipText = "Skeletal animations";
//
// SklAnimsList
//
this.SklAnimsList.BackColor = System.Drawing.Color.Transparent;
this.SklAnimsList.BarColor = System.Drawing.Color.White;
this.SklAnimsList.BarColorHover = System.Drawing.Color.FromArgb(((int)(((byte)(188)))), ((int)(((byte)(183)))), ((int)(((byte)(123)))));
this.SklAnimsList.Dock = System.Windows.Forms.DockStyle.Fill;
this.SklAnimsList.ForeColor = System.Drawing.Color.White;
this.SklAnimsList.ItemHeight = 16;
this.SklAnimsList.Location = new System.Drawing.Point(3, 3);
this.SklAnimsList.Margin = new System.Windows.Forms.Padding(3, 7, 3, 7);
this.SklAnimsList.MultiSelect = true;
this.SklAnimsList.Name = "SklAnimsList";
this.SklAnimsList.SelectedIndex = -1;
this.SklAnimsList.SelectionColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(134)))), ((int)(((byte)(106)))));
this.SklAnimsList.Size = new System.Drawing.Size(228, 408);
this.SklAnimsList.TabIndex = 3;
this.SklAnimsList.Selected += new System.EventHandler(this.SklAnimsList_Selected);
//
// TabPageMatAnims
//
this.TabPageMatAnims.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(53)))), ((int)(((byte)(48)))));
this.TabPageMatAnims.Controls.Add(this.MatAnimsList);
this.TabPageMatAnims.ImageKey = "sui_rainbow_film.png";
this.TabPageMatAnims.Location = new System.Drawing.Point(4, 28);
this.TabPageMatAnims.Name = "TabPageMatAnims";
this.TabPageMatAnims.Padding = new System.Windows.Forms.Padding(3);
this.TabPageMatAnims.Size = new System.Drawing.Size(234, 414);
this.TabPageMatAnims.TabIndex = 3;
this.TabPageMatAnims.ToolTipText = "Material animations";
//
// MatAnimsList
//
this.MatAnimsList.BackColor = System.Drawing.Color.Transparent;
this.MatAnimsList.BarColor = System.Drawing.Color.White;
this.MatAnimsList.BarColorHover = System.Drawing.Color.FromArgb(((int)(((byte)(188)))), ((int)(((byte)(183)))), ((int)(((byte)(123)))));
this.MatAnimsList.Dock = System.Windows.Forms.DockStyle.Fill;
this.MatAnimsList.ForeColor = System.Drawing.Color.White;
this.MatAnimsList.ItemHeight = 16;
this.MatAnimsList.Location = new System.Drawing.Point(3, 3);
this.MatAnimsList.Margin = new System.Windows.Forms.Padding(3, 9, 3, 9);
this.MatAnimsList.MultiSelect = true;
this.MatAnimsList.Name = "MatAnimsList";
this.MatAnimsList.SelectedIndex = -1;
this.MatAnimsList.SelectionColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(134)))), ((int)(((byte)(106)))));
this.MatAnimsList.Size = new System.Drawing.Size(228, 408);
this.MatAnimsList.TabIndex = 4;
this.MatAnimsList.Selected += new System.EventHandler(this.MatAnimsList_Selected);
//
// TabPageVisAnims
//
this.TabPageVisAnims.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(53)))), ((int)(((byte)(48)))));
this.TabPageVisAnims.Controls.Add(this.VisAnimsList);
this.TabPageVisAnims.ImageKey = "sui_transparent_film.png";
this.TabPageVisAnims.Location = new System.Drawing.Point(4, 28);
this.TabPageVisAnims.Name = "TabPageVisAnims";
this.TabPageVisAnims.Size = new System.Drawing.Size(234, 414);
this.TabPageVisAnims.TabIndex = 6;
this.TabPageVisAnims.ToolTipText = "Visibility animations";
//
// VisAnimsList
//
this.VisAnimsList.BackColor = System.Drawing.Color.Transparent;
this.VisAnimsList.BarColor = System.Drawing.Color.White;
this.VisAnimsList.BarColorHover = System.Drawing.Color.FromArgb(((int)(((byte)(188)))), ((int)(((byte)(183)))), ((int)(((byte)(123)))));
this.VisAnimsList.Dock = System.Windows.Forms.DockStyle.Fill;
this.VisAnimsList.ForeColor = System.Drawing.Color.White;
this.VisAnimsList.ItemHeight = 16;
this.VisAnimsList.Location = new System.Drawing.Point(0, 0);
this.VisAnimsList.Margin = new System.Windows.Forms.Padding(3, 12, 3, 12);
this.VisAnimsList.MultiSelect = true;
this.VisAnimsList.Name = "VisAnimsList";
this.VisAnimsList.SelectedIndex = -1;
this.VisAnimsList.SelectionColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(134)))), ((int)(((byte)(106)))));
this.VisAnimsList.Size = new System.Drawing.Size(234, 414);
this.VisAnimsList.TabIndex = 5;
this.VisAnimsList.Selected += new System.EventHandler(this.VisAnimsList_Selected);
//
// TabPageCamAnims
//
this.TabPageCamAnims.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(53)))), ((int)(((byte)(48)))));
this.TabPageCamAnims.Controls.Add(this.CamAnimsList);
this.TabPageCamAnims.ImageKey = "sui_cam_film.png";
this.TabPageCamAnims.Location = new System.Drawing.Point(4, 28);
this.TabPageCamAnims.Name = "TabPageCamAnims";
this.TabPageCamAnims.Size = new System.Drawing.Size(234, 414);
this.TabPageCamAnims.TabIndex = 5;
this.TabPageCamAnims.ToolTipText = "Camera animations";
//
// CamAnimsList
//
this.CamAnimsList.BackColor = System.Drawing.Color.Transparent;
this.CamAnimsList.BarColor = System.Drawing.Color.White;
this.CamAnimsList.BarColorHover = System.Drawing.Color.FromArgb(((int)(((byte)(188)))), ((int)(((byte)(183)))), ((int)(((byte)(123)))));
this.CamAnimsList.Dock = System.Windows.Forms.DockStyle.Fill;
this.CamAnimsList.ForeColor = System.Drawing.Color.White;
this.CamAnimsList.ItemHeight = 16;
this.CamAnimsList.Location = new System.Drawing.Point(0, 0);
this.CamAnimsList.Margin = new System.Windows.Forms.Padding(3, 12, 3, 12);
this.CamAnimsList.MultiSelect = false;
this.CamAnimsList.Name = "CamAnimsList";
this.CamAnimsList.SelectedIndex = -1;
this.CamAnimsList.SelectionColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(134)))), ((int)(((byte)(106)))));
this.CamAnimsList.Size = new System.Drawing.Size(234, 414);
this.CamAnimsList.TabIndex = 5;
this.CamAnimsList.Selected += new System.EventHandler(this.CamAnimsList_Selected);
//
// TabPageLUTs
//
this.TabPageLUTs.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(53)))), ((int)(((byte)(48)))));
this.TabPageLUTs.Controls.Add(this.LUTsList);
this.TabPageLUTs.Location = new System.Drawing.Point(4, 28);
this.TabPageLUTs.Name = "TabPageLUTs";
this.TabPageLUTs.Size = new System.Drawing.Size(234, 414);
this.TabPageLUTs.TabIndex = 8;
this.TabPageLUTs.Text = "LUT";
//
// LUTsList
//
this.LUTsList.BackColor = System.Drawing.Color.Transparent;
this.LUTsList.BarColor = System.Drawing.Color.White;
this.LUTsList.BarColorHover = System.Drawing.Color.Gray;
this.LUTsList.Dock = System.Windows.Forms.DockStyle.Fill;
this.LUTsList.ForeColor = System.Drawing.Color.White;
this.LUTsList.ItemHeight = 16;
this.LUTsList.Location = new System.Drawing.Point(0, 0);
this.LUTsList.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.LUTsList.MultiSelect = false;
this.LUTsList.Name = "LUTsList";
this.LUTsList.SelectedIndex = -1;
this.LUTsList.SelectionColor = System.Drawing.Color.Orange;
this.LUTsList.Size = new System.Drawing.Size(234, 414);
this.LUTsList.TabIndex = 0;
//
// SideIcons
//
this.SideIcons.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(73)))), ((int)(((byte)(66)))), ((int)(((byte)(61)))));
this.SideIcons.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ToolButtonExport,
this.ToolButtonImport,
this.ToolButtonRemove});
this.SideIcons.Location = new System.Drawing.Point(0, 0);
this.SideIcons.Name = "SideIcons";
this.SideIcons.Size = new System.Drawing.Size(242, 31);
this.SideIcons.TabIndex = 1;
//
// ToolButtonExport
//
this.ToolButtonExport.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.ToolButtonExport.Image = ((System.Drawing.Image)(resources.GetObject("ToolButtonExport.Image")));
this.ToolButtonExport.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.ToolButtonExport.ImageTransparentColor = System.Drawing.Color.Magenta;
this.ToolButtonExport.Name = "ToolButtonExport";
this.ToolButtonExport.Size = new System.Drawing.Size(28, 28);
this.ToolButtonExport.ToolTipText = "Export...";
this.ToolButtonExport.Click += new System.EventHandler(this.ToolButtonExport_Click);
//
// ToolButtonImport
//
this.ToolButtonImport.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.ToolButtonImport.Image = ((System.Drawing.Image)(resources.GetObject("ToolButtonImport.Image")));
this.ToolButtonImport.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.ToolButtonImport.ImageTransparentColor = System.Drawing.Color.Magenta;
this.ToolButtonImport.Name = "ToolButtonImport";
this.ToolButtonImport.Size = new System.Drawing.Size(28, 28);
this.ToolButtonImport.ToolTipText = "Import...";
this.ToolButtonImport.Click += new System.EventHandler(this.ToolButtonImport_Click);
//
// ToolButtonRemove
//
this.ToolButtonRemove.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.ToolButtonRemove.Image = ((System.Drawing.Image)(resources.GetObject("ToolButtonRemove.Image")));
this.ToolButtonRemove.ImageTransparentColor = System.Drawing.Color.Magenta;
this.ToolButtonRemove.Name = "ToolButtonRemove";
this.ToolButtonRemove.Size = new System.Drawing.Size(54, 28);
this.ToolButtonRemove.Text = "Remove";
this.ToolButtonRemove.ToolTipText = "Removes the selected scene element";
this.ToolButtonRemove.Click += new System.EventHandler(this.ToolButtonRemove_Click);
//
// TBtnOpen
//
this.TBtnOpen.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.TBtnOpen.Image = ((System.Drawing.Image)(resources.GetObject("TBtnOpen.Image")));
this.TBtnOpen.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.TBtnOpen.ImageTransparentColor = System.Drawing.Color.Magenta;
this.TBtnOpen.Name = "TBtnOpen";
this.TBtnOpen.Size = new System.Drawing.Size(28, 27);
this.TBtnOpen.ToolTipText = "Open...";
this.TBtnOpen.Click += new System.EventHandler(this.TBtnOpen_Click);
//
// TBtnMerge
//
this.TBtnMerge.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.TBtnMerge.Image = ((System.Drawing.Image)(resources.GetObject("TBtnMerge.Image")));
this.TBtnMerge.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.TBtnMerge.ImageTransparentColor = System.Drawing.Color.Magenta;
this.TBtnMerge.Name = "TBtnMerge";
this.TBtnMerge.Size = new System.Drawing.Size(28, 27);
this.TBtnMerge.ToolTipText = "Merge...";
this.TBtnMerge.Click += new System.EventHandler(this.TBtnMerge_Click);
//
// TBtnSave
//
this.TBtnSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.TBtnSave.Image = ((System.Drawing.Image)(resources.GetObject("TBtnSave.Image")));
this.TBtnSave.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.TBtnSave.ImageTransparentColor = System.Drawing.Color.Magenta;
this.TBtnSave.Name = "TBtnSave";
this.TBtnSave.Size = new System.Drawing.Size(28, 27);
this.TBtnSave.ToolTipText = "Save...";
this.TBtnSave.Click += new System.EventHandler(this.TBtnSave_Click);
//
// MenuSeparatorShowHideJustIgnore
//
this.MenuSeparatorShowHideJustIgnore.Name = "MenuSeparatorShowHideJustIgnore";
this.MenuSeparatorShowHideJustIgnore.Size = new System.Drawing.Size(6, 30);
//
// TBtnShowGrid
//
this.TBtnShowGrid.CheckOnClick = true;
this.TBtnShowGrid.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.TBtnShowGrid.Image = ((System.Drawing.Image)(resources.GetObject("TBtnShowGrid.Image")));
this.TBtnShowGrid.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.TBtnShowGrid.ImageTransparentColor = System.Drawing.Color.Magenta;
this.TBtnShowGrid.Name = "TBtnShowGrid";
this.TBtnShowGrid.Size = new System.Drawing.Size(28, 27);
this.TBtnShowGrid.ToolTipText = "Toggle grid";
this.TBtnShowGrid.Click += new System.EventHandler(this.TBtnShowGrid_Click);
//
// TBtnShowAxis
//
this.TBtnShowAxis.CheckOnClick = true;
this.TBtnShowAxis.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.TBtnShowAxis.Image = ((System.Drawing.Image)(resources.GetObject("TBtnShowAxis.Image")));
this.TBtnShowAxis.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.TBtnShowAxis.ImageTransparentColor = System.Drawing.Color.Magenta;
this.TBtnShowAxis.Name = "TBtnShowAxis";
this.TBtnShowAxis.Size = new System.Drawing.Size(28, 27);
this.TBtnShowAxis.ToolTipText = "Toggle axis";
this.TBtnShowAxis.Click += new System.EventHandler(this.TBtnShowAxis_Click);
//
// TBtnShowBones
//
this.TBtnShowBones.CheckOnClick = true;
this.TBtnShowBones.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.TBtnShowBones.Image = ((System.Drawing.Image)(resources.GetObject("TBtnShowBones.Image")));
this.TBtnShowBones.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.TBtnShowBones.ImageTransparentColor = System.Drawing.Color.Magenta;
this.TBtnShowBones.Name = "TBtnShowBones";
this.TBtnShowBones.Size = new System.Drawing.Size(28, 27);
this.TBtnShowBones.ToolTipText = "Toggle skeleton";
//
// TBtnShowInfo
//
this.TBtnShowInfo.CheckOnClick = true;
this.TBtnShowInfo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.TBtnShowInfo.Image = ((System.Drawing.Image)(resources.GetObject("TBtnShowInfo.Image")));
this.TBtnShowInfo.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.TBtnShowInfo.ImageTransparentColor = System.Drawing.Color.Magenta;
this.TBtnShowInfo.Name = "TBtnShowInfo";
this.TBtnShowInfo.Size = new System.Drawing.Size(28, 27);
this.TBtnShowInfo.ToolTipText = "Toggle model info.";
//
// TBtnShowSide
//
this.TBtnShowSide.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.TBtnShowSide.CheckOnClick = true;
this.TBtnShowSide.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.TBtnShowSide.Image = ((System.Drawing.Image)(resources.GetObject("TBtnShowSide.Image")));
this.TBtnShowSide.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.TBtnShowSide.ImageTransparentColor = System.Drawing.Color.Magenta;
this.TBtnShowSide.Name = "TBtnShowSide";
this.TBtnShowSide.Size = new System.Drawing.Size(28, 27);
this.TBtnShowSide.ToolTipText = "Toggle side menu";
this.TBtnShowSide.Click += new System.EventHandler(this.TBtnShowSide_Click);
//
// TopIcons
//
this.TopIcons.AutoSize = false;
this.TopIcons.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(73)))), ((int)(((byte)(66)))), ((int)(((byte)(61)))));
this.TopIcons.ForeColor = System.Drawing.Color.White;
this.TopIcons.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.TBtnOpen,
this.TBtnMerge,
this.TBtnSave,
this.MenuSeparatorShowHideJustIgnore,
this.TBtnShowGrid,
this.TBtnShowAxis,
this.TBtnShowBones,
this.TBtnShowInfo,
this.TBtnShowSide});
this.TopIcons.Location = new System.Drawing.Point(0, 24);
this.TopIcons.Name = "TopIcons";
this.TopIcons.Size = new System.Drawing.Size(944, 30);
this.TopIcons.TabIndex = 3;
//
// FrmMain
//
this.AllowDrop = true;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(73)))), ((int)(((byte)(66)))), ((int)(((byte)(61)))));
this.ClientSize = new System.Drawing.Size(944, 561);
this.Controls.Add(this.MainContainer);
this.Controls.Add(this.AnimControlsPanel);
this.Controls.Add(this.TopIcons);
this.Controls.Add(this.TopMenu);
this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ForeColor = System.Drawing.Color.White;
this.Name = "FrmMain";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "SPICA";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmMain_FormClosing);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.FrmMain_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.FrmMain_DragEnter);
this.TopMenu.ResumeLayout(false);
this.TopMenu.PerformLayout();
this.AnimControlsPanel.ResumeLayout(false);
this.MainContainer.Panel2.ResumeLayout(false);
this.MainContainer.Panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.MainContainer)).EndInit();
this.MainContainer.ResumeLayout(false);
this.SideTabs.ResumeLayout(false);
this.TabPageModels.ResumeLayout(false);
this.TabPageTextures.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.TexturePreview)).EndInit();
this.TabPageCameras.ResumeLayout(false);
this.TabPageLights.ResumeLayout(false);
this.TabPageSklAnims.ResumeLayout(false);
this.TabPageMatAnims.ResumeLayout(false);
this.TabPageVisAnims.ResumeLayout(false);
this.TabPageCamAnims.ResumeLayout(false);
this.TabPageLUTs.ResumeLayout(false);
this.SideIcons.ResumeLayout(false);
this.SideIcons.PerformLayout();
this.TopIcons.ResumeLayout(false);
this.TopIcons.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.SplitContainer MainContainer;
private System.Windows.Forms.MenuStrip TopMenu;
private System.Windows.Forms.ToolStripMenuItem MenuFileRoot;
private System.Windows.Forms.ToolStripMenuItem MenuHelpRoot;
private System.Windows.Forms.ToolStripMenuItem MenuOpenFile;
private GUI.SUITabControl SideTabs;
private System.Windows.Forms.TabPage TabPageModels;
private System.Windows.Forms.TabPage TabPageTextures;
private System.Windows.Forms.TabPage TabPageSklAnims;
private GUI.SUIList ModelsList;
private System.Windows.Forms.Label TextureInfo;
private System.Windows.Forms.PictureBox TexturePreview;
private GUI.SUIList TexturesList;
private GUI.SUIList SklAnimsList;
private System.Windows.Forms.Panel AnimControlsPanel;
private System.Windows.Forms.Label LblAnimSpeed;
private System.Windows.Forms.Label LblAnimLoopMode;
private GUI.SUIAnimSeekBar AnimSeekBar;
private GUI.SUIIconButton AnimButtonPlayBackward;
private GUI.SUIIconButton AnimButtonPlayForward;
private GUI.SUIIconButton AnimButtonPause;
private GUI.SUIIconButton AnimButtonStop;
private GUI.SUIIconButton AnimButtonSpeedUp;
private GUI.SUIIconButton AnimButtonNext;
private GUI.SUIIconButton AnimButtonSlowDown;
private GUI.SUIIconButton AnimButtonPrev;
private System.Windows.Forms.Timer Animator;
private System.Windows.Forms.ImageList TabIcons;
private System.Windows.Forms.TabPage TabPageMatAnims;
private GUI.SUIList MatAnimsList;
private System.Windows.Forms.ToolStripMenuItem MenuMergeFiles;
private System.Windows.Forms.ToolStripMenuItem MenuBatchExport;
private System.Windows.Forms.ToolStripMenuItem MenuOptionsRoot;
private System.Windows.Forms.ToolStripMenuItem MenuRenderer;
private System.Windows.Forms.ToolStripButton TBtnOpen;
private System.Windows.Forms.ToolStripButton TBtnMerge;
private System.Windows.Forms.ToolStripButton TBtnSave;
private System.Windows.Forms.ToolStripSeparator MenuSeparatorShowHideJustIgnore;
private System.Windows.Forms.ToolStripButton TBtnShowGrid;
private System.Windows.Forms.ToolStripButton TBtnShowAxis;
private System.Windows.Forms.ToolStripButton TBtnShowBones;
private System.Windows.Forms.ToolStripButton TBtnShowInfo;
private System.Windows.Forms.ToolStripButton TBtnShowSide;
private System.Windows.Forms.ToolStrip TopIcons;
private System.Windows.Forms.ToolStripMenuItem MenuShowGrid;
private System.Windows.Forms.ToolStripMenuItem MenuShowAxis;
private System.Windows.Forms.ToolStripMenuItem MenuShowSkeleton;
private System.Windows.Forms.ToolStripMenuItem MenuShowInfo;
private System.Windows.Forms.ToolStripMenuItem MenuWireframeMode;
private System.Windows.Forms.ToolStripMenuItem MenuUserInterface;
private System.Windows.Forms.ToolStripMenuItem MenuShowSide;
private System.Windows.Forms.ToolStrip SideIcons;
private System.Windows.Forms.ToolStripButton ToolButtonExport;
private System.Windows.Forms.ToolStripButton ToolButtonImport;
private System.Windows.Forms.TabPage TabPageCameras;
private GUI.SUIList CamerasList;
private System.Windows.Forms.TabPage TabPageCamAnims;
private GUI.SUIList CamAnimsList;
private System.Windows.Forms.TabPage TabPageVisAnims;
private GUI.SUIList VisAnimsList;
private System.Windows.Forms.TabPage TabPageLights;
private GUI.SUIList LightsList;
private System.Windows.Forms.ToolStripButton ToolButtonRemove;
private System.Windows.Forms.TabPage TabPageLUTs;
private GUI.SUIList LUTsList;
}
} | 59.142137 | 165 | 0.630179 | [
"Unlicense"
] | HelloOO7/SPICA | SPICA.WinForms/FrmMain.Designer.cs | 58,671 | C# |
namespace Emrys.SuperConfig.Mapping
{
public interface ITypeMapping
{
void Apply(object instance);
void Add(IPropertyMapping propertyMapping);
}
} | 21.875 | 51 | 0.685714 | [
"MIT"
] | Emrys5/Emrys.SuperConfig | Emrys.SuperConfig/Mapping/ITypeMapping.cs | 177 | C# |
// <copyright file="ApplicationArea.cs" company="SoluiNet">
// Copyright (c) SoluiNet. All rights reserved.
// </copyright>
namespace SoluiNet.DevTools.Utils.TimeTracking.Entities
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SoluiNet.DevTools.Core.XmlData;
/// <summary>
/// The entity ApplicationArea.
/// </summary>
[Table("ApplicationArea")]
public class ApplicationArea : IContainsExtendedConfiguration
{
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationArea"/> class.
/// </summary>
public ApplicationArea()
{
}
/// <summary>
/// Gets or sets the ApplicationAreaId.
/// </summary>
public virtual int ApplicationAreaId { get; set; }
/// <summary>
/// Gets or sets the ApplicationId.
/// </summary>
public virtual int ApplicationId { get; set; }
/// <summary>
/// Gets or sets the AreaName.
/// </summary>
public virtual string AreaName { get; set; }
/// <summary>
/// Gets or sets the application.
/// </summary>
public virtual Application Application { get; set; }
/// <summary>
/// Gets or sets the usage times.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Usage",
"CA2227:Collection properties should be read only",
Justification = "This property will be used from Entity Framework. Just to be safe the setter shouldn't be removed")]
public virtual ICollection<UsageTime> UsageTime { get; set; }
/// <summary>
/// Gets or sets the extended configuration.
/// </summary>
public virtual string ExtendedConfiguration { get; set; }
}
}
| 31.190476 | 129 | 0.602036 | [
"MIT"
] | Kimiyou/SoluiNet.DevTools | SoluiNet.DevTools.Utils.TimeTracking/Entities/ApplicationArea.cs | 1,967 | C# |
using System.ComponentModel.DataAnnotations;
namespace Nsiclass.Client.Areas.Admin.Models.Users
{
public class ChangeUserPasswordViewModel
{
[Required]
public string Id { get; set; }
[Required]
[Display(Name = "Потребителско име:")]
public string Username { get; set; }
[Required]
[StringLength(100, MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Парола")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Потвърди паролата")]
[Compare("Password", ErrorMessage = "Паролата и потвърждението не съвпадат!")]
public string ConfirmPassword { get; set; }
}
}
| 27.37037 | 86 | 0.62111 | [
"MIT"
] | moher4o/NSIClass | Nsiclass.Client/Areas/Admin/Models/Users/ChangeUserPasswordViewModel.cs | 812 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace SimplestSample
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
}
}
| 17.166667 | 47 | 0.66343 | [
"MIT"
] | Bhekinkosi12/Xamarin.Forms.GoogleMaps.Bindings | Sample/SimplestSample/SimplestSample/MainPage.xaml.cs | 311 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using AsmResolver.IO;
namespace AsmResolver.PE.DotNet.Metadata.UserStrings
{
/// <summary>
/// Provides an implementation of a user-strings stream that obtains strings from a readable segment in a file.
/// </summary>
public class SerializedUserStringsStream : UserStringsStream
{
private readonly Dictionary<uint, string> _cachedStrings = new();
private readonly BinaryStreamReader _reader;
/// <summary>
/// Creates a new user-strings stream based on a byte array.
/// </summary>
/// <param name="name">The name of the stream.</param>
/// <param name="rawData">The raw contents of the stream.</param>
public SerializedUserStringsStream(string name, byte[] rawData)
: this(name, ByteArrayDataSource.CreateReader(rawData))
{
}
/// <summary>
/// Creates a new user-strings stream based on a segment in a file.
/// </summary>
/// <param name="name">The name of the stream.</param>
/// <param name="reader">The raw contents of the stream.</param>
public SerializedUserStringsStream(string name, BinaryStreamReader reader)
: base(name)
{
_reader = reader;
}
/// <inheritdoc />
public override bool CanRead => true;
/// <inheritdoc />
public override BinaryStreamReader CreateReader() => _reader.Fork();
/// <inheritdoc />
public override uint GetPhysicalSize() => _reader.Length;
/// <inheritdoc />
public override void Write(IBinaryStreamWriter writer) => _reader.Fork().WriteToOutput(writer);
/// <inheritdoc />
public override string GetStringByIndex(uint index)
{
if (!_cachedStrings.TryGetValue(index, out string value) && index < _reader.Length)
{
var stringsReader = _reader.ForkRelative(index);
// Try read length.
if (stringsReader.TryReadCompressedUInt32(out uint length))
{
if (length == 0)
return string.Empty;
// Read unicode bytes.
var data = new byte[length];
int actualLength = stringsReader.ReadBytes(data, 0, (int) length);
// Exclude the terminator byte.
value = Encoding.Unicode.GetString(data, 0, actualLength - 1);
}
_cachedStrings[index] = value;
}
return value;
}
}
}
| 34.493506 | 115 | 0.57756 | [
"MIT"
] | Anonym0ose/AsmResolver | src/AsmResolver.PE/DotNet/Metadata/UserStrings/SerializedUserStringsStream.cs | 2,656 | C# |
using System;
using System.Text;
using System.Web;
using System.Web.Http.Description;
namespace Zer0.Api.Areas.HelpPage
{
public static class ApiDescriptionExtensions
{
/// <summary>
/// Generates an URI-friendly ID for the <see cref="ApiDescription"/>. E.g. "Get-Values-id_name" instead of "GetValues/{id}?name={name}"
/// </summary>
/// <param name="description">The <see cref="ApiDescription"/>.</param>
/// <returns>The ID as a string.</returns>
public static string GetFriendlyId(this ApiDescription description)
{
string path = description.RelativePath;
string[] urlParts = path.Split('?');
string localPath = urlParts[0];
string queryKeyString = null;
if (urlParts.Length > 1)
{
string query = urlParts[1];
string[] queryKeys = HttpUtility.ParseQueryString(query).AllKeys;
queryKeyString = String.Join("_", queryKeys);
}
StringBuilder friendlyPath = new StringBuilder();
friendlyPath.AppendFormat("{0}-{1}",
description.HttpMethod.Method,
localPath.Replace("/", "-").Replace("{", String.Empty).Replace("}", String.Empty));
if (queryKeyString != null)
{
friendlyPath.AppendFormat("_{0}", queryKeyString.Replace('.', '-'));
}
return friendlyPath.ToString();
}
}
} | 38.410256 | 144 | 0.570761 | [
"MIT"
] | aquiladev/zer0 | Zer0.WA/Areas/HelpPage/ApiDescriptionExtensions.cs | 1,498 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
namespace DaleranGames.TileEngine
{
public abstract class MapTemplate : ScriptableObject
{
public abstract void GenerateMap(out DataGrid<TileBase> tiles, out DataGrid<GameObject> objects, Vector3Int origin);
public static void DrawLine<T>(T item, ref T[,] grid, Vector2Int start, Vector2Int end, int thickness, bool overwrite = false)
{
}
public static void DrawBox<T>(T item, DataGrid<T> grid, BoundsInt bounds,int z, bool fill = false, bool overwrite = false)
{
for (int y = bounds.yMin; y <= bounds.yMax; y++)
{
for (int x = bounds.xMin; x <= bounds.xMax; x++)
{
if (fill)
grid.Add(new Vector3Int(x, y, z), item, overwrite);
else
{
if (x == bounds.xMin || x == bounds.xMax || y == bounds.yMin || y == bounds.yMax)
grid.Add(new Vector3Int(x, y, z), item, overwrite);
}
}
}
}
public static void DrawCircle<T>(T item, ref T[,] grid, Vector2Int radii, Vector2Int center, bool fill = false, bool overwrite = false)
{
}
public static void LayoutObjectsAtRandom<T>(T item, DataGrid<T> grid, BoundsInt bounds, int z, float chance, bool overwrite = false)
{
for (int y = bounds.yMin; y <= bounds.yMax; y++)
{
for (int x = bounds.xMin; x <= bounds.xMax; x++)
{
if (Random.Bool(chance))
grid.Add(new Vector3Int(x, y, z), item, overwrite);
}
}
}
public static void LayoutObjectsAtRandom<T>(T[] items, DataGrid<T> grid, BoundsInt bounds, int z, float chance, bool overwrite = false)
{
for (int y = bounds.yMin; y <= bounds.yMax; y++)
{
for (int x = bounds.xMin; x <= bounds.xMax; x++)
{
if (Random.Bool(chance))
grid.Add(new Vector3Int(x, y, z), items[items.RandomArrayIndex()], overwrite);
}
}
}
public static void LayoutObjectsAtRandom<T>(T[] items, ref T[,] grid, Vector2Int bottomLeft, Vector2Int topRight, int numberOfObjects, bool overwrite = false)
{
}
public static void LayoutObjectsInPattern<T>(T[] items, ref T[,] grid, Vector2Int bottomLeft, Vector2Int topRight, Vector2Int pattern, bool overwrite = false)
{
}
public static void DrawRandomBorder<T>(T border, DataGrid<T> grid, Vector2Int borderThickness, int z, MapEdge edges, bool overwrite = false)
{
if (edges.HasFlag(MapEdge.North))
{
int thickness = Random.Int(borderThickness);
for (int x = grid.Bounds.xMin; x <= grid.Bounds.xMax; x++)
{
for (int y = grid.Bounds.yMax - thickness; y <= grid.Bounds.yMax ; y++ )
{
grid.Add(new Vector3Int(x, y, z), border, overwrite);
}
thickness = ChangeThickness(thickness, borderThickness);
}
}
if (edges.HasFlag(MapEdge.South))
{
int thickness = Random.Int(borderThickness);
for (int x = grid.Bounds.xMin; x <= grid.Bounds.xMax; x++)
{
for (int y = grid.Bounds.yMin + thickness; y >= grid.Bounds.yMin; y--)
{
grid.Add(new Vector3Int(x, y, 0), border, overwrite);
}
thickness = ChangeThickness(thickness, borderThickness);
}
}
if (edges.HasFlag(MapEdge.East))
{
int thickness = Random.Int(borderThickness);
for (int y = grid.Bounds.yMin; y <= grid.Bounds.yMax; y++)
{
for (int x = grid.Bounds.xMax - thickness; x <= grid.Bounds.xMax; x++)
{
grid.Add(new Vector3Int(x, y, 0), border, overwrite);
}
thickness = ChangeThickness(thickness, borderThickness);
}
}
if (edges.HasFlag(MapEdge.West))
{
int thickness = Random.Int(borderThickness);
for (int y = grid.Bounds.yMin; y <= grid.Bounds.yMax; y++)
{
for (int x = grid.Bounds.xMin + thickness; x >= grid.Bounds.xMin; x--)
{
grid.Add(new Vector3Int(x, y, 0), border, overwrite);
}
thickness = ChangeThickness(thickness, borderThickness);
}
}
}
static int ChangeThickness(int thickness, Vector2Int range)
{
if (Random.Bool())
{
if (Random.Bool())
thickness++;
else
thickness--;
thickness = Mathf.Clamp(thickness, range.x, range.y);
}
return thickness;
}
public static void DrawRoom<T>(T wall, T floor, Vector2Int bottomLeft, Vector2Int topRight, bool overwrite = false)
{
}
}
}
| 36.366013 | 166 | 0.489935 | [
"MIT"
] | Daleran-Games/adelaides-ph | Assets/DalLib/Tilemap/TileEngine/Templates/MapTemplate.cs | 5,566 | C# |
namespace SqlStreamStore
{
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Shouldly;
using SqlStreamStore.Infrastructure;
using SqlStreamStore.Streams;
using Xunit;
public partial class StreamStoreAcceptanceTests
{
[Theory, Trait("Category", "ReadStream")]
[MemberData(nameof(GetReadStreamForwardsTheories))]
public async Task Can_read_streams_forwards_with_prefetch(ReadStreamTheory theory)
{
using(var fixture = GetFixture())
{
using(var store = await fixture.GetStreamStore())
{
await store.AppendToStream("stream-1", ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3));
await store.AppendToStream("stream-2", ExpectedVersion.NoStream, CreateNewStreamMessages(4, 5, 6));
var streamMessagesPage =
await store.ReadStreamForwards(theory.StreamId, theory.Start, theory.PageSize);
var expectedStreamMessagesPage = theory.ExpectedReadStreamPage;
var expectedMessages = theory.ExpectedReadStreamPage.Messages.ToArray();
streamMessagesPage.FromStreamVersion.ShouldBe(expectedStreamMessagesPage.FromStreamVersion);
streamMessagesPage.LastStreamVersion.ShouldBe(expectedStreamMessagesPage.LastStreamVersion);
streamMessagesPage.NextStreamVersion.ShouldBe(expectedStreamMessagesPage.NextStreamVersion);
streamMessagesPage.ReadDirection.ShouldBe(expectedStreamMessagesPage.ReadDirection);
streamMessagesPage.IsEnd.ShouldBe(expectedStreamMessagesPage.IsEnd);
streamMessagesPage.Status.ShouldBe(expectedStreamMessagesPage.Status);
streamMessagesPage.StreamId.ShouldBe(expectedStreamMessagesPage.StreamId);
streamMessagesPage.Messages.Length.ShouldBe(expectedStreamMessagesPage.Messages.Length);
for (int i = 0; i < streamMessagesPage.Messages.Length; i++)
{
var message = streamMessagesPage.Messages.ToArray()[i];
var expectedMessage = expectedMessages[i];
message.MessageId.ShouldBe(expectedMessage.MessageId);
(await message.GetJsonData()).ShouldBe(await expectedMessage.GetJsonData());
message.JsonMetadata.ShouldBe(expectedMessage.JsonMetadata);
message.StreamId.ShouldBe(expectedMessage.StreamId);
message.StreamVersion.ShouldBe(expectedMessage.StreamVersion);
message.Type.ShouldBe(expectedMessage.Type);
// We don't care about StreamMessage.Position and StreamMessage.Position
// as they are non-deterministic
}
}
}
}
[Theory, Trait("Category", "ReadStream")]
[MemberData(nameof(GetReadStreamForwardsTheories))]
public async Task Can_read_streams_forwards_without_prefetch(ReadStreamTheory theory)
{
using (var fixture = GetFixture())
{
using (var store = await fixture.GetStreamStore())
{
await store.AppendToStream("stream-1", ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3));
await store.AppendToStream("stream-2", ExpectedVersion.NoStream, CreateNewStreamMessages(4, 5, 6));
var streamMessagesPage =
await store.ReadStreamForwards(theory.StreamId, theory.Start, theory.PageSize, false);
var expectedStreamMessagesPage = theory.ExpectedReadStreamPage;
var expectedMessages = theory.ExpectedReadStreamPage.Messages.ToArray();
streamMessagesPage.FromStreamVersion.ShouldBe(expectedStreamMessagesPage.FromStreamVersion);
streamMessagesPage.LastStreamVersion.ShouldBe(expectedStreamMessagesPage.LastStreamVersion);
streamMessagesPage.NextStreamVersion.ShouldBe(expectedStreamMessagesPage.NextStreamVersion);
streamMessagesPage.ReadDirection.ShouldBe(expectedStreamMessagesPage.ReadDirection);
streamMessagesPage.IsEnd.ShouldBe(expectedStreamMessagesPage.IsEnd);
streamMessagesPage.Status.ShouldBe(expectedStreamMessagesPage.Status);
streamMessagesPage.StreamId.ShouldBe(expectedStreamMessagesPage.StreamId);
streamMessagesPage.Messages.Length.ShouldBe(expectedStreamMessagesPage.Messages.Length);
for (int i = 0; i < streamMessagesPage.Messages.Length; i++)
{
var message = streamMessagesPage.Messages.ToArray()[i];
var expectedMessage = expectedMessages[i];
message.MessageId.ShouldBe(expectedMessage.MessageId);
(await message.GetJsonData()).ShouldBe(await expectedMessage.GetJsonData());
message.JsonMetadata.ShouldBe(expectedMessage.JsonMetadata);
message.StreamId.ShouldBe(expectedMessage.StreamId);
message.StreamVersion.ShouldBe(expectedMessage.StreamVersion);
message.Type.ShouldBe(expectedMessage.Type);
// We don't care about StreamMessage.Position and StreamMessage.Position
// as they are non-deterministic
}
}
}
}
[Fact, Trait("Category", "ReadStream")]
public async Task Can_read_whole_stream_forwards_without_prefetch()
{
using (var fixture = GetFixture())
{
using (var store = await fixture.GetStreamStore())
{
await store.AppendToStream("stream-1", ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3));
var page = await store.ReadStreamForwards("stream-1", StreamVersion.Start, 5, prefetchJsonData: false);
foreach (var streamMessage in page.Messages)
{
streamMessage.GetJsonData().IsCompleted.ShouldBeFalse();
(await streamMessage.GetJsonData()).ShouldNotBeNullOrWhiteSpace();
}
}
}
}
[Fact, Trait("Category", "ReadStream")]
public async Task Can_read_next_page_past_end_of_stream()
{
using (var fixture = GetFixture())
{
using (var store = await fixture.GetStreamStore())
{
await store.AppendToStream("stream-1", ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3));
var page = await store.ReadStreamForwards("stream-1", StreamVersion.Start, 4);
page = await page.ReadNext();
page.Messages.Length.ShouldBe(0);
}
}
}
[Fact, Trait("Category", "ReadStream")]
public async Task Can_read_all_messages()
{
using (var fixture = GetFixture())
{
using (var store = await fixture.GetStreamStore())
{
await store.AppendToStream("stream-1", ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3));
var page = await store.ReadStreamForwards("stream-1", StreamVersion.Start, int.MaxValue);
page.Messages.Length.ShouldBe(3);
}
}
}
[Theory, Trait("Category", "ReadStream")]
[MemberData(nameof(GetReadStreamBackwardsTheories))]
public async Task Can_read_streams_backwards_with_prefetch(ReadStreamTheory theory)
{
using (var fixture = GetFixture())
{
using (var store = await fixture.GetStreamStore())
{
await store.AppendToStream("stream-1", ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3));
await store.AppendToStream("stream-2", ExpectedVersion.NoStream, CreateNewStreamMessages(4, 5, 6));
var streamMessagesPage =
await store.ReadStreamBackwards(theory.StreamId, theory.Start, theory.PageSize);
var expectedStreamMessagesPage = theory.ExpectedReadStreamPage;
var expectedMessages = theory.ExpectedReadStreamPage.Messages.ToArray();
streamMessagesPage.FromStreamVersion.ShouldBe(expectedStreamMessagesPage.FromStreamVersion);
streamMessagesPage.LastStreamVersion.ShouldBe(expectedStreamMessagesPage.LastStreamVersion);
streamMessagesPage.NextStreamVersion.ShouldBe(expectedStreamMessagesPage.NextStreamVersion);
streamMessagesPage.ReadDirection.ShouldBe(expectedStreamMessagesPage.ReadDirection);
streamMessagesPage.IsEnd.ShouldBe(expectedStreamMessagesPage.IsEnd);
streamMessagesPage.Status.ShouldBe(expectedStreamMessagesPage.Status);
streamMessagesPage.StreamId.ShouldBe(expectedStreamMessagesPage.StreamId);
streamMessagesPage.Messages.Length.ShouldBe(expectedStreamMessagesPage.Messages.Length);
for (int i = 0; i < streamMessagesPage.Messages.Length; i++)
{
var streamMessage = streamMessagesPage.Messages.ToArray()[i];
var expectedMessage = expectedMessages[i];
streamMessage.MessageId.ShouldBe(expectedMessage.MessageId);
(await streamMessage.GetJsonData()).ShouldBe(await expectedMessage.GetJsonData());
streamMessage.JsonMetadata.ShouldBe(expectedMessage.JsonMetadata);
streamMessage.StreamId.ShouldBe(expectedMessage.StreamId);
streamMessage.StreamVersion.ShouldBe(expectedMessage.StreamVersion);
streamMessage.Type.ShouldBe(expectedMessage.Type);
// We don't care about StreamMessage.Position and StreamMessage.Position
// as they are non-deterministic
}
}
}
}
[Theory, Trait("Category", "ReadStream")]
[MemberData(nameof(GetReadStreamBackwardsTheories))]
public async Task Can_read_streams_backwards_without_prefetch(ReadStreamTheory theory)
{
using (var fixture = GetFixture())
{
using (var store = await fixture.GetStreamStore())
{
await store.AppendToStream("stream-1", ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3));
await store.AppendToStream("stream-2", ExpectedVersion.NoStream, CreateNewStreamMessages(4, 5, 6));
var streamMessagesPage =
await store.ReadStreamBackwards(theory.StreamId, theory.Start, theory.PageSize, false);
var expectedStreamMessagesPage = theory.ExpectedReadStreamPage;
var expectedMessages = theory.ExpectedReadStreamPage.Messages.ToArray();
streamMessagesPage.FromStreamVersion.ShouldBe(expectedStreamMessagesPage.FromStreamVersion);
streamMessagesPage.LastStreamVersion.ShouldBe(expectedStreamMessagesPage.LastStreamVersion);
streamMessagesPage.NextStreamVersion.ShouldBe(expectedStreamMessagesPage.NextStreamVersion);
streamMessagesPage.ReadDirection.ShouldBe(expectedStreamMessagesPage.ReadDirection);
streamMessagesPage.IsEnd.ShouldBe(expectedStreamMessagesPage.IsEnd);
streamMessagesPage.Status.ShouldBe(expectedStreamMessagesPage.Status);
streamMessagesPage.StreamId.ShouldBe(expectedStreamMessagesPage.StreamId);
streamMessagesPage.Messages.Length.ShouldBe(expectedStreamMessagesPage.Messages.Length);
for (int i = 0; i < streamMessagesPage.Messages.Length; i++)
{
var streamMessage = streamMessagesPage.Messages.ToArray()[i];
var expectedMessage = expectedMessages[i];
streamMessage.MessageId.ShouldBe(expectedMessage.MessageId);
(await streamMessage.GetJsonData()).ShouldBe(await expectedMessage.GetJsonData());
streamMessage.JsonMetadata.ShouldBe(expectedMessage.JsonMetadata);
streamMessage.StreamId.ShouldBe(expectedMessage.StreamId);
streamMessage.StreamVersion.ShouldBe(expectedMessage.StreamVersion);
streamMessage.Type.ShouldBe(expectedMessage.Type);
// We don't care about StreamMessage.Position and StreamMessage.Position
// as they are non-deterministic
}
}
}
}
[Fact, Trait("Category", "ReadStream")]
public async Task Can_read_stream_backwards_without_prefetch()
{
using (var fixture = GetFixture())
{
using (var store = await fixture.GetStreamStore())
{
await store.AppendToStream("stream-1", ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3));
var page = await store.ReadStreamBackwards("stream-1", StreamVersion.End, 5, prefetchJsonData: false);
foreach (var streamMessage in page.Messages)
{
streamMessage.GetJsonData().IsCompleted.ShouldBeFalse();
(await streamMessage.GetJsonData()).ShouldNotBeNullOrWhiteSpace();
}
}
}
}
[Theory, Trait("Category", "ReadStream")]
[InlineData(true), InlineData(false)]
public async Task Can_read_empty_stream_backwards(bool prefetch)
{
using (var fixture = GetFixture())
{
using (var store = await fixture.GetStreamStore())
{
await store.AppendToStream("stream-1", ExpectedVersion.NoStream, CreateNewStreamMessages());
var page = await store.ReadStreamBackwards("stream-1", StreamVersion.End, 1, prefetch);
page.Status.ShouldBe(PageReadStatus.Success);
page.Messages.Length.ShouldBe(0);
page.FromStreamVersion.ShouldBe(StreamVersion.End);
page.IsEnd.ShouldBeTrue();
page.LastStreamVersion.ShouldBe(StreamVersion.End);
page.LastStreamPosition.ShouldBe(-1);
page.NextStreamVersion.ShouldBe(StreamVersion.End);
page.ReadDirection.ShouldBe(ReadDirection.Backward);
page.StreamId.ShouldBe("stream-1");
}
}
}
[Theory, Trait("Category", "ReadStream")]
[InlineData(true), InlineData(false)]
public async Task Can_read_empty_stream_forwards(bool prefetch)
{
using (var fixture = GetFixture())
{
using (var store = await fixture.GetStreamStore())
{
await store.AppendToStream("stream-1", ExpectedVersion.NoStream, CreateNewStreamMessages());
var page = await store.ReadStreamForwards("stream-1", StreamVersion.Start, 1, prefetch);
page.Status.ShouldBe(PageReadStatus.Success);
page.Messages.Length.ShouldBe(0);
page.FromStreamVersion.ShouldBe(StreamVersion.Start);
page.IsEnd.ShouldBeTrue();
page.LastStreamVersion.ShouldBe(StreamVersion.End);
page.LastStreamPosition.ShouldBe(-1);
page.NextStreamVersion.ShouldBe(StreamVersion.Start);
page.ReadDirection.ShouldBe(ReadDirection.Forward);
page.StreamId.ShouldBe("stream-1");
}
}
}
[Fact, Trait("Category", "ReadStream")]
public async Task When_read_non_exist_stream_forwards_then_should_get_StreamNotFound()
{
using(var fixture = GetFixture())
{
using(var store = await fixture.GetStreamStore())
{
var streamMessagesPage =
await store.ReadStreamForwards("stream-does-not-exist", StreamVersion.Start, 1);
streamMessagesPage.Status.ShouldBe(PageReadStatus.StreamNotFound);
}
}
}
[Fact, Trait("Category", "ReadStream")]
public async Task When_read_non_exist_stream_backwards_then_should_get_StreamNotFound()
{
using (var fixture = GetFixture())
{
using (var store = await fixture.GetStreamStore())
{
var streamMessagesPage =
await store.ReadStreamBackwards("stream-does-not-exist", StreamVersion.End, 1);
streamMessagesPage.Status.ShouldBe(PageReadStatus.StreamNotFound);
}
}
}
[Fact, Trait("Category", "ReadStream")]
public async Task When_read_deleted_stream_forwards_then_should_get_StreamNotFound()
{
using (var fixture = GetFixture())
{
using (var store = await fixture.GetStreamStore())
{
await store.AppendToStream("stream-1", ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3));
await store.DeleteStream("stream-1");
var streamMessagesPage =
await store.ReadStreamForwards("stream-1", StreamVersion.Start, 1);
streamMessagesPage.Status.ShouldBe(PageReadStatus.StreamNotFound);
}
}
}
[Fact, Trait("Category", "ReadStream")]
public async Task When_read_deleted_stream_backwards_then_should_get_StreamNotFound()
{
using (var fixture = GetFixture())
{
using (var store = await fixture.GetStreamStore())
{
await store.AppendToStream("stream-1", ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3));
await store.DeleteStream("stream-1");
var streamMessagesPage =
await store.ReadStreamBackwards("stream-1", StreamVersion.Start, 1);
streamMessagesPage.Status.ShouldBe(PageReadStatus.StreamNotFound);
}
}
}
// ReSharper disable once UnusedMethodReturnValue.Global
public static IEnumerable<object[]> GetReadStreamForwardsTheories()
{
var theories = new[]
{
new ReadStreamTheory("stream-1", StreamVersion.Start, 2,
new ReadStreamPage("stream-1", PageReadStatus.Success, 0, 2, 2, -1, ReadDirection.Forward, false,
messages:
new [] {
ExpectedStreamMessage("stream-1", 1, 0, SystemClock.GetUtcNow()),
ExpectedStreamMessage("stream-1", 2, 1, SystemClock.GetUtcNow())
})),
new ReadStreamTheory("not-exist", 1, 2,
new ReadStreamPage("not-exist", PageReadStatus.StreamNotFound, 1, -1, -1, -1, ReadDirection.Forward, true)),
new ReadStreamTheory("stream-2", 1, 2,
new ReadStreamPage("stream-2", PageReadStatus.Success, 1, 3, 2, -1, ReadDirection.Forward, true,
messages:
new [] {
ExpectedStreamMessage("stream-2", 5, 1, SystemClock.GetUtcNow()),
ExpectedStreamMessage("stream-2", 6, 2, SystemClock.GetUtcNow())
}))
};
return theories.Select(t => new object[] { t });
}
public static IEnumerable<object[]> GetReadStreamBackwardsTheories()
{
var theories = new[]
{
new ReadStreamTheory("stream-1", StreamVersion.End, 1,
new ReadStreamPage("stream-1", PageReadStatus.Success, -1, 1, 2, -1, ReadDirection.Backward, false, messages:
new [] {
ExpectedStreamMessage("stream-1", 3, 2, SystemClock.GetUtcNow())
})),
new ReadStreamTheory("stream-1", StreamVersion.End, 2,
new ReadStreamPage("stream-1", PageReadStatus.Success, -1, 0, 2, -1, ReadDirection.Backward, false, messages:
new [] {
ExpectedStreamMessage("stream-1", 3, 2, SystemClock.GetUtcNow()),
ExpectedStreamMessage("stream-1", 2, 1, SystemClock.GetUtcNow())
})),
new ReadStreamTheory("stream-1", StreamVersion.End, 4,
new ReadStreamPage("stream-1", PageReadStatus.Success, -1, -1, 2, -1, ReadDirection.Backward, true, messages:
new [] {
ExpectedStreamMessage("stream-1", 3, 2, SystemClock.GetUtcNow()),
ExpectedStreamMessage("stream-1", 2, 1, SystemClock.GetUtcNow()),
ExpectedStreamMessage("stream-1", 1, 0, SystemClock.GetUtcNow())
}))
};
return theories.Select(t => new object[] { t });
}
public class ReadStreamTheory
{
public readonly string StreamId;
public readonly int Start;
public readonly int PageSize;
public readonly ReadStreamPage ExpectedReadStreamPage;
public ReadStreamTheory(
string streamId,
int start,
int pageSize,
ReadStreamPage expectedReadStreamPage)
{
StreamId = streamId;
Start = start;
PageSize = pageSize;
ExpectedReadStreamPage = expectedReadStreamPage;
}
}
}
}
| 49.383948 | 129 | 0.582667 | [
"MIT"
] | ddd-cqrs-es/SQLStreamStore | src/SqlStreamStore.AcceptanceTests/SqlStreamStoreAcceptanceTests.ReadStream.cs | 22,768 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace CarDealer.Web.Models.AccountViewModels
{
public class LoginViewModel
{
[Required]
[MinLength(4)]
[MaxLength(50)]
public string Username { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
}
| 22.583333 | 48 | 0.643911 | [
"MIT"
] | NikolaVodenicharov/ASP.NET-Core | CarDealer/CarDealer.Web/Models/AccountViewModels/LoginViewModel.cs | 544 | C# |
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
namespace _6MKT.Identity.Api.Extensions
{
public static class SwaggerExtension
{
public static void SwaggerServices(this IServiceCollection services)
{
services.AddSwaggerGen(c => {
c.SwaggerDoc("v1",
new OpenApiInfo
{
Title = "6MKT - Authentication",
Version = "v1",
Description = "API REST - Authentication",
Contact = new OpenApiContact
{
Name = "6MKT Corporation",
Url = new Uri("https://github.com/mateusggeracino/6mkt")
}
});
});
}
public static void SwaggerApp(this IApplicationBuilder app)
{
app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Authentication v1");
});
}
}
} | 30.684211 | 84 | 0.490566 | [
"MIT"
] | mateusggeracino/6mkt | src/backend/microservices/sso/6MKT.Identity.Api/Extensions/SwaggerExtension.cs | 1,168 | C# |
using SpeedDate.Network;
using SpeedDate.Network.Utils.IO;
namespace SpeedDate.Packets.Spawner
{
public class KillSpawnedProcessPacket : SerializablePacket
{
public int SpawnerId;
public int SpawnId;
public override void ToBinaryWriter(EndianBinaryWriter writer)
{
writer.Write(SpawnerId);
writer.Write(SpawnId);
}
public override void FromBinaryReader(EndianBinaryReader reader)
{
SpawnerId = reader.ReadInt32();
SpawnId = reader.ReadInt32();
}
}
} | 25.086957 | 72 | 0.634315 | [
"MIT"
] | proepkes/SpeedDate | SpeedDate/Packets/Spawner/KillSpawnedProcessPacket.cs | 579 | C# |
// <auto-generated />
namespace RadCBA.Core.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
public sealed partial class mig3 : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(mig3));
string IMigrationMetadata.Id
{
get { return "201902100928580_mig3"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 26.5 | 87 | 0.608805 | [
"MIT"
] | Sulzmido/Core-Banking-Application---RadCBA | RadCBA.Core/Migrations/201902100928580_mig3.Designer.cs | 795 | 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 Valve.VR
{
using System;
using UnityEngine;
public partial class SteamVR_Actions
{
private static SteamVR_Input_ActionSet_default p__default;
public static SteamVR_Input_ActionSet_default _default
{
get
{
return SteamVR_Actions.p__default.GetCopy<SteamVR_Input_ActionSet_default>();
}
}
private static void StartPreInitActionSets()
{
SteamVR_Actions.p__default = ((SteamVR_Input_ActionSet_default)(SteamVR_ActionSet.Create<SteamVR_Input_ActionSet_default>("/actions/default")));
Valve.VR.SteamVR_Input.actionSets = new Valve.VR.SteamVR_ActionSet[] {
SteamVR_Actions._default};
}
}
}
| 32.526316 | 157 | 0.527508 | [
"MIT"
] | iamrequest/blastyboy | Assets/SteamVR_Input/SteamVR_Input_ActionSets.cs | 1,236 | C# |
using System;
using System.Collections.Generic;
using System.Globalization; // Chamada para função que substitui ponto por virgula.
using System.Text;
namespace CursoCSharp.Fundamentos
{
class LendoDados
{
public static void Executar()
{
Console.Write("Qual é o seu nome? ");
string nome = Console.ReadLine();
Console.Write("Qual é a sua idade? ");
int idade = int.Parse(Console.ReadLine());
Console.Write("Qual é o seu salário? ");
double salario = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture); // Substitui ponto por virgula.
Console.WriteLine($"Seu nome é {nome}, você tem {idade} e recebe R$ {salario}");
}
}
}
| 30.32 | 124 | 0.624011 | [
"MIT"
] | filipe0li/CursoCSharp | CursoCSharp/Fundamentos/LendoDados.cs | 768 | C# |
using System;
using CoreGraphics;
namespace aRCCar.Xamarin.Game
{
public class TwoFingerTouch
{
public TwoFingerTouch(int id, CGPoint coord1, CGPoint coord2, GestureState state)
{
Id = id;
Coord1 = coord1;
Coord2 = coord2;
State = state;
}
public int Id { get; private set; }
public CGPoint Coord1 { get; private set; }
public CGPoint Coord2 { get; private set; }
public GestureState State { get; private set; }
}
}
| 24.272727 | 89 | 0.578652 | [
"MIT"
] | Trojka/ARRunner | aRCCar.Xamarin/Game/TwoFingerTouch.cs | 536 | C# |
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.Extensions.Configuration;
using System.IO;
using Roughcut.DataMartServices.Infrastructure.DbModels;
namespace Roughcut.DataMartServices.Infrastructure.DbContexts
{
public partial class DataMartServicesDbContext : DbContext
{
public DataMartServicesDbContext()
{
}
public DataMartServicesDbContext(DbContextOptions<DataMartServicesDbContext> options)
: base(options)
{
}
static DataMartServicesDbContext()
{
//Database.SetInitializer<DataMartServicesDbContext>(null);
}
//public DataMartServicesDbContext()
// : base("Name=DataMartServicesDbContext")
//{
//}
// overload/default constructer
public DataMartServicesDbContext(string dbConnString)
//: base(dbConnString)
{
// google search:
// https://www.google.com/search?q=how+to+use+Microsoft.Extensions.Configuration
// https://swimburger.net/blog/dotnet/using-configurationproviders-from-microsoft-extensions-configuration-on-dotnet-framework
var configuration = new ConfigurationBuilder()
//.SetBasePath(Directory.GetCurrentDirectory())
//.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
//// https://stackoverflow.com/questions/65564889/established-dependency-injection-in-net-core-console-application-for-ef-core-db
////.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
//// https://stackoverflow.com/questions/42268265/how-to-get-manage-user-secrets-in-a-net-core-console-application
//// https://github.com/dotnet/extensions/issues/2743
//.AddUserSecrets<ConnectionStrings>(optional: false)
//.AddEnvironmentVariables()
.Build();
//
DbContextOptionsBuilder optionsBuilder = new DbContextOptionsBuilder();
//
optionsBuilder.UseSqlServer(dbConnString);
//
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<DimDateTime> DimDateTime { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Data Source=(localdb)\\mssqllocaldb;Initial Catalog=DataMartServices;Integrated Security=True");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<DimDateTime>(entity =>
{
entity.HasKey(e => e.DimDateTimeKeyId)
.HasName("PK_dbo.DimDateTime");
entity.Property(e => e.DimDateTimeKeyId).ValueGeneratedNever();
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
} | 38.315789 | 214 | 0.633516 | [
"MIT"
] | roughcutsoftware/DataMartServices | src/Roughcut.DataMartServices.Infrastructure/Data/DbContexts/DataMartServicesDbContext.cs | 3,642 | C# |
using Lucene.Net.Analysis.Tokenattributes;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Lucene.Net.Util;
using NUnit.Framework;
using System.IO;
namespace Lucene.Net.Analysis.Core
{
/*
* 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.
*/
public class TestKeywordAnalyzer : BaseTokenStreamTestCase
{
private Store.Directory directory;
private IndexSearcher searcher;
private IndexReader reader;
public override void SetUp()
{
base.SetUp();
directory = NewDirectory();
IndexWriter writer = new IndexWriter(directory, new IndexWriterConfig(TEST_VERSION_CURRENT, new SimpleAnalyzer(TEST_VERSION_CURRENT)));
Document doc = new Document();
doc.Add(new StringField("partnum", "Q36", Field.Store.YES));
doc.Add(new TextField("description", "Illidium Space Modulator", Field.Store.YES));
writer.AddDocument(doc);
writer.Dispose();
reader = DirectoryReader.Open(directory);
searcher = NewSearcher(reader);
}
public override void TearDown()
{
reader.Dispose();
directory.Dispose();
base.TearDown();
}
/*
public void testPerFieldAnalyzer() throws Exception {
PerFieldAnalyzerWrapper analyzer = new PerFieldAnalyzerWrapper(new SimpleAnalyzer(TEST_VERSION_CURRENT));
analyzer.addAnalyzer("partnum", new KeywordAnalyzer());
QueryParser queryParser = new QueryParser(TEST_VERSION_CURRENT, "description", analyzer);
Query query = queryParser.parse("partnum:Q36 AND SPACE");
ScoreDoc[] hits = searcher.search(query, null, 1000).scoreDocs;
assertEquals("Q36 kept as-is",
"+partnum:Q36 +space", query.toString("description"));
assertEquals("doc found!", 1, hits.length);
}
*/
[Test]
public virtual void TestMutipleDocument()
{
RAMDirectory dir = new RAMDirectory();
IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new KeywordAnalyzer()));
Document doc = new Document();
doc.Add(new TextField("partnum", "Q36", Field.Store.YES));
writer.AddDocument(doc);
doc = new Document();
doc.Add(new TextField("partnum", "Q37", Field.Store.YES));
writer.AddDocument(doc);
writer.Dispose();
IndexReader reader = DirectoryReader.Open(dir);
DocsEnum td = TestUtil.Docs(Random(), reader, "partnum", new BytesRef("Q36"), MultiFields.GetLiveDocs(reader), null, 0);
assertTrue(td.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
td = TestUtil.Docs(Random(), reader, "partnum", new BytesRef("Q37"), MultiFields.GetLiveDocs(reader), null, 0);
assertTrue(td.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
}
// LUCENE-1441
[Test]
public virtual void TestOffsets()
{
TokenStream stream = (new KeywordAnalyzer()).TokenStream("field", new StringReader("abcd"));
try
{
IOffsetAttribute offsetAtt = stream.AddAttribute<IOffsetAttribute>();
stream.Reset();
assertTrue(stream.IncrementToken());
assertEquals(0, offsetAtt.StartOffset());
assertEquals(4, offsetAtt.EndOffset());
assertFalse(stream.IncrementToken());
stream.End();
}
finally
{
IOUtils.CloseWhileHandlingException(stream);
}
}
/// <summary>
/// blast some random strings through the analyzer </summary>
[Test]
public virtual void TestRandomStrings()
{
CheckRandomData(Random(), new KeywordAnalyzer(), 1000 * RANDOM_MULTIPLIER);
}
}
} | 38.669355 | 147 | 0.624192 | [
"Apache-2.0"
] | BlueCurve-Team/lucenenet | src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestKeywordAnalyzer.cs | 4,797 | C# |
/* ============================================================================================================================
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
* =========================================================================================================================== */
using System;
using System.Web;
using System.Net;
using System.IO;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Recaptcha.Web.Configuration;
using Microsoft.AspNetCore.Http;
namespace Recaptcha.Web
{
/// <summary>
/// Represents the functionality for verifying user's response to the recpatcha challenge.
/// </summary>
public class RecaptchaVerificationHelper
{
#region Constructors
private RecaptchaVerificationHelper()
{ }
/// <summary>
/// Creates an instance of the <see cref="RecaptchaVerificationHelper"/> class.
/// </summary>
/// <param name="secretKey">Sets the secret key of the reCAPTCHA verification request.</param>
internal RecaptchaVerificationHelper(HttpContext httpContext, string secretKey)
{
if (String.IsNullOrEmpty(secretKey))
{
throw new InvalidOperationException("Private key cannot be null or empty.");
}
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
var request = httpContext.Request;
this.UseSsl = request.IsHttps;
this.SecretKey = secretKey;
this.UserHostAddress = request.Path.Value;
Response = request.Form["g-recaptcha-response"];
}
#endregion Constructors
#region Properties
/// <summary>
/// Determines if HTTPS intead of HTTP is to be used in reCAPTCHA verification API calls.
/// </summary>
public bool UseSsl
{
get;
private set;
}
/// <summary>
/// Gets the privae key of the recaptcha verification request.
/// </summary>
public string SecretKey
{
get;
private set;
}
/// <summary>
/// Gets the user's host address of the recaptcha verification request.
/// </summary>
public string UserHostAddress
{
get;
private set;
}
/// <summary>
/// Gets the user's response to the recaptcha challenge of the recaptcha verification request.
/// </summary>
public string Response
{
get;
private set;
}
#endregion Properties
#region Public Methods
/// <summary>
/// Verifies whether the user's response to the recaptcha request is correct.
/// </summary>
/// <returns>Returns the result as a value of the <see cref="RecaptchaVerificationResult"/> enum.</returns>
public RecaptchaVerificationResult VerifyRecaptchaResponse()
{
if (string.IsNullOrEmpty(Response))
{
return new RecaptchaVerificationResult { Success = false };
}
string secretKey = SecretKey;
if(string.IsNullOrEmpty(secretKey))
{
var config = RecaptchaConfigurationManager.GetConfiguration();
secretKey = config.SecretKey;
}
return VerifyRecpatcha2Response(secretKey);
}
/// <summary>
/// Verifies whether the user's response to the recaptcha request is correct.
/// </summary>
/// <returns>Returns the result as a value of the <see cref="RecaptchaVerificationResult"/> enum.</returns>
public Task<RecaptchaVerificationResult> VerifyRecaptchaResponseTaskAsync()
{
if (string.IsNullOrEmpty(Response))
{
Task<RecaptchaVerificationResult>.Factory.StartNew(()=>
{
return new RecaptchaVerificationResult { Success = false };
});
}
string secretKey = SecretKey;
if (string.IsNullOrEmpty(secretKey))
{
var config = RecaptchaConfigurationManager.GetConfiguration();
secretKey = config.SecretKey;
}
return VerifyRecpatcha2ResponseTaskAsync(secretKey);
}
#endregion Public Methods
#region Private Methods
private Task<RecaptchaVerificationResult> VerifyRecpatcha2ResponseTaskAsync(string secretKey)
{
Task<RecaptchaVerificationResult> taskResult = Task<RecaptchaVerificationResult>.Factory.StartNew(() =>
{
string postData = String.Format("secret={0}&response={1}&remoteip={2}", secretKey, this.Response, this.UserHostAddress);
byte[] postDataBuffer = System.Text.Encoding.ASCII.GetBytes(postData);
Uri verifyUri = null;
verifyUri = new Uri("https://www.google.com/recaptcha/api/siteverify", UriKind.Absolute);
try
{
var webRequest = (HttpWebRequest)WebRequest.Create(verifyUri);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postDataBuffer.Length;
webRequest.Method = "POST";
var proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
webRequest.Proxy = proxy;
using (var requestStream = webRequest.GetRequestStream())
{
requestStream.Write(postDataBuffer, 0, postDataBuffer.Length);
}
var webResponse = (HttpWebResponse)webRequest.GetResponse();
string sResponse = null;
using (var sr = new StreamReader(webResponse.GetResponseStream()))
{
sResponse = sr.ReadToEnd();
}
return JsonConvert.DeserializeObject<RecaptchaVerificationResult>(sResponse);
}
catch (Exception ex)
{
throw ex;
}
});
return taskResult;
}
private RecaptchaVerificationResult VerifyRecpatcha2Response(string secretKey)
{
string postData = String.Format("secret={0}&response={1}&remoteip={2}", secretKey, this.Response, this.UserHostAddress);
byte[] postDataBuffer = System.Text.Encoding.ASCII.GetBytes(postData);
Uri verifyUri = new Uri("https://www.google.com/recaptcha/api/siteverify", UriKind.Absolute);
try
{
var webRequest = (HttpWebRequest)WebRequest.Create(verifyUri);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postDataBuffer.Length;
webRequest.Method = "POST";
var proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
webRequest.Proxy = proxy;
using (var requestStream = webRequest.GetRequestStream())
{
requestStream.Write(postDataBuffer, 0, postDataBuffer.Length);
}
var webResponse = (HttpWebResponse)webRequest.GetResponse();
string sResponse = null;
using (var sr = new StreamReader(webResponse.GetResponseStream()))
{
sResponse = sr.ReadToEnd();
}
return JsonConvert.DeserializeObject<RecaptchaVerificationResult>(sResponse);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion Private Methods
}
}
| 34.341667 | 136 | 0.551929 | [
"Apache-2.0"
] | edika99/recaptcha-net | src/Recaptcha.Web-netcoreapp3.1/RecaptchaVerificationHelper.cs | 8,244 | C# |
using System;
using System.IO;
using FluentAssertions;
using TestableFileSystem.Fakes.Builders;
using TestableFileSystem.Interfaces;
using Xunit;
namespace TestableFileSystem.Fakes.Tests.Specs.FakeDirectory
{
public sealed class DirectoryTimeLastAccessUtcSpecs
{
private static readonly DateTime DefaultTimeUtc = 1.February(2034).At(12, 34, 56).AsUtc();
private static readonly DateTime HighTimeUtc = DateTime.MaxValue.AddDays(-2).AsUtc();
private static readonly DateTime ZeroFileTimeUtc = 1.January(1601).AsUtc();
[Fact]
private void When_getting_last_access_time_in_UTC_for_null_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
// ReSharper disable once AssignNullToNotNullAttribute
Action action = () => fileSystem.Directory.GetLastAccessTimeUtc(null);
// Assert
action.ShouldThrow<ArgumentNullException>();
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_null_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
// ReSharper disable once AssignNullToNotNullAttribute
Action action = () => fileSystem.Directory.SetLastAccessTimeUtc(null, DefaultTimeUtc);
// Assert
action.ShouldThrow<ArgumentNullException>();
}
[Fact]
private void When_getting_last_access_time_in_UTC_for_empty_string_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.GetLastAccessTimeUtc(string.Empty);
// Assert
action.ShouldThrow<ArgumentException>().WithMessage("The path is not of a legal form.*");
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_empty_string_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTimeUtc(string.Empty, DefaultTimeUtc);
// Assert
action.ShouldThrow<ArgumentException>().WithMessage("The path is not of a legal form.*");
}
[Fact]
private void When_getting_last_access_time_in_UTC_for_whitespace_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.GetLastAccessTimeUtc(" ");
// Assert
action.ShouldThrow<ArgumentException>().WithMessage("The path is not of a legal form.*");
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_whitespace_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTimeUtc(" ", DefaultTimeUtc);
// Assert
action.ShouldThrow<ArgumentException>().WithMessage("The path is not of a legal form.*");
}
[Fact]
private void When_getting_last_access_time_in_UTC_for_invalid_root_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.GetLastAccessTimeUtc("::");
// Assert
action.ShouldThrow<NotSupportedException>().WithMessage("The given path's format is not supported.");
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_invalid_root_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTimeUtc("::", DefaultTimeUtc);
// Assert
action.ShouldThrow<NotSupportedException>().WithMessage("The given path's format is not supported.");
}
[Fact]
private void When_getting_last_access_time_in_UTC_for_invalid_characters_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.GetLastAccessTimeUtc(@"c:\dir?i");
// Assert
action.ShouldThrow<ArgumentException>().WithMessage("Illegal characters in path.*");
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_invalid_characters_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTimeUtc(@"c:\dir?i", DefaultTimeUtc);
// Assert
action.ShouldThrow<ArgumentException>().WithMessage("Illegal characters in path.*");
}
[Fact]
private void When_getting_last_access_time_in_UTC_for_missing_directory_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"C:\some")
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTimeUtc(@"C:\some\nested");
// Assert
time.Should().Be(ZeroFileTimeUtc);
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_missing_directory_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"C:\some")
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTimeUtc(@"C:\some\nested", DefaultTimeUtc);
// Assert
action.ShouldThrow<FileNotFoundException>().WithMessage(@"Could not find file 'C:\some\nested'.");
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_existing_directory_it_must_succeed()
{
// Arrange
const string path = @"C:\some";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(path)
.Build();
// Act
fileSystem.Directory.SetLastAccessTimeUtc(path, DefaultTimeUtc);
// Assert
fileSystem.Directory.GetLastAccessTimeUtc(path).Should().Be(DefaultTimeUtc);
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_existing_directory_with_trailing_whitespace_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"C:\some")
.Build();
// Act
fileSystem.Directory.SetLastAccessTimeUtc(@"C:\some ", DefaultTimeUtc);
// Assert
fileSystem.Directory.GetLastAccessTimeUtc(@"C:\some ").Should().Be(DefaultTimeUtc);
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_existing_readonly_directory_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"C:\some", FileAttributes.ReadOnly)
.Build();
// Act
fileSystem.Directory.SetLastAccessTimeUtc(@"C:\some", DefaultTimeUtc);
// Assert
fileSystem.Directory.GetLastAccessTimeUtc(@"C:\some").Should().Be(DefaultTimeUtc);
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_existing_subdirectory_in_readonly_directory_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"c:\folder", FileAttributes.ReadOnly)
.IncludingDirectory(@"C:\folder\some")
.Build();
// Act
fileSystem.Directory.SetLastAccessTimeUtc(@"C:\folder\some", DefaultTimeUtc);
// Assert
fileSystem.Directory.GetLastAccessTimeUtc(@"C:\folder\some").Should().Be(DefaultTimeUtc);
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_current_directory_it_must_succeed()
{
// Arrange
const string path = @"C:\some\folder";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(path)
.Build();
fileSystem.Directory.SetCurrentDirectory(path);
// Act
fileSystem.Directory.SetLastAccessTimeUtc(path, DefaultTimeUtc);
// Assert
fileSystem.Directory.GetLastAccessTimeUtc(path).Should().Be(DefaultTimeUtc);
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_existing_directory_to_MinValue_it_must_fail()
{
// Arrange
const string path = @"C:\some";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(path)
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTimeUtc(path, DateTime.MinValue);
// Assert
action.ShouldThrow<ArgumentOutOfRangeException>().WithMessage("Not a valid Win32 FileTime.*");
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_existing_directory_to_MaxValue_it_must_succeed()
{
// Arrange
const string path = @"C:\some";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(path)
.Build();
// Act
fileSystem.Directory.SetLastAccessTimeUtc(path, HighTimeUtc);
// Assert
fileSystem.Directory.GetLastAccessTimeUtc(path).Should().Be(HighTimeUtc);
}
[Fact]
private void When_getting_last_access_time_in_UTC_for_drive_it_must_succeed()
{
// Arrange
const string path = @"C:\";
var clock = new SystemClock { UtcNow = () => DefaultTimeUtc };
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingDirectory(path)
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTimeUtc(path);
// Assert
time.Should().Be(DefaultTimeUtc);
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_drive_it_must_fail()
{
// Arrange
const string path = @"C:\";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(path)
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTimeUtc(path, DefaultTimeUtc);
// Assert
action.ShouldThrow<ArgumentException>().WithMessage("Path must not be a drive.*");
}
[Fact]
private void When_getting_last_access_time_in_UTC_using_absolute_path_without_drive_letter_it_must_succeed()
{
// Arrange
var clock = new SystemClock { UtcNow = () => DefaultTimeUtc };
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingDirectory(@"c:\some")
.IncludingDirectory(@"C:\folder")
.Build();
fileSystem.Directory.SetCurrentDirectory(@"C:\some");
// Act
DateTime time = fileSystem.Directory.GetLastAccessTimeUtc(@"\folder");
// Assert
time.Should().Be(DefaultTimeUtc);
}
[Fact]
private void When_setting_last_access_time_in_UTC_using_absolute_path_without_drive_letter_it_must_succeed()
{
// Arrange
var clock = new SystemClock { UtcNow = () => DefaultTimeUtc };
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingDirectory(@"c:\some")
.IncludingDirectory(@"C:\folder")
.Build();
fileSystem.Directory.SetCurrentDirectory(@"C:\some");
// Act
fileSystem.Directory.SetLastAccessTimeUtc(@"\folder", DefaultTimeUtc);
// Assert
fileSystem.Directory.GetLastAccessTimeUtc(@"c:\folder").Should().Be(DefaultTimeUtc);
}
[Fact]
private void When_getting_last_access_time_in_UTC_for_existing_relative_local_directory_it_must_succeed()
{
// Arrange
var clock = new SystemClock { UtcNow = () => DefaultTimeUtc };
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingDirectory(@"C:\folder\some")
.Build();
fileSystem.Directory.SetCurrentDirectory(@"c:\folder");
// Act
DateTime time = fileSystem.Directory.GetLastAccessTimeUtc(@"some");
// Assert
time.Should().Be(DefaultTimeUtc);
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_existing_relative_local_directory_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"C:\folder\some")
.Build();
fileSystem.Directory.SetCurrentDirectory(@"c:\folder");
// Act
fileSystem.Directory.SetLastAccessTimeUtc(@"some", DefaultTimeUtc);
// Assert
fileSystem.Directory.GetLastAccessTimeUtc(@"C:\folder\some").Should().Be(DefaultTimeUtc);
}
[Fact]
private void When_getting_last_access_time_in_UTC_for_existing_local_directory_with_different_casing_it_must_succeed()
{
// Arrange
var clock = new SystemClock { UtcNow = () => DefaultTimeUtc };
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingDirectory(@"C:\FOLDER\some")
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTimeUtc(@"C:\folder\SOME");
// Assert
time.Should().Be(DefaultTimeUtc);
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_existing_local_directory_with_different_casing_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"C:\FOLDER\some")
.Build();
// Act
fileSystem.Directory.SetLastAccessTimeUtc(@"C:\folder\SOME", DefaultTimeUtc);
// Assert
fileSystem.Directory.GetLastAccessTimeUtc(@"C:\FOLDER\some").Should().Be(DefaultTimeUtc);
}
[Fact]
private void When_getting_last_access_time_in_UTC_for_missing_parent_directory_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTimeUtc(@"C:\some\folder");
// Assert
time.Should().Be(ZeroFileTimeUtc);
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_missing_parent_directory_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTimeUtc(@"C:\some\folder", DefaultTimeUtc);
// Assert
action.ShouldThrow<DirectoryNotFoundException>()
.WithMessage(@"Could not find a part of the path 'C:\some\folder'.");
}
[Fact]
private void When_getting_last_access_time_in_UTC_for_existing_file_it_must_succeed()
{
// Arrange
const string path = @"C:\some\file.txt";
var clock = new SystemClock { UtcNow = () => DefaultTimeUtc };
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingEmptyFile(path)
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTimeUtc(path);
// Assert
time.Should().Be(DefaultTimeUtc);
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_existing_file_it_must_succeed()
{
// Arrange
const string path = @"C:\some\file.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(path)
.Build();
// Act
fileSystem.Directory.SetLastAccessTimeUtc(path, DefaultTimeUtc);
// Assert
fileSystem.Directory.GetLastAccessTimeUtc(path).Should().Be(DefaultTimeUtc);
}
[Fact]
private void When_getting_last_access_time_in_UTC_for_parent_directory_that_exists_as_file_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(@"c:\some\file.txt")
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTimeUtc(@"c:\some\file.txt\nested.txt");
// Assert
time.Should().Be(ZeroFileTimeUtc);
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_parent_directory_that_exists_as_file_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(@"c:\some\file.txt")
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTimeUtc(@"c:\some\file.txt\nested", DefaultTimeUtc);
// Assert
action.ShouldThrow<DirectoryNotFoundException>()
.WithMessage(@"Could not find a part of the path 'c:\some\file.txt\nested'.");
}
[Fact]
private void When_getting_last_access_time_in_UTC_for_parent_parent_directory_that_exists_as_file_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(@"c:\some\file.txt")
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTimeUtc(@"c:\some\file.txt\nested\more");
// Assert
time.Should().Be(ZeroFileTimeUtc);
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_parent_parent_directory_that_exists_as_file_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(@"c:\some\file.txt")
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTimeUtc(@"c:\some\file.txt\nested\more", DefaultTimeUtc);
// Assert
action.ShouldThrow<DirectoryNotFoundException>()
.WithMessage(@"Could not find a part of the path 'c:\some\file.txt\nested\more'.");
}
[Fact]
private void When_getting_last_access_time_in_UTC_for_missing_network_share_it_must_fail()
{
// Arrange
const string path = @"\\server\share\missing";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.GetLastAccessTimeUtc(path);
// Assert
action.ShouldThrow<IOException>().WithMessage("The network path was not found");
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_missing_network_share_it_must_fail()
{
// Arrange
const string path = @"\\server\share\missing";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTimeUtc(path, DefaultTimeUtc);
// Assert
action.ShouldThrow<IOException>().WithMessage("The network path was not found");
}
[Fact]
private void When_getting_last_access_time_in_UTC_for_existing_network_share_it_must_succeed()
{
// Arrange
const string path = @"\\server\share";
var clock = new SystemClock { UtcNow = () => DefaultTimeUtc };
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingDirectory(path)
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTimeUtc(path);
// Assert
time.Should().Be(DefaultTimeUtc);
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_existing_network_share_it_must_succeed()
{
// Arrange
const string path = @"\\server\share";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(path)
.Build();
// Act
fileSystem.Directory.SetLastAccessTimeUtc(path, DefaultTimeUtc);
// Assert
fileSystem.Directory.GetLastAccessTimeUtc(path).Should().Be(DefaultTimeUtc);
}
[Fact]
private void When_getting_last_access_time_in_UTC_for_missing_remote_directory_it_must_succeed()
{
// Arrange
const string path = @"\\server\share\missing";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"\\server\share")
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTimeUtc(path);
// Assert
time.Should().Be(ZeroFileTimeUtc);
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_missing_remote_directory_it_must_fail()
{
// Arrange
const string path = @"\\server\share\missing";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"\\server\share")
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTimeUtc(path, DefaultTimeUtc);
// Assert
action.ShouldThrow<FileNotFoundException>().WithMessage(@"Could not find file '\\server\share\missing'.");
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_existing_remote_directory_it_must_succeed()
{
// Arrange
const string path = @"\\server\share\personal";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(path)
.Build();
// Act
fileSystem.Directory.SetLastAccessTimeUtc(path, DefaultTimeUtc);
// Assert
fileSystem.Directory.GetLastAccessTimeUtc(path).Should().Be(DefaultTimeUtc);
}
[Fact]
private void When_getting_last_access_time_in_UTC_for_reserved_name_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.GetLastAccessTimeUtc("COM1");
// Assert
action.ShouldThrow<PlatformNotSupportedException>().WithMessage("Reserved names are not supported.");
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_reserved_name_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTimeUtc("COM1", DefaultTimeUtc);
// Assert
action.ShouldThrow<PlatformNotSupportedException>().WithMessage("Reserved names are not supported.");
}
[Fact]
private void When_getting_last_access_time_in_UTC_for_missing_extended_local_directory_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"c:\some")
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTimeUtc(@"\\?\C:\some\missing");
// Assert
time.Should().Be(ZeroFileTimeUtc);
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_missing_extended_local_directory_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"c:\some")
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTimeUtc(@"\\?\C:\some\missing", DefaultTimeUtc);
// Assert
action.ShouldThrow<FileNotFoundException>().WithMessage(@"Could not find file '\\?\C:\some\missing'.");
}
[Fact]
private void When_setting_last_access_time_in_UTC_for_existing_extended_local_directory_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"C:\some\other")
.Build();
// Act
fileSystem.Directory.SetLastAccessTimeUtc(@"\\?\C:\some\other", DefaultTimeUtc);
// Assert
fileSystem.Directory.GetLastAccessTimeUtc(@"\\?\C:\some\other").Should().Be(DefaultTimeUtc);
}
}
}
| 34.460938 | 126 | 0.591589 | [
"Apache-2.0"
] | sankarpraveen02/sample | src/Fakes.Tests/Specs/FakeDirectory/DirectoryTimeLastAccessUtcSpecs.cs | 26,468 | C# |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Collections.Concurrent;
namespace ASTool
{
// class used to store the offset of each moof box in the file
// based on the time associated with the moof box
public class TimeMoofOffset
{
public TimeMoofOffset(ulong Time, ulong Offset)
{
time = Time;
offset = Offset;
}
public ulong time;
public ulong offset;
}
[DataContract(Name = "ChunkListConfiguration")]
public class ChunkListConfiguration
{
public ChunkListConfiguration()
{
CreateTimeOffsetList();
}
[DataMember]
public int TrackID { get; set; }
[DataMember]
public string FourCC { get; set; }
[DataMember]
public int TimeScale { get; set; }
[DataMember]
public long Duration { get; set; }
[DataMember]
public int Bitrate { get; set; }
[DataMember]
public string Language { get; set; }
[DataMember]
public string TrackName { get; set; }
[DataMember]
public string Source { get; set; }
[DataMember]
public string CustomAttributes { get; set; }
/// <summary>
/// Get Protection Guid.
/// </summary>
[DataMember]
public Guid ProtectionGuid { get; set; }
/// <summary>
/// Get Protection Data.
/// </summary>
[DataMember]
public string ProtectionData { get; set; }
public byte[] GetFTYPData()
{
ISMHelper.Mp4Box box = ISMHelper.Mp4Box.CreateFTYPBox();
if (box != null)
return box.GetBoxBytes();
return null;
}
public virtual byte[] GetMOOVData()
{
return null;
}
public virtual string GetSourceName()
{
return Source + "_" + Bitrate.ToString() + "_" + (string.IsNullOrEmpty(TrackName) ? "unknown" :TrackName.ToString() );
}
protected List<TimeMoofOffset> ListTimeOffset;
public bool CreateTimeOffsetList()
{
ListTimeOffset = new List<TimeMoofOffset>();
return ListTimeOffset != null;
}
public bool AddTimeOffset(ulong Time, ulong Offset)
{
try
{
if (ListTimeOffset != null)
ListTimeOffset.Add(new TimeMoofOffset(Time, Offset));
}
catch(Exception)
{
return false;
}
return true;
}
public virtual byte[] GetMFRAData(ulong OffsetWithVideo)
{
ISMHelper.Mp4Box box = ISMHelper.Mp4Box.CreateMFRABox((Int16)TrackID,ListTimeOffset, OffsetWithVideo);
if (box != null)
return box.GetBoxBytes();
return null;
}
}
[DataContract(Name = "VideoChunkListConfiguration")]
public class VideoChunkListConfiguration : ChunkListConfiguration
{
[DataMember]
public int Width { get; set; }
[DataMember]
public int Height { get; set; }
[DataMember]
public string CodecPrivateData { get; set; }
public override byte[] GetMOOVData()
{
ISMHelper.Mp4Box box = ISMHelper.Mp4Box.CreateVideoMOOVBox((Int16) TrackID, (Int16)Width, (Int16)Height, TimeScale, Duration, Language, CodecPrivateData,ProtectionGuid,ProtectionData);
if (box != null)
return box.GetBoxBytes();
return null;
}
}
[DataContract(Name = "AudioChunkListConfiguration")]
public class AudioChunkListConfiguration : ChunkListConfiguration
{
[DataMember]
public int BitsPerSample { get; set; }
[DataMember]
public int Channels { get; set; }
[DataMember]
public int SamplingRate { get; set; }
[DataMember]
public string CodecPrivateData { get; set; }
[DataMember]
public int MaxFramesize { get; set; }
[DataMember]
public string AudioTag { get; set; }
[DataMember]
public int PacketSize { get; set; }
public override byte[] GetMOOVData()
{
ISMHelper.Mp4Box box = ISMHelper.Mp4Box.CreateAudioMOOVBox((Int16)TrackID,MaxFramesize,Bitrate,BitsPerSample,SamplingRate,Channels, TimeScale, Duration, Language, CodecPrivateData, ProtectionGuid, ProtectionData);
if (box != null)
return box.GetBoxBytes();
return null;
}
}
[DataContract(Name = "TextChunkListConfiguration")]
public class TextChunkListConfiguration : ChunkListConfiguration
{
public override byte[] GetMOOVData()
{
ISMHelper.Mp4Box box = ISMHelper.Mp4Box.CreateTextMOOVBox((Int16)TrackID, TimeScale,Duration,Language, ProtectionGuid, ProtectionData);
if (box != null)
return box.GetBoxBytes();
return null;
}
}
[DataContract(Name = "ChunkList")]
public class ChunkList : IDisposable
{
public object ListLock;
/// <summary>
/// LastDataOffset
/// Last Data Offset used to build the mfra box
/// </summary>
public ulong LastDataOffset { get; set; }
/// <summary>
/// Chunks
/// The number of chunks for this asset
/// </summary>
[DataMember]
public ulong TotalChunks { get; set; }
/// <summary>
/// InputChunks
/// The number of chunks downloaded
/// </summary>
[DataMember]
public ulong InputChunks { get; set; }
/// <summary>
/// OutputChunks
/// The number of chunks in the archive
/// </summary>
[DataMember]
public ulong OutputChunks { get; set; }
/// <summary>
/// InputChunks
/// The number of bytes downloaded
/// </summary>
[DataMember]
public ulong InputBytes { get; set; }
/// <summary>
/// OutputChunks
/// The number of bytes in the archive
/// </summary>
[DataMember]
public ulong OutputBytes { get; set; }
/// <summary>
/// ChunksToReadQueue
/// List of the chunks to read
/// </summary>
public ConcurrentQueue<ChunkBuffer> ChunksToReadQueue { get; set; }
/// <summary>
/// LastTimeChunksToRead
/// The Time of the last Chunk to read
/// </summary>
public ulong LastTimeChunksToRead { get; set; }
/// <summary>
/// Time of the first Chunk downloaded
/// </summary>
public ulong TimeFirstChunk { get; set; }
/// <summary>
/// Time of the last Chunk downloaded
/// </summary>
public ulong TimeLastChunk { get; set; }
/// <summary>
/// ChunksQueue
/// List of the chunks read
/// </summary>
public ConcurrentQueue<ChunkBuffer> ChunksQueue { get; set; }
/// <summary>
/// Original TemplateUrl
/// The Url template to download the chunks
/// </summary>
[DataMember]
public string OriginalTemplateUrl { get; set; }
/// <summary>
/// TemplateUrl
/// The Url template to download the chunks
/// </summary>
[DataMember]
public string TemplateUrl { get; set; }
/// <summary>
/// TemplateUrlType
/// Type in the Url template to download the chunks
/// </summary>
[DataMember]
public string TemplateUrlType { get; set; }
/// <summary>
/// Amount of memory used to store chunks
/// </summary>
public ulong MemorySizeForChunks { get; set; }
/// <summary>
/// Bitrate
/// Bitrate of the track
/// </summary>
[DataMember]
public int Bitrate { get; set; }
/// <summary>
/// Chunklist Configuration
/// Contains information to create moov and ftyp chunks
/// </summary>
public ChunkListConfiguration Configuration { get; set; }
/// <summary>
/// moovData
/// Contains the moov box for this chunk list
/// </summary>
public byte[] moovData;
/// <summary>
/// ftypData
/// Contains the ftyp box for this chunk list
/// </summary>
public byte[] ftypData;
/// <summary>
/// mfraData
/// Contains the mfra box for this chunk list, the mfra box is inserted at the end of the chunk list.
/// </summary>
public byte[] mfraData;
/// <summary>
/// GetType
/// Get Type from the url template.
/// </summary>
/// <param name="source">Source url</param>
/// <returns>string Type included in the source url</returns>
public static string GetType(string Template)
{
string[] url = Template.ToLower().Split('/');
string type = string.Empty;
try
{
if (Template.ToLower().Contains("/fragments("))
{
//url = "fragments(audio=0)"
string[] keys = { "(", "=", ")" };
url = url[url.Length - 1].Split(keys, StringSplitOptions.RemoveEmptyEntries);
type = url[url.Length - 2];
}
}
catch (Exception)
{
}
return type;
}
public bool AreChunksDownloaded()
{
return (TotalChunks == InputChunks);
}
public bool AreChunksArchived()
{
return (TotalChunks == OutputChunks);
}
public ChunkList() {
ChunksToReadQueue = new ConcurrentQueue<ChunkBuffer>();
LastTimeChunksToRead = 0;
TimeFirstChunk = 0;
TimeLastChunk = 0;
ChunksQueue = new ConcurrentQueue<ChunkBuffer>();
MemorySizeForChunks = 0;
ListLock = new object();
}
public void Dispose()
{
if(ChunksToReadQueue != null)
{
foreach(var c in ChunksToReadQueue)
{
c.Dispose();
}
ChunksToReadQueue.Clear();
}
if (ChunksQueue != null)
{
foreach (var c in ChunksQueue)
{
c.Dispose();
}
ChunksQueue.Clear();
}
MemorySizeForChunks = 0;
}
}
}
| 29.907895 | 225 | 0.529168 | [
"MIT"
] | flecoqui/ASTool | cs/ASTool/ASTool/ChunkList.cs | 11,367 | C# |
/*
* Copyright 2010-2014 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 neptune-2014-10-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Neptune.Model
{
/// <summary>
/// Provides information about a pending maintenance action for a resource.
/// </summary>
public partial class PendingMaintenanceAction
{
private string _action;
private DateTime? _autoAppliedAfterDate;
private DateTime? _currentApplyDate;
private string _description;
private DateTime? _forcedApplyDate;
private string _optInStatus;
/// <summary>
/// Gets and sets the property Action.
/// <para>
/// The type of pending maintenance action that is available for the resource.
/// </para>
/// </summary>
public string Action
{
get { return this._action; }
set { this._action = value; }
}
// Check to see if Action property is set
internal bool IsSetAction()
{
return this._action != null;
}
/// <summary>
/// Gets and sets the property AutoAppliedAfterDate.
/// <para>
/// The date of the maintenance window when the action is applied. The maintenance action
/// is applied to the resource during its first maintenance window after this date. If
/// this date is specified, any <code>next-maintenance</code> opt-in requests are ignored.
/// </para>
/// </summary>
public DateTime AutoAppliedAfterDate
{
get { return this._autoAppliedAfterDate.GetValueOrDefault(); }
set { this._autoAppliedAfterDate = value; }
}
// Check to see if AutoAppliedAfterDate property is set
internal bool IsSetAutoAppliedAfterDate()
{
return this._autoAppliedAfterDate.HasValue;
}
/// <summary>
/// Gets and sets the property CurrentApplyDate.
/// <para>
/// The effective date when the pending maintenance action is applied to the resource.
/// This date takes into account opt-in requests received from the <a>ApplyPendingMaintenanceAction</a>
/// API, the <code>AutoAppliedAfterDate</code>, and the <code>ForcedApplyDate</code>.
/// This value is blank if an opt-in request has not been received and nothing has been
/// specified as <code>AutoAppliedAfterDate</code> or <code>ForcedApplyDate</code>.
/// </para>
/// </summary>
public DateTime CurrentApplyDate
{
get { return this._currentApplyDate.GetValueOrDefault(); }
set { this._currentApplyDate = value; }
}
// Check to see if CurrentApplyDate property is set
internal bool IsSetCurrentApplyDate()
{
return this._currentApplyDate.HasValue;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// A description providing more detail about the maintenance action.
/// </para>
/// </summary>
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 ForcedApplyDate.
/// <para>
/// The date when the maintenance action is automatically applied. The maintenance action
/// is applied to the resource on this date regardless of the maintenance window for the
/// resource. If this date is specified, any <code>immediate</code> opt-in requests are
/// ignored.
/// </para>
/// </summary>
public DateTime ForcedApplyDate
{
get { return this._forcedApplyDate.GetValueOrDefault(); }
set { this._forcedApplyDate = value; }
}
// Check to see if ForcedApplyDate property is set
internal bool IsSetForcedApplyDate()
{
return this._forcedApplyDate.HasValue;
}
/// <summary>
/// Gets and sets the property OptInStatus.
/// <para>
/// Indicates the type of opt-in request that has been received for the resource.
/// </para>
/// </summary>
public string OptInStatus
{
get { return this._optInStatus; }
set { this._optInStatus = value; }
}
// Check to see if OptInStatus property is set
internal bool IsSetOptInStatus()
{
return this._optInStatus != null;
}
}
} | 34.5625 | 111 | 0.610127 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/Neptune/Generated/Model/PendingMaintenanceAction.cs | 5,530 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
namespace FASTER.core
{
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct Record<Key, Value>
{
public RecordInfo info;
public Key key;
public Value value;
}
public unsafe sealed class GenericAllocator<Key, Value> : AllocatorBase<Key, Value>
where Key : new()
where Value : new()
{
// Circular buffer definition
private Record<Key, Value>[][] values;
// Object log related variables
private readonly IDevice objectLogDevice;
// Size of object chunks beign written to storage
private const int ObjectBlockSize = 100 * (1 << 20);
// Tail offsets per segment, in object log
public readonly long[] segmentOffsets;
// Buffer pool for object log related work
SectorAlignedBufferPool ioBufferPool;
// Record sizes
private static readonly int recordSize = Utility.GetSize(default(Record<Key, Value>));
private readonly SerializerSettings<Key, Value> SerializerSettings;
public GenericAllocator(LogSettings settings, SerializerSettings<Key, Value> serializerSettings, IFasterEqualityComparer<Key> comparer)
: base(settings, comparer)
{
SerializerSettings = serializerSettings;
if (default(Key) == null && ((SerializerSettings == null) || (SerializerSettings.keySerializer == null)))
{
throw new Exception("Key is a class, but no serializer specified via SerializerSettings");
}
if (default(Value) == null && ((SerializerSettings == null) || (SerializerSettings.valueSerializer == null)))
{
throw new Exception("Value is a class, but no serializer specified via SerializerSettings");
}
values = new Record<Key, Value>[BufferSize][];
segmentOffsets = new long[SegmentBufferSize];
objectLogDevice = settings.ObjectLogDevice;
if (KeyHasObjects() || ValueHasObjects())
{
if (objectLogDevice == null)
throw new Exception("Objects in key/value, but object log not provided during creation of FASTER instance");
}
epoch = LightEpoch.Instance;
ioBufferPool = SectorAlignedBufferPool.GetPool(1, sectorSize);
}
public override void Initialize()
{
Initialize(recordSize);
}
/// <summary>
/// Get start logical address
/// </summary>
/// <param name="page"></param>
/// <returns></returns>
public override long GetStartLogicalAddress(long page)
{
if (page == 0)
return (page << LogPageSizeBits) + recordSize;
return page << LogPageSizeBits;
}
public override ref RecordInfo GetInfo(long physicalAddress)
{
// Offset within page
int offset = (int)(physicalAddress & PageSizeMask);
// Index of page within the circular buffer
int pageIndex = (int)((physicalAddress >> LogPageSizeBits) & BufferSizeMask);
return ref values[pageIndex][offset/recordSize].info;
}
public override ref RecordInfo GetInfoFromBytePointer(byte* ptr)
{
return ref Unsafe.AsRef<Record<Key, Value>>(ptr).info;
}
public override ref Key GetKey(long physicalAddress)
{
// Offset within page
int offset = (int)(physicalAddress & PageSizeMask);
// Index of page within the circular buffer
int pageIndex = (int)((physicalAddress >> LogPageSizeBits) & BufferSizeMask);
return ref values[pageIndex][offset / recordSize].key;
}
public override ref Value GetValue(long physicalAddress)
{
// Offset within page
int offset = (int)(physicalAddress & PageSizeMask);
// Index of page within the circular buffer
int pageIndex = (int)((physicalAddress >> LogPageSizeBits) & BufferSizeMask);
return ref values[pageIndex][offset / recordSize].value;
}
public override int GetRecordSize(long physicalAddress)
{
return recordSize;
}
public override int GetAverageRecordSize()
{
return recordSize;
}
public override int GetInitialRecordSize<Input>(ref Key key, ref Input input)
{
return recordSize;
}
public override int GetRecordSize(ref Key key, ref Value value)
{
return recordSize;
}
/// <summary>
/// Dispose memory allocator
/// </summary>
public override void Dispose()
{
for (int i = 0; i < values.Length; i++)
{
values[i] = null;
}
values = null;
base.Dispose();
}
public override AddressInfo* GetKeyAddressInfo(long physicalAddress)
{
return (AddressInfo*)Unsafe.AsPointer(ref Unsafe.AsRef<Record<Key, Value>>((byte*)physicalAddress).key);
}
public override AddressInfo* GetValueAddressInfo(long physicalAddress)
{
return (AddressInfo*)Unsafe.AsPointer(ref Unsafe.AsRef<Record<Key, Value>>((byte*)physicalAddress).value);
}
/// <summary>
/// Allocate memory page, pinned in memory, and in sector aligned form, if possible
/// </summary>
/// <param name="index"></param>
protected override void AllocatePage(int index)
{
values[index] = AllocatePage();
PageStatusIndicator[index].PageFlushCloseStatus.PageFlushStatus = PMMFlushStatus.Flushed;
PageStatusIndicator[index].PageFlushCloseStatus.PageCloseStatus = PMMCloseStatus.Closed;
Interlocked.MemoryBarrier();
}
internal Record<Key, Value>[] AllocatePage()
{
Record<Key, Value>[] tmp;
if (PageSize % recordSize == 0)
tmp = new Record<Key, Value>[PageSize / recordSize];
else
tmp = new Record<Key, Value>[1 + (PageSize / recordSize)];
Array.Clear(tmp, 0, tmp.Length);
return tmp;
}
public override long GetPhysicalAddress(long logicalAddress)
{
return logicalAddress;
}
protected override bool IsAllocated(int pageIndex)
{
return values[pageIndex] != null;
}
protected override void DeleteAddressRange(long fromAddress, long toAddress)
{
base.DeleteAddressRange(fromAddress, toAddress);
objectLogDevice.DeleteSegmentRange((int)(fromAddress >> LogSegmentSizeBits), (int)(toAddress >> LogSegmentSizeBits));
}
protected override void WriteAsync<TContext>(long flushPage, IOCompletionCallback callback, PageAsyncFlushResult<TContext> asyncResult)
{
WriteAsync(flushPage,
(ulong)(AlignedPageSizeBytes * flushPage),
(uint)PageSize,
callback,
asyncResult, device, objectLogDevice);
}
protected override void WriteAsyncToDevice<TContext>
(long startPage, long flushPage, int pageSize, IOCompletionCallback callback,
PageAsyncFlushResult<TContext> asyncResult, IDevice device, IDevice objectLogDevice)
{
// We are writing to separate device, so use fresh segment offsets
WriteAsync(flushPage,
(ulong)(AlignedPageSizeBytes * (flushPage - startPage)),
(uint)pageSize, callback, asyncResult,
device, objectLogDevice, flushPage, new long[SegmentBufferSize]);
}
protected override void ClearPage(int page, bool pageZero)
{
Array.Clear(values[page], 0, values[page].Length);
// Close segments
var thisCloseSegment = page >> (LogSegmentSizeBits - LogPageSizeBits);
var nextClosePage = page + 1;
var nextCloseSegment = nextClosePage >> (LogSegmentSizeBits - LogPageSizeBits);
if (thisCloseSegment != nextCloseSegment)
{
// Last page in current segment
segmentOffsets[thisCloseSegment % SegmentBufferSize] = 0;
}
}
private void WriteAsync<TContext>(long flushPage, ulong alignedDestinationAddress, uint numBytesToWrite,
IOCompletionCallback callback, PageAsyncFlushResult<TContext> asyncResult,
IDevice device, IDevice objlogDevice, long intendedDestinationPage = -1, long[] localSegmentOffsets = null)
{
/*
if (!(KeyHasObjects() || ValueHasObjects()))
{
device.WriteAsync((IntPtr)pointers[flushPage % BufferSize], alignedDestinationAddress,
numBytesToWrite, callback, asyncResult);
return;
}
*/
int start = 0, aligned_start = 0, end = (int)numBytesToWrite;
if (asyncResult.partial)
{
start = (int)((asyncResult.fromAddress - (asyncResult.page << LogPageSizeBits)));
aligned_start = (start / sectorSize) * sectorSize;
end = (int)((asyncResult.untilAddress - (asyncResult.page << LogPageSizeBits)));
}
// Check if user did not override with special segment offsets
if (localSegmentOffsets == null) localSegmentOffsets = segmentOffsets;
var src = values[flushPage % BufferSize];
var buffer = ioBufferPool.Get((int)numBytesToWrite);
if (aligned_start < start && (KeyHasObjects() || ValueHasObjects()))
{
// Get the overlapping HLOG from disk as we wrote it with
// object pointers previously. This avoids object reserialization
PageAsyncReadResult<Empty> result =
new PageAsyncReadResult<Empty>
{
handle = new CountdownEvent(1)
};
device.ReadAsync(alignedDestinationAddress + (ulong)aligned_start, (IntPtr)buffer.aligned_pointer + aligned_start,
(uint)sectorSize, AsyncReadPageCallback, result);
result.handle.Wait();
fixed (RecordInfo* pin = &src[0].info)
{
Buffer.MemoryCopy((void*)((long)Unsafe.AsPointer(ref src[0]) + start), buffer.aligned_pointer + start,
numBytesToWrite - start, numBytesToWrite - start);
}
}
else
{
fixed (RecordInfo* pin = &src[0].info)
{
Buffer.MemoryCopy((void*)((long)Unsafe.AsPointer(ref src[0]) + aligned_start), buffer.aligned_pointer + aligned_start,
numBytesToWrite - aligned_start, numBytesToWrite - aligned_start);
}
}
long ptr = (long)buffer.aligned_pointer;
List<long> addr = new List<long>();
asyncResult.freeBuffer1 = buffer;
addr = new List<long>();
MemoryStream ms = new MemoryStream();
IObjectSerializer<Key> keySerializer = null;
IObjectSerializer<Value> valueSerializer = null;
if (KeyHasObjects())
{
keySerializer = SerializerSettings.keySerializer();
keySerializer.BeginSerialize(ms);
}
if (ValueHasObjects())
{
valueSerializer = SerializerSettings.valueSerializer();
valueSerializer.BeginSerialize(ms);
}
for (int i=start/recordSize; i<end/recordSize; i++)
{
if (!src[i].info.Invalid)
{
if (KeyHasObjects())
{
long pos = ms.Position;
keySerializer.Serialize(ref src[i].key);
var key_address = GetKeyAddressInfo((long)(buffer.aligned_pointer + i * recordSize));
key_address->Address = pos;
key_address->Size = (int)(ms.Position - pos);
addr.Add((long)key_address);
}
if (ValueHasObjects())
{
long pos = ms.Position;
valueSerializer.Serialize(ref src[i].value);
var value_address = GetValueAddressInfo((long)(buffer.aligned_pointer + i * recordSize));
value_address->Address = pos;
value_address->Size = (int)(ms.Position - pos);
addr.Add((long)value_address);
}
}
if (ms.Position > ObjectBlockSize || i == (end / recordSize) - 1)
{
var _s = ms.ToArray();
ms.Close();
ms = new MemoryStream();
var _objBuffer = ioBufferPool.Get(_s.Length);
asyncResult.done = new AutoResetEvent(false);
var _alignedLength = (_s.Length + (sectorSize - 1)) & ~(sectorSize - 1);
var _objAddr = Interlocked.Add(ref localSegmentOffsets[(long)(alignedDestinationAddress >> LogSegmentSizeBits) % SegmentBufferSize], _alignedLength) - _alignedLength;
fixed (void* src_ = _s)
Buffer.MemoryCopy(src_, _objBuffer.aligned_pointer, _s.Length, _s.Length);
foreach (var address in addr)
*((long*)address) += _objAddr;
if (i < (end / recordSize) - 1)
{
objlogDevice.WriteAsync(
(IntPtr)_objBuffer.aligned_pointer,
(int)(alignedDestinationAddress >> LogSegmentSizeBits),
(ulong)_objAddr, (uint)_alignedLength, AsyncFlushPartialObjectLogCallback<TContext>, asyncResult);
// Wait for write to complete before resuming next write
asyncResult.done.WaitOne();
_objBuffer.Return();
}
else
{
// need to write both page and object cache
asyncResult.count++;
asyncResult.freeBuffer2 = _objBuffer;
objlogDevice.WriteAsync(
(IntPtr)_objBuffer.aligned_pointer,
(int)(alignedDestinationAddress >> LogSegmentSizeBits),
(ulong)_objAddr, (uint)_alignedLength, callback, asyncResult);
}
}
}
if (KeyHasObjects())
{
keySerializer.EndSerialize();
}
if (ValueHasObjects())
{
valueSerializer.EndSerialize();
}
if (asyncResult.partial)
{
var aligned_end = (int)((asyncResult.untilAddress - (asyncResult.page << LogPageSizeBits)));
aligned_end = ((aligned_end + (sectorSize - 1)) & ~(sectorSize - 1));
numBytesToWrite = (uint)(aligned_end - aligned_start);
}
var alignedNumBytesToWrite = (uint)((numBytesToWrite + (sectorSize - 1)) & ~(sectorSize - 1));
// Finally write the hlog page
device.WriteAsync((IntPtr)buffer.aligned_pointer + aligned_start, alignedDestinationAddress + (ulong)aligned_start,
alignedNumBytesToWrite, callback, asyncResult);
}
private void AsyncReadPageCallback(uint errorCode, uint numBytes, NativeOverlapped* overlap)
{
if (errorCode != 0)
{
Trace.TraceError("OverlappedStream GetQueuedCompletionStatus error: {0}", errorCode);
}
// Set the page status to flushed
var result = (PageAsyncReadResult<Empty>)Overlapped.Unpack(overlap).AsyncResult;
result.handle.Signal();
Overlapped.Free(overlap);
}
protected override void ReadAsync<TContext>(
ulong alignedSourceAddress, int destinationPageIndex, uint aligned_read_length,
IOCompletionCallback callback, PageAsyncReadResult<TContext> asyncResult, IDevice device, IDevice objlogDevice)
{
asyncResult.freeBuffer1 = readBufferPool.Get((int)aligned_read_length);
asyncResult.freeBuffer1.required_bytes = (int)aligned_read_length;
if (!(KeyHasObjects() || ValueHasObjects()))
{
device.ReadAsync(alignedSourceAddress, (IntPtr)asyncResult.freeBuffer1.aligned_pointer,
aligned_read_length, callback, asyncResult);
return;
}
asyncResult.callback = callback;
asyncResult.count++;
if (objlogDevice == null)
{
Debug.Assert(objectLogDevice != null);
objlogDevice = objectLogDevice;
}
asyncResult.objlogDevice = objlogDevice;
device.ReadAsync(alignedSourceAddress, (IntPtr)asyncResult.freeBuffer1.aligned_pointer,
aligned_read_length, AsyncReadPageWithObjectsCallback<TContext>, asyncResult);
}
/// <summary>
/// IOCompletion callback for page flush
/// </summary>
/// <param name="errorCode"></param>
/// <param name="numBytes"></param>
/// <param name="overlap"></param>
private void AsyncFlushPartialObjectLogCallback<TContext>(uint errorCode, uint numBytes, NativeOverlapped* overlap)
{
if (errorCode != 0)
{
Trace.TraceError("OverlappedStream GetQueuedCompletionStatus error: {0}", errorCode);
}
// Set the page status to flushed
PageAsyncFlushResult<TContext> result = (PageAsyncFlushResult<TContext>)Overlapped.Unpack(overlap).AsyncResult;
result.done.Set();
Overlapped.Free(overlap);
}
private void AsyncReadPageWithObjectsCallback<TContext>(uint errorCode, uint numBytes, NativeOverlapped* overlap)
{
if (errorCode != 0)
{
Trace.TraceError("OverlappedStream GetQueuedCompletionStatus error: {0}", errorCode);
}
PageAsyncReadResult<TContext> result = (PageAsyncReadResult<TContext>)Overlapped.Unpack(overlap).AsyncResult;
var src = values[result.page % BufferSize];
// We are reading into a frame
if (result.frame != null)
{
src = ((Record<Key, Value>[][])result.frame)[result.page % result.frameSize];
if (result.freeBuffer1.buffer != null && result.freeBuffer1.required_bytes > 0)
{
PopulatePageFrame(result.freeBuffer1.GetValidPointer(), PageSize, src);
result.freeBuffer1.required_bytes = 0;
}
}
else
{
if (result.freeBuffer1.buffer != null && result.freeBuffer1.required_bytes > 0)
{
PopulatePage(result.freeBuffer1.GetValidPointer(), PageSize, result.page);
result.freeBuffer1.required_bytes = 0;
}
}
long ptr = 0;
// Correct for page 0 of HLOG
//if (result.page == 0)
// ptr += Constants.kFirstValidAddress;
// Check if we are resuming
if (result.resumeptr > ptr)
ptr = result.resumeptr;
// Deserialize all objects until untilptr
if (ptr < result.untilptr)
{
MemoryStream ms = new MemoryStream(result.freeBuffer2.buffer);
ms.Seek(result.freeBuffer2.offset, SeekOrigin.Begin);
Deserialize(ptr, result.untilptr, src, ms);
ms.Dispose();
ptr = result.untilptr;
result.freeBuffer2.Return();
result.freeBuffer2.buffer = null;
result.resumeptr = ptr;
}
// If we have processed entire page, return
if (ptr >= PageSize)
{
result.Free();
// Call the "real" page read callback
result.callback(errorCode, numBytes, overlap);
return;
}
// We will be re-issuing I/O, so free current overlap
Overlapped.Free(overlap);
GetObjectInfo(result.freeBuffer1.GetValidPointer(), ref ptr, PageSize, ObjectBlockSize, src, out long startptr, out long size);
// Object log fragment should be aligned by construction
Debug.Assert(startptr % sectorSize == 0);
// We will be able to process all records until (but not including) ptr
result.untilptr = ptr;
if (size > int.MaxValue)
throw new Exception("Unable to read object page, total size greater than 2GB: " + size);
var objBuffer = ioBufferPool.Get((int)size);
result.freeBuffer2 = objBuffer;
var alignedLength = (size + (sectorSize - 1)) & ~(sectorSize - 1);
// Request objects from objlog
result.objlogDevice.ReadAsync(
(int)(result.page >> (LogSegmentSizeBits - LogPageSizeBits)),
(ulong)startptr,
(IntPtr)objBuffer.aligned_pointer, (uint)alignedLength, AsyncReadPageWithObjectsCallback<TContext>, result);
}
/// <summary>
/// Invoked by users to obtain a record from disk. It uses sector aligned memory to read
/// the record efficiently into memory.
/// </summary>
/// <param name="fromLogical"></param>
/// <param name="numBytes"></param>
/// <param name="callback"></param>
/// <param name="context"></param>
/// <param name="result"></param>
protected override void AsyncReadRecordObjectsToMemory(long fromLogical, int numBytes, IOCompletionCallback callback, AsyncIOContext<Key, Value> context, SectorAlignedMemory result = default(SectorAlignedMemory))
{
ulong fileOffset = (ulong)(AlignedPageSizeBytes * (fromLogical >> LogPageSizeBits) + (fromLogical & PageSizeMask));
ulong alignedFileOffset = (ulong)(((long)fileOffset / sectorSize) * sectorSize);
uint alignedReadLength = (uint)((long)fileOffset + numBytes - (long)alignedFileOffset);
alignedReadLength = (uint)((alignedReadLength + (sectorSize - 1)) & ~(sectorSize - 1));
var record = readBufferPool.Get((int)alignedReadLength);
record.valid_offset = (int)(fileOffset - alignedFileOffset);
record.available_bytes = (int)(alignedReadLength - (fileOffset - alignedFileOffset));
record.required_bytes = numBytes;
var asyncResult = default(AsyncGetFromDiskResult<AsyncIOContext<Key, Value>>);
asyncResult.context = context;
asyncResult.context.record = result;
asyncResult.context.objBuffer = record;
objectLogDevice.ReadAsync(
(int)(context.logicalAddress >> LogSegmentSizeBits),
alignedFileOffset,
(IntPtr)asyncResult.context.objBuffer.aligned_pointer,
alignedReadLength,
callback,
asyncResult);
}
/// <summary>
/// Read pages from specified device
/// </summary>
/// <typeparam name="TContext"></typeparam>
/// <param name="readPageStart"></param>
/// <param name="numPages"></param>
/// <param name="callback"></param>
/// <param name="context"></param>
/// <param name="frame"></param>
/// <param name="frameSize"></param>
/// <param name="completed"></param>
/// <param name="devicePageOffset"></param>
/// <param name="device"></param>
/// <param name="objectLogDevice"></param>
private void AsyncReadPagesFromDeviceToFrame<TContext>(
long readPageStart,
int numPages,
IOCompletionCallback callback,
TContext context,
Record<Key, Value>[][] frame,
int frameSize,
out CountdownEvent completed,
long devicePageOffset = 0,
IDevice device = null, IDevice objectLogDevice = null)
{
var usedDevice = device;
IDevice usedObjlogDevice = objectLogDevice;
if (device == null)
{
usedDevice = this.device;
}
completed = new CountdownEvent(numPages);
for (long readPage = readPageStart; readPage < (readPageStart + numPages); readPage++)
{
int pageIndex = (int)(readPage % frameSize);
if (frame[pageIndex] == null)
{
frame[pageIndex] = AllocatePage();
}
else
{
Array.Clear(frame[pageIndex], 0, frame[pageIndex].Length);
}
var asyncResult = new PageAsyncReadResult<TContext>()
{
page = readPage,
context = context,
handle = completed,
count = 1,
frame = frame,
frameSize = frameSize
};
ulong offsetInFile = (ulong)(AlignedPageSizeBytes * readPage);
if (device != null)
offsetInFile = (ulong)(AlignedPageSizeBytes * (readPage - devicePageOffset));
ReadAsync(offsetInFile, pageIndex, (uint)AlignedPageSizeBytes, callback, asyncResult, usedDevice, usedObjlogDevice);
}
}
#region Page handlers for objects
/// <summary>
/// Deseialize part of page from stream
/// </summary>
/// <param name="ptr">From pointer</param>
/// <param name="untilptr">Until pointer</param>
/// <param name="src"></param>
/// <param name="stream">Stream</param>
public void Deserialize(long ptr, long untilptr, Record<Key, Value>[] src, Stream stream)
{
IObjectSerializer<Key> keySerializer = null;
IObjectSerializer<Value> valueSerializer = null;
if (KeyHasObjects())
{
keySerializer = SerializerSettings.keySerializer();
keySerializer.BeginDeserialize(stream);
}
if (ValueHasObjects())
{
valueSerializer = SerializerSettings.valueSerializer();
valueSerializer.BeginDeserialize(stream);
}
while (ptr < untilptr)
{
if (!src[ptr/recordSize].info.Invalid)
{
if (KeyHasObjects())
{
src[ptr/recordSize].key = new Key();
keySerializer.Deserialize(ref src[ptr/recordSize].key);
}
if (ValueHasObjects())
{
src[ptr / recordSize].value = new Value();
valueSerializer.Deserialize(ref src[ptr/recordSize].value);
}
}
ptr += GetRecordSize(ptr);
}
if (KeyHasObjects())
{
keySerializer.EndDeserialize();
}
if (ValueHasObjects())
{
valueSerializer.EndDeserialize();
}
}
/// <summary>
/// Serialize part of page to stream
/// </summary>
/// <param name="ptr">From pointer</param>
/// <param name="untilptr">Until pointer</param>
/// <param name="stream">Stream</param>
/// <param name="objectBlockSize">Size of blocks to serialize in chunks of</param>
/// <param name="addr">List of addresses that need to be updated with offsets</param>
public void Serialize(ref long ptr, long untilptr, Stream stream, int objectBlockSize, out List<long> addr)
{
IObjectSerializer<Key> keySerializer = null;
IObjectSerializer<Value> valueSerializer = null;
if (KeyHasObjects())
{
keySerializer = SerializerSettings.keySerializer();
keySerializer.BeginSerialize(stream);
}
if (ValueHasObjects())
{
valueSerializer = SerializerSettings.valueSerializer();
valueSerializer.BeginSerialize(stream);
}
addr = new List<long>();
while (ptr < untilptr)
{
if (!GetInfo(ptr).Invalid)
{
long pos = stream.Position;
if (KeyHasObjects())
{
keySerializer.Serialize(ref GetKey(ptr));
var key_address = GetKeyAddressInfo(ptr);
key_address->Address = pos;
key_address->Size = (int)(stream.Position - pos);
addr.Add((long)key_address);
}
if (ValueHasObjects())
{
pos = stream.Position;
var value_address = GetValueAddressInfo(ptr);
valueSerializer.Serialize(ref GetValue(ptr));
value_address->Address = pos;
value_address->Size = (int)(stream.Position - pos);
addr.Add((long)value_address);
}
}
ptr += GetRecordSize(ptr);
if (stream.Position > objectBlockSize)
break;
}
if (KeyHasObjects())
{
keySerializer.EndSerialize();
}
if (ValueHasObjects())
{
valueSerializer.EndSerialize();
}
}
/// <summary>
/// Get location and range of object log addresses for specified log page
/// </summary>
/// <param name="raw"></param>
/// <param name="ptr"></param>
/// <param name="untilptr"></param>
/// <param name="objectBlockSize"></param>
/// <param name="src"></param>
/// <param name="startptr"></param>
/// <param name="size"></param>
public void GetObjectInfo(byte* raw, ref long ptr, long untilptr, int objectBlockSize, Record<Key, Value>[] src, out long startptr, out long size)
{
long minObjAddress = long.MaxValue;
long maxObjAddress = long.MinValue;
while (ptr < untilptr)
{
if (!src[ptr/recordSize].info.Invalid)
{
if (KeyHasObjects())
{
var key_addr = GetKeyAddressInfo((long)raw + ptr);
var addr = key_addr->Address;
// If object pointer is greater than kObjectSize from starting object pointer
if (minObjAddress != long.MaxValue && (addr - minObjAddress > objectBlockSize))
{
break;
}
if (addr < minObjAddress) minObjAddress = addr;
addr += key_addr->Size;
if (addr > maxObjAddress) maxObjAddress = addr;
}
if (ValueHasObjects())
{
var value_addr = GetValueAddressInfo((long)raw + ptr);
var addr = value_addr->Address;
// If object pointer is greater than kObjectSize from starting object pointer
if (minObjAddress != long.MaxValue && (addr - minObjAddress > objectBlockSize))
{
break;
}
if (addr < minObjAddress) minObjAddress = addr;
addr += value_addr->Size;
if (addr > maxObjAddress) maxObjAddress = addr;
}
}
ptr += GetRecordSize(ptr);
}
// Handle the case where no objects are to be written
if (minObjAddress == long.MaxValue && maxObjAddress == long.MinValue)
{
minObjAddress = 0;
maxObjAddress = 0;
}
startptr = minObjAddress;
size = maxObjAddress - minObjAddress;
}
/// <summary>
/// Retrieve objects from object log
/// </summary>
/// <param name="record"></param>
/// <param name="ctx"></param>
/// <returns></returns>
protected override bool RetrievedFullRecord(byte* record, ref AsyncIOContext<Key, Value> ctx)
{
if (!KeyHasObjects())
{
ShallowCopy(ref Unsafe.AsRef<Record<Key, Value>>(record).key, ref ctx.key);
}
if (!ValueHasObjects())
{
ShallowCopy(ref Unsafe.AsRef<Record<Key, Value>>(record).value, ref ctx.value);
}
if (!(KeyHasObjects() || ValueHasObjects()))
return true;
if (ctx.objBuffer.buffer == null)
{
// Issue IO for objects
long startAddress = -1;
long endAddress = -1;
if (KeyHasObjects())
{
var x = GetKeyAddressInfo((long)record);
startAddress = x->Address;
endAddress = x->Address + x->Size;
}
if (ValueHasObjects())
{
var x = GetValueAddressInfo((long)record);
if (startAddress == -1)
startAddress = x->Address;
endAddress = x->Address + x->Size;
}
// We are limited to a 2GB size per key-value
if (endAddress-startAddress > int.MaxValue)
throw new Exception("Size of key-value exceeds max of 2GB: " + (endAddress - startAddress));
AsyncGetFromDisk(startAddress, (int)(endAddress - startAddress), ctx, ctx.record);
return false;
}
// Parse the key and value objects
MemoryStream ms = new MemoryStream(ctx.objBuffer.buffer);
ms.Seek(ctx.objBuffer.offset + ctx.objBuffer.valid_offset, SeekOrigin.Begin);
if (KeyHasObjects())
{
ctx.key = new Key();
var keySerializer = SerializerSettings.keySerializer();
keySerializer.BeginDeserialize(ms);
keySerializer.Deserialize(ref ctx.key);
keySerializer.EndDeserialize();
}
if (ValueHasObjects())
{
ctx.value = new Value();
var valueSerializer = SerializerSettings.valueSerializer();
valueSerializer.BeginDeserialize(ms);
valueSerializer.Deserialize(ref ctx.value);
valueSerializer.EndDeserialize();
}
ctx.objBuffer.Return();
return true;
}
/// <summary>
/// Whether KVS has keys to serialize/deserialize
/// </summary>
/// <returns></returns>
public override bool KeyHasObjects()
{
return SerializerSettings.keySerializer != null;
}
/// <summary>
/// Whether KVS has values to serialize/deserialize
/// </summary>
/// <returns></returns>
public override bool ValueHasObjects()
{
return SerializerSettings.valueSerializer != null;
}
#endregion
public override long[] GetSegmentOffsets()
{
return segmentOffsets;
}
internal override void PopulatePage(byte* src, int required_bytes, long destinationPage)
{
PopulatePage(src, required_bytes, ref values[destinationPage % BufferSize]);
}
internal void PopulatePageFrame(byte* src, int required_bytes, Record<Key, Value>[] frame)
{
PopulatePage(src, required_bytes, ref frame);
}
internal void PopulatePage(byte* src, int required_bytes, ref Record<Key, Value>[] destinationPage)
{
fixed (RecordInfo* pin = &destinationPage[0].info)
{
Buffer.MemoryCopy(src, Unsafe.AsPointer(ref destinationPage[0]), required_bytes, required_bytes);
}
}
/// <summary>
/// Iterator interface for scanning FASTER log
/// </summary>
/// <param name="beginAddress"></param>
/// <param name="endAddress"></param>
/// <param name="scanBufferingMode"></param>
/// <returns></returns>
public override IFasterScanIterator<Key, Value> Scan(long beginAddress, long endAddress, ScanBufferingMode scanBufferingMode)
{
return new GenericScanIterator(this, beginAddress, endAddress, scanBufferingMode);
}
/// <summary>
/// Scan iterator for hybrid log
/// </summary>
public class GenericScanIterator : IFasterScanIterator<Key, Value>
{
private readonly int frameSize;
private readonly GenericAllocator<Key, Value> hlog;
private readonly long beginAddress, endAddress;
private readonly Record<Key, Value>[][] frame;
private readonly CountdownEvent[] loaded;
private bool first = true;
private long currentAddress;
/// <summary>
/// Constructor
/// </summary>
/// <param name="hlog"></param>
/// <param name="beginAddress"></param>
/// <param name="endAddress"></param>
/// <param name="scanBufferingMode"></param>
public GenericScanIterator(GenericAllocator<Key, Value> hlog, long beginAddress, long endAddress, ScanBufferingMode scanBufferingMode)
{
this.hlog = hlog;
this.beginAddress = beginAddress;
this.endAddress = endAddress;
currentAddress = beginAddress;
if (scanBufferingMode == ScanBufferingMode.SinglePageBuffering)
frameSize = 1;
else
frameSize = 2;
frame = new Record<Key, Value>[frameSize][];
loaded = new CountdownEvent[frameSize];
var frameNumber = (currentAddress >> hlog.LogPageSizeBits) % frameSize;
hlog.AsyncReadPagesFromDeviceToFrame
(currentAddress >> hlog.LogPageSizeBits,
1, AsyncReadPagesCallback, Empty.Default,
frame, frameSize, out loaded[frameNumber]);
}
public bool GetNext(out Key key, out Value value)
{
key = default(Key);
value = default(Value);
while (true)
{
// Check for boundary conditions
if (currentAddress >= endAddress)
{
return false;
}
if (currentAddress < hlog.BeginAddress)
{
throw new Exception("Iterator address is less than log BeginAddress " + hlog.BeginAddress);
}
var currentPage = currentAddress >> hlog.LogPageSizeBits;
var currentFrame = currentPage % frameSize;
var offset = (currentAddress & hlog.PageSizeMask) / recordSize;
if (currentAddress < hlog.HeadAddress)
BufferAndLoad(currentAddress, currentPage, currentFrame);
// Check if record fits on page, if not skip to next page
if ((currentAddress & hlog.PageSizeMask) + recordSize > hlog.PageSize)
{
currentAddress = (1 + (currentAddress >> hlog.LogPageSizeBits)) << hlog.LogPageSizeBits;
continue;
}
if (currentAddress >= hlog.HeadAddress)
{
// Read record from cached page memory
currentAddress += recordSize;
var page = currentPage % hlog.BufferSize;
key = hlog.values[page][offset].key;
value = hlog.values[page][offset].value;
return true;
}
currentAddress += recordSize;
key = frame[currentFrame][offset].key;
value = frame[currentFrame][offset].value;
return true;
}
}
private void BufferAndLoad(long currentAddress, long currentPage, long currentFrame)
{
if (first || (currentAddress & hlog.PageSizeMask) == 0)
{
// Prefetch pages based on buffering mode
if (frameSize == 1)
{
if (!first)
{
hlog.AsyncReadPagesFromDeviceToFrame(currentAddress >> hlog.LogPageSizeBits, 1, AsyncReadPagesCallback, Empty.Default, frame, frameSize, out loaded[currentFrame]);
}
}
else
{
var endPage = endAddress >> hlog.LogPageSizeBits;
if ((endPage > currentPage) &&
((endPage > currentPage + 1) || ((endAddress & hlog.PageSizeMask) != 0)))
{
hlog.AsyncReadPagesFromDeviceToFrame(1 + (currentAddress >> hlog.LogPageSizeBits), 1, AsyncReadPagesCallback, Empty.Default, frame, frameSize, out loaded[(currentPage + 1) % frameSize]);
}
}
first = false;
}
loaded[currentFrame].Wait();
}
public void Dispose()
{
throw new NotImplementedException();
}
private void AsyncReadPagesCallback(uint errorCode, uint numBytes, NativeOverlapped* overlap)
{
if (errorCode != 0)
{
Trace.TraceError("OverlappedStream GetQueuedCompletionStatus error: {0}", errorCode);
}
var result = (PageAsyncReadResult<Empty>)Overlapped.Unpack(overlap).AsyncResult;
if (result.freeBuffer1.buffer != null)
{
hlog.PopulatePage(result.freeBuffer1.GetValidPointer(), result.freeBuffer1.required_bytes, ref frame[result.page % result.frameSize]);
result.freeBuffer1.Return();
}
if (result.handle != null)
{
result.handle.Signal();
}
Interlocked.MemoryBarrier();
Overlapped.Free(overlap);
}
}
}
}
| 39.331288 | 220 | 0.529469 | [
"MIT"
] | sahwar/FASTER | cs/src/core/Allocator/GenericAllocator.cs | 44,879 | C# |
using System;
using System.Reflection;
namespace OneTwoOne.Infrastructure.Helpers
{
/// <summary>
/// Some simple type-checking methods used internally.
/// </summary>
internal static class TypeHelper
{
public static bool IsFunc(object obj)
{
if (obj == null)
{
return false;
}
var type = obj.GetType();
if (!type.GetTypeInfo().IsGenericType)
{
return false;
}
return type.GetGenericTypeDefinition() == typeof(Func<>);
}
public static bool IsFunc<TReturn>(object obj)
{
return obj != null && obj.GetType() == typeof(Func<TReturn>);
}
public static bool IsPrimitiveExtendedIncludingNullable(Type type, bool includeEnums = false)
{
if (IsPrimitiveExtended(type, includeEnums))
{
return true;
}
if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return IsPrimitiveExtended(type.GenericTypeArguments[0], includeEnums);
}
return false;
}
private static bool IsPrimitiveExtended(Type type, bool includeEnums)
{
if (type.GetTypeInfo().IsPrimitive)
{
return true;
}
if (includeEnums && type.GetTypeInfo().IsEnum)
{
return true;
}
return type == typeof(string) ||
type == typeof(decimal) ||
type == typeof(DateTime) ||
type == typeof(DateTimeOffset) ||
type == typeof(TimeSpan) ||
type == typeof(Guid);
}
}
}
| 27.117647 | 106 | 0.497289 | [
"Apache-2.0"
] | microcapital/one2one | src/OneTwoOne.Infrastructure/Helpers/TypeHelper.cs | 1,846 | C# |
using System.Windows;
using System.Windows.Controls;
using HalationGhost.WinApps;
using Reactive.Bindings;
using Reactive.Bindings.Extensions;
namespace MaterialDesignControls.MetroWindows
{
public class MetroWindowPanelViewModel : HalationGhostViewModelBase
{
public ReadOnlyReactivePropertySlim<bool> IsEnableMinEnable { get; }
public ReadOnlyReactivePropertySlim<bool> IsEnabledCloseEnable { get; }
public ReadOnlyReactivePropertySlim<bool> IsEnabledMaxEnable { get; }
public ReactivePropertySlim<bool> IgnoreTaskbarOnMaximize { get; set; }
public ReactivePropertySlim<bool> IsCloseButtonEnabled { get; set; }
public ReactivePropertySlim<bool> IsMaxRestoreButtonEnabled { get; set; }
public ReactivePropertySlim<bool> IsMinButtonEnabled { get; set; }
public ReactivePropertySlim<bool> IsWindowDraggable { get; set; }
public ReactivePropertySlim<bool> ShowCloseButton { get; set; }
public ReactivePropertySlim<bool> ShowMaxRestoreButton { get; set; }
public ReactivePropertySlim<bool> ShowMinButton { get; set; }
public ReactivePropertySlim<bool> ShowSystemMenuOnRightClick { get; set; }
public ReactivePropertySlim<bool> ShowTitleBar { get; set; }
public ReactivePropertySlim<HorizontalAlignment> TitleAlignment { get; set; }
public ReactivePropertySlim<CharacterCasing> TitleCharacterCasing { get; set; }
public ReactivePropertySlim<bool> WindowTransitionsEnabled { get; set; }
public ReactivePropertySlim<bool> ShowIconOnTitleBar { get; set; }
public ReactiveCommand WindowClose { get; }
private IMainWindowService mainWindowService = null;
public MetroWindowPanelViewModel(IMainWindowService mainWindow)
{
this.mainWindowService = mainWindow;
this.IgnoreTaskbarOnMaximize = this.mainWindowService.IgnoreTaskbarOnMaximize
.AddTo(this.disposable);
this.IsCloseButtonEnabled = this.mainWindowService.IsCloseButtonEnabled
.AddTo(this.disposable);
this.IsMaxRestoreButtonEnabled = this.mainWindowService.IsMaxRestoreButtonEnabled
.AddTo(this.disposable);
this.IsMinButtonEnabled = this.mainWindowService.IsMinButtonEnabled
.AddTo(this.disposable);
this.IsWindowDraggable = this.mainWindowService.IsWindowDraggable
.AddTo(this.disposable);
this.ShowCloseButton = this.mainWindowService.ShowCloseButton
.AddTo(this.disposable);
this.ShowMaxRestoreButton = this.mainWindowService.ShowMaxRestoreButton
.AddTo(this.disposable);
this.ShowMinButton = this.mainWindowService.ShowMinButton
.AddTo(this.disposable);
this.ShowSystemMenuOnRightClick = this.mainWindowService.ShowSystemMenuOnRightClick
.AddTo(this.disposable);
this.ShowTitleBar = this.mainWindowService.ShowTitleBar
.AddTo(this.disposable);
this.TitleAlignment = this.mainWindowService.TitleAlignment
.AddTo(this.disposable);
this.TitleCharacterCasing = this.mainWindowService.TitleCharacterCasing
.AddTo(this.disposable);
this.WindowTransitionsEnabled = this.mainWindowService.WindowTransitionsEnabled
.AddTo(this.disposable);
this.ShowIconOnTitleBar = this.mainWindowService.ShowIconOnTitleBar
.AddTo(this.disposable);
this.IsEnabledCloseEnable = new[] { this.mainWindowService.ShowTitleBar, this.mainWindowService.ShowCloseButton }
.CombineLatestValuesAreAllTrue()
.ToReadOnlyReactivePropertySlim()
.AddTo(this.disposable);
this.IsEnabledMaxEnable = new[] { this.mainWindowService.ShowTitleBar, this.mainWindowService.ShowMaxRestoreButton }
.CombineLatestValuesAreAllTrue()
.ToReadOnlyReactivePropertySlim()
.AddTo(this.disposable);
this.IsEnableMinEnable = new[] { this.mainWindowService.ShowTitleBar, this.mainWindowService.ShowMinButton }
.CombineLatestValuesAreAllTrue()
.ToReadOnlyReactivePropertySlim()
.AddTo(this.disposable);
this.WindowClose = new ReactiveCommand()
.WithSubscribe(() => this.mainWindowService.WindowCloseRequest.Value = true)
.AddTo(this.disposable);
}
}
}
| 40.29703 | 120 | 0.77371 | [
"Apache-2.0"
] | YouseiSakusen/WpfUiGallery | 03_MaterialDesignControls01/ChildViews/MetroWindows/MetroWindowPanelViewModel.cs | 4,072 | C# |
using HRM.CrossCutting.Command;
using Library.Library.Category.ViewModels;
using System.Threading.Tasks;
namespace Library.Library.Category.Commands.SaveCategory
{
public interface ISaveCategoryCommand
{
Task<CommandResult> ExecuteAsync(CategoryViewModel model);
}
}
| 24.083333 | 66 | 0.782007 | [
"MIT"
] | hoangphuong020193/library | back-end/Library/Library.Library/Category/Commands/SaveCategory/ISaveCategoryCommand.cs | 291 | C# |
using System;
namespace CoreValidation.Translations
{
public sealed class TranslationNotFoundException : ArgumentException
{
public TranslationNotFoundException(string name)
: base($"Translation '{name}' not found.")
{
Name = name;
}
public string Name { get; }
}
} | 22.4 | 72 | 0.613095 | [
"MIT"
] | Grosbo/CoreValidation | src/CoreValidation/Translations/TranslationNotFoundException.cs | 338 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/sapi.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.Windows;
/// <include file='SPSEMANTICFORMAT.xml' path='doc/member[@name="SPSEMANTICFORMAT"]/*' />
public enum SPSEMANTICFORMAT
{
/// <include file='SPSEMANTICFORMAT.xml' path='doc/member[@name="SPSEMANTICFORMAT.SPSMF_SAPI_PROPERTIES"]/*' />
SPSMF_SAPI_PROPERTIES = 0,
/// <include file='SPSEMANTICFORMAT.xml' path='doc/member[@name="SPSEMANTICFORMAT.SPSMF_SRGS_SEMANTICINTERPRETATION_MS"]/*' />
SPSMF_SRGS_SEMANTICINTERPRETATION_MS = 1,
/// <include file='SPSEMANTICFORMAT.xml' path='doc/member[@name="SPSEMANTICFORMAT.SPSMF_SRGS_SAPIPROPERTIES"]/*' />
SPSMF_SRGS_SAPIPROPERTIES = 2,
/// <include file='SPSEMANTICFORMAT.xml' path='doc/member[@name="SPSEMANTICFORMAT.SPSMF_UPS"]/*' />
SPSMF_UPS = 4,
/// <include file='SPSEMANTICFORMAT.xml' path='doc/member[@name="SPSEMANTICFORMAT.SPSMF_SRGS_SEMANTICINTERPRETATION_W3C"]/*' />
SPSMF_SRGS_SEMANTICINTERPRETATION_W3C = 8,
}
| 47.192308 | 145 | 0.743276 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/Windows/um/sapi/SPSEMANTICFORMAT.cs | 1,229 | C# |
using System;
using System.Linq;
using System.Windows;
namespace ConstructServer.Runtime.Windows
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
} | 17.923077 | 42 | 0.660944 | [
"MIT"
] | dgerding/Construct | Construct3/Construct3/Construct.Server.Runtime.WindowsUX/App.xaml.cs | 235 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WhereToFly.App.Core.Views;
using WhereToFly.Geo.Model;
namespace WhereToFly.App.UnitTest.Views
{
/// <summary>
/// Tests for AddLiveWaypointPopupPage class
/// </summary>
[TestClass]
public class AddLiveWaypointPopupPageTest
{
/// <summary>
/// Sets up tests by initializing Xamarin.Forms.Mocks
/// </summary>
[TestInitialize]
public void SetUp()
{
Xamarin.Forms.Mocks.MockForms.Init();
FFImageLoading.ImageService.EnableMockImageService = true;
}
/// <summary>
/// Tests default ctor of AddLiveWaypointPopupPage
/// </summary>
[TestMethod]
public void TestDefaultCtor()
{
// set up
var location = new Location
{
Name = "Test Live Waypoint",
Type = LocationType.LiveWaypoint,
InternetLink = "where-to-fly://xxx",
};
var page = new AddLiveWaypointPopupPage(location);
// check
Assert.IsNotNull(page.Content, "page content must have been set");
}
}
}
| 28.069767 | 78 | 0.56918 | [
"BSD-2-Clause"
] | vividos/WhereToFly | src/App/UnitTest/Views/AddLiveWaypointPopupPageTest.cs | 1,209 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Linq;
using Xunit;
using Yarp.ReverseProxy.Service.Config;
using Yarp.ReverseProxy.Service.RuntimeModel.Transforms;
namespace Yarp.ReverseProxy.Abstractions.Config
{
public class RequestHeadersTransformExtensionsTests : TransformExtentionsTestsBase
{
private readonly RequestHeadersTransformFactory _factory = new();
[Theory]
[InlineData(true)]
[InlineData(false)]
public void WithTransformCopyRequestHeaders(bool copy)
{
var proxyRoute = new ProxyRoute();
proxyRoute = proxyRoute.WithTransformCopyRequestHeaders(copy);
var builderContext = ValidateAndBuild(proxyRoute, _factory);
Assert.Equal(copy, builderContext.CopyRequestHeaders);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void WithTransformUseOriginalHostHeader(bool useOriginal)
{
var proxyRoute = new ProxyRoute();
proxyRoute = proxyRoute.WithTransformUseOriginalHostHeader(useOriginal);
var builderContext = ValidateAndBuild(proxyRoute, _factory);
Assert.Equal(useOriginal, builderContext.UseOriginalHost);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void WithTransformRequestHeader(bool append)
{
var proxyRoute = new ProxyRoute();
proxyRoute = proxyRoute.WithTransformRequestHeader("name", "value", append);
var builderContext = ValidateAndBuild(proxyRoute, _factory);
ValidateRequestHeader(append, builderContext);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void AddRequestHeader(bool append)
{
var builderContext = CreateBuilderContext();
builderContext.AddRequestHeader("name", "value", append);
ValidateRequestHeader(append, builderContext);
}
private static void ValidateRequestHeader(bool append, TransformBuilderContext builderContext)
{
var requestHeaderValueTransform = Assert.Single(builderContext.RequestTransforms.OfType<RequestHeaderValueTransform>().Where(x => x.HeaderName == "name"));
Assert.Equal("value", requestHeaderValueTransform.Value);
Assert.Equal(append, requestHeaderValueTransform.Append);
}
}
}
| 33.972603 | 167 | 0.667339 | [
"MIT"
] | bmatatuk/reverse-proxy | test/ReverseProxy.Tests/Abstractions/Config/RequestHeadersTransformExtensionsTests.cs | 2,480 | C# |
using System.Threading.Tasks;
namespace SIL.Machine.Threading
{
/// <summary>
/// Provides completed task constants.
/// </summary>
public static class TaskConstants
{
/// <summary>
/// A task that has been completed with the value <c>true</c>.
/// </summary>
public static Task<bool> BooleanTrue { get; } = Task.FromResult(true);
/// <summary>
/// A task that has been completed with the value <c>false</c>.
/// </summary>
public static Task<bool> BooleanFalse => TaskConstants<bool>.Default;
/// <summary>
/// A task that has been completed with the value <c>0</c>.
/// </summary>
public static Task<int> Int32Zero => TaskConstants<int>.Default;
/// <summary>
/// A task that has been completed with the value <c>-1</c>.
/// </summary>
public static Task<int> Int32NegativeOne { get; } = Task.FromResult(-1);
/// <summary>
/// A <see cref="Task"/> that has been completed.
/// </summary>
public static Task Completed => BooleanTrue;
/// <summary>
/// A <see cref="Task"/> that will never complete.
/// </summary>
public static Task Never => TaskConstants<bool>.Never;
/// <summary>
/// A task that has been canceled.
/// </summary>
public static Task Canceled => TaskConstants<bool>.Canceled;
}
/// <summary>
/// Provides completed task constants.
/// </summary>
/// <typeparam name="T">The type of the task result.</typeparam>
public static class TaskConstants<T>
{
private static Task<T> CanceledTask()
{
var tcs = new TaskCompletionSource<T>();
tcs.SetCanceled();
return tcs.Task;
}
/// <summary>
/// A task that has been completed with the default value of <typeparamref name="T"/>.
/// </summary>
public static Task<T> Default { get; } = Task.FromResult(default(T));
/// <summary>
/// A <see cref="Task"/> that will never complete.
/// </summary>
public static Task<T> Never { get; } = new TaskCompletionSource<T>().Task;
/// <summary>
/// A task that has been canceled.
/// </summary>
public static Task<T> Canceled { get; } = CanceledTask();
}
}
| 27.666667 | 88 | 0.641928 | [
"MIT"
] | russellmorley/machine | src/SIL.Machine/Threading/TaskConstants.cs | 2,077 | C# |
using LiveSplit.Mgs3LoadRemover;
using LiveSplit.Model;
using LiveSplit.UI.Components;
using System;
[assembly: ComponentFactory(typeof(LoadRemoverFactory))]
namespace LiveSplit.Mgs3LoadRemover
{
public class LoadRemoverFactory : IComponentFactory
{
public string ComponentName => "MGS3 HD Load Remover";
public string Description => "Automatically detects MGS3 HD load screens and removes them from GameTime.";
public ComponentCategory Category => ComponentCategory.Control;
public IComponent Create(LiveSplitState state) => new LoadRemoverComponent(state);
public string UpdateName => ComponentName;
public string UpdateURL => "";
public string XMLURL => "";
public Version Version => Version.Parse("1.0");
}
} | 37.666667 | 114 | 0.723135 | [
"MIT"
] | makotocchi/LiveSplit.BlackScreenDetector | LoadRemoverFactory.cs | 793 | C# |
namespace PicturesShop.Models.OrderController
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
public class ChangeStatus
{
[Required]
public int OrderId { get; set; }
[Required]
public string Status { get; set; }
}
}
| 21.055556 | 48 | 0.651715 | [
"MIT"
] | ruydiy/PicturesShop | PicturesShop/Models/OrderController/ChangeStatus.cs | 381 | C# |
// Copyright(c) 2021 Digital Asset(Switzerland) GmbH and/or its affiliates.All rights reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Reactive.Concurrency;
namespace Daml.Ledger.Client.Reactive
{
using Daml.Ledger.Client.Reactive.Util;
using Daml.Ledger.Api.Data.Util;
using GetLedgerConfigurationResponse = Com.Daml.Ledger.Api.V1.GetLedgerConfigurationResponse;
using TraceContext = Com.Daml.Ledger.Api.V1.TraceContext;
public class LedgerConfigurationClient
{
private readonly ILedgerConfigurationClient _ledgerConfigurationClient;
private readonly IScheduler _scheduler;
public LedgerConfigurationClient(ILedgerConfigurationClient ledgerConfigurationClient, IScheduler scheduler = null)
{
_ledgerConfigurationClient = ledgerConfigurationClient;
_scheduler = scheduler;
}
public IObservable<GetLedgerConfigurationResponse> GetLedgerConfiguration(Optional<string> accessToken = null, TraceContext traceContext = null)
{
return _ledgerConfigurationClient.GetLedgerConfiguration(accessToken?.Reduce((string) null), traceContext).CreateAsyncObservable(_scheduler);
}
}
}
| 38.5 | 153 | 0.755682 | [
"Apache-2.0"
] | AndrewDCDrummond/daml-net | src/Daml.Ledger.Client.Reactive/LedgerConfigurationClient.cs | 1,234 | 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.IO;
using System.Linq;
using System.Xml.Linq;
using FluentAssertions;
using NuGet.Test.Utility;
using Xunit;
namespace NuGet.Configuration.Test
{
public class CredentialsItemTests
{
private static readonly string _moreThanOneUsername = Resources.Error_MoreThanOneUsername;
private static readonly string _moreThanOnePassword = Resources.Error_MoreThanOnePassword;
private static readonly string _moreThanOneValidAuthenticationTypes = Resources.Error_MoreThanOneValidAuthenticationTypes;
[Theory]
[InlineData(null, "user", "pass")]
[InlineData("", "user", "pass")]
[InlineData("name", null, "pass")]
[InlineData("name", "", "pass")]
[InlineData("name", "user", null)]
[InlineData("name", "user", "")]
public void CredentialsItem_Constructor_WithEmptyOrNullParameters_Throws(string name, string username, string password)
{
var ex = Record.Exception(() => new CredentialsItem(name, username, password, isPasswordClearText: true, validAuthenticationTypes: null));
ex.Should().NotBeNull();
ex.Should().BeOfType<ArgumentException>();
}
[Fact]
public void CredentialsItem_Constructor_WithSpaceOnName_EncodesItCorrectly()
{
var item = new CredentialsItem("credentials name", "username", "password", isPasswordClearText: true, validAuthenticationTypes: null);
item.ElementName.Should().Be("credentials name");
}
[Fact]
public void CredentialsItem_Parsing_WithoutUsername_Throws()
{
// Arrange
var nugetConfigPath = "NuGet.Config";
var config = @"
<configuration>
<packageSourceCredentials>
<NuGet.Org meta1='data1'>
<add key='Password' value='password' />
</NuGet.Org>
</packageSourceCredentials>
</configuration>";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var ex = Record.Exception(() => new SettingsFile(mockBaseDirectory));
ex.Should().NotBeNull();
ex.Should().BeOfType<NuGetConfigurationException>();
ex.Message.Should().Be(string.Format("Unable to parse config file because: Credentials item must have username and password. Path: '{0}'.", Path.Combine(mockBaseDirectory, nugetConfigPath)));
}
}
[Fact]
public void CredentialsItem_Parsing_WithoutPasswordOrClearTextPassword_Throws()
{
// Arrange
var nugetConfigPath = "NuGet.Config";
var config = @"
<configuration>
<packageSourceCredentials>
<NuGet.Org meta1='data1'>
<add key='Username' value='username' />
</NuGet.Org>
</packageSourceCredentials>
</configuration>";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var ex = Record.Exception(() => new SettingsFile(mockBaseDirectory));
ex.Should().NotBeNull();
ex.Should().BeOfType<NuGetConfigurationException>();
ex.Message.Should().Be(string.Format("Unable to parse config file because: Credentials item must have username and password. Path: '{0}'.", Path.Combine(mockBaseDirectory, nugetConfigPath)));
}
}
[Fact]
public void CredentialsItem_Parsing_WithUsernamePasswordAndClearTextPassword_Throws()
{
// Arrange
var nugetConfigPath = "NuGet.Config";
var config = @"
<configuration>
<packageSourceCredentials>
<NuGet.Org meta1='data1'>
<add key='Username' value='username' />
<add key='Password' value='password' />
<add key='ClearTextPassword' value='clearTextPassword' />
</NuGet.Org>
</packageSourceCredentials>
</configuration>";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var ex = Record.Exception(() => new SettingsFile(mockBaseDirectory));
ex.Should().NotBeNull();
ex.Should().BeOfType<NuGetConfigurationException>();
ex.Message.Should().Be(string.Format("Unable to parse config file because: {0} Path: '{1}'.", _moreThanOnePassword, Path.Combine(mockBaseDirectory, nugetConfigPath)));
}
}
[Fact]
public void CredentialsItem_Parsing_WithMultiplePassword_Throws()
{
// Arrange
var nugetConfigPath = "NuGet.Config";
var config = @"
<configuration>
<packageSourceCredentials>
<NuGet.Org meta1='data1'>
<add key='Username' value='username' />
<add key='Password' value='password' />
<add key='Password' value='password' />
</NuGet.Org>
</packageSourceCredentials>
</configuration>";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var ex = Record.Exception(() => new SettingsFile(mockBaseDirectory));
ex.Should().NotBeNull();
ex.Should().BeOfType<NuGetConfigurationException>();
ex.Message.Should().Be(string.Format("Unable to parse config file because: {0} Path: '{1}'.", _moreThanOnePassword, Path.Combine(mockBaseDirectory, nugetConfigPath)));
}
}
[Fact]
public void CredentialsItem_Parsing_WithMultipleClearTextPassword_Throws()
{
// Arrange
var nugetConfigPath = "NuGet.Config";
var config = @"
<configuration>
<packageSourceCredentials>
<NuGet.Org meta1='data1'>
<add key='Username' value='username' />
<add key='ClearTextPassword' value='clearTextPassword' />
<add key='ClearTextPassword' value='clearTextPassword' />
</NuGet.Org>
</packageSourceCredentials>
</configuration>";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var ex = Record.Exception(() => new SettingsFile(mockBaseDirectory));
ex.Should().NotBeNull();
ex.Should().BeOfType<NuGetConfigurationException>();
ex.Message.Should().Be(string.Format("Unable to parse config file because: {0} Path: '{1}'.", _moreThanOnePassword, Path.Combine(mockBaseDirectory, nugetConfigPath)));
}
}
[Fact]
public void CredentialsItem_Parsing_WithMultipleUsernames_Throws()
{
// Arrange
var nugetConfigPath = "NuGet.Config";
var config = @"
<configuration>
<packageSourceCredentials>
<NuGet.Org meta1='data1'>
<add key='Username' value='username' />
<add key='Username' value='username2' />
<add key='Password' value='password' />
</NuGet.Org>
</packageSourceCredentials>
</configuration>";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var ex = Record.Exception(() => new SettingsFile(mockBaseDirectory));
ex.Should().NotBeNull();
ex.Should().BeOfType<NuGetConfigurationException>();
ex.Message.Should().Be(string.Format("Unable to parse config file because: {0} Path: '{1}'.", _moreThanOneUsername, Path.Combine(mockBaseDirectory, nugetConfigPath)));
}
}
[Fact]
public void CredentialsItem_Parsing_WithMultipleValidAuthenticationTypes_Throws()
{
// Arrange
var nugetConfigPath = "NuGet.Config";
var config = @"
<configuration>
<packageSourceCredentials>
<NuGet.Org meta1='data1'>
<add key='Username' value='username' />
<add key='Password' value='password' />
<add key='ValidAuthenticationTypes' value='one,two,three' />
<add key='ValidAuthenticationTypes' value='four,five,six' />
</NuGet.Org>
</packageSourceCredentials>
</configuration>";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var ex = Record.Exception(() => new SettingsFile(mockBaseDirectory));
ex.Should().NotBeNull();
ex.Should().BeOfType<NuGetConfigurationException>();
ex.Message.Should().Be(string.Format("Unable to parse config file because: {0} Path: '{1}'.", _moreThanOneValidAuthenticationTypes, Path.Combine(mockBaseDirectory, nugetConfigPath)));
}
}
[Fact]
public void CredentialsItem_Update_WhenItemIsNotCredentialsItem_Throws()
{
// Arrange
var credentials = new CredentialsItem("name", "user", "pass", isPasswordClearText: true, validAuthenticationTypes: null);
// Act
var ex = Record.Exception(() => credentials.Update(new AddItem("key", "value")));
// Assert
ex.Should().NotBeNull();
ex.Should().BeOfType<InvalidOperationException>();
ex.Message.Should().Be("The item passed to the Update method cannot refer to a different item than the one being updated.");
credentials.ElementName.Should().Be("name");
credentials.Username.Should().Be("user");
credentials.Password.Should().Be("pass");
}
[Fact]
public void CredentialsItem_Update_WhenOriginIsMachineWide_Throws()
{
// Arrange
using (var mockBaseDirectory = TestDirectory.Create())
{
var origin = new SettingsFile(mockBaseDirectory, fileName: Settings.DefaultSettingsFileName, isMachineWide: true);
var xelement = new XElement("name",
new XElement("add", new XAttribute("key", "Username"), new XAttribute("value", "user")),
new XElement("add", new XAttribute("key", "Password"), new XAttribute("value", "pass")));
var credentials = new CredentialsItem(xelement, origin);
// Act
var ex = Record.Exception(() =>
credentials.Update(new CredentialsItem("name", "user", "notpass", isPasswordClearText: true, validAuthenticationTypes: null)));
// Assert
ex.Should().NotBeNull();
ex.Should().BeOfType<InvalidOperationException>();
ex.Message.Should().Be("Unable to update setting since it is in a machine-wide NuGet.Config.");
credentials.Password.Should().Be("pass");
}
}
[Fact]
public void CredentialsItem_Update_ChangeUsername_UpdatesObjectAndXNode()
{
// Arrange
using (var mockBaseDirectory = TestDirectory.Create())
{
var origin = new SettingsFile(mockBaseDirectory);
var xelement = new XElement("name",
new XElement("add", new XAttribute("key", "Username"), new XAttribute("value", "user")),
new XElement("add", new XAttribute("key", "Password"), new XAttribute("value", "pass")));
var credentials = new CredentialsItem(xelement, origin);
// Act
credentials.Update(new CredentialsItem("name", "newuser", "pass", isPasswordClearText: false, validAuthenticationTypes: null));
// Assert
credentials.Username.Should().Be("newuser");
var credentialElement = credentials.AsXNode() as XElement;
var childElements = credentialElement.Elements().ToList();
childElements.Count.Should().Be(2);
childElements[0].Name.LocalName.Should().Be("add");
var elattr = childElements[0].Attributes().ToList();
elattr.Count.Should().Be(2);
elattr[0].Value.Should().Be("Username");
elattr[1].Value.Should().Be("newuser");
}
}
[Fact]
public void CredentialsItem_Update_ChangePassword_UpdatesObjectAndXNode()
{
// Arrange
using (var mockBaseDirectory = TestDirectory.Create())
{
var origin = new SettingsFile(mockBaseDirectory);
var xelement = new XElement("name",
new XElement("add", new XAttribute("key", "Username"), new XAttribute("value", "user")),
new XElement("add", new XAttribute("key", "Password"), new XAttribute("value", "pass")));
var credentials = new CredentialsItem(xelement, origin);
// Act
credentials.Update(new CredentialsItem("name", "user", "newpass", isPasswordClearText: false, validAuthenticationTypes: null));
// Assert
credentials.Password.Should().Be("newpass");
var credentialElement = credentials.AsXNode() as XElement;
var childElements = credentialElement.Elements().ToList();
childElements.Count.Should().Be(2);
childElements[1].Name.LocalName.Should().Be("add");
var elattr = childElements[1].Attributes().ToList();
elattr.Count.Should().Be(2);
elattr[0].Value.Should().Be("Password");
elattr[1].Value.Should().Be("newpass");
}
}
[Fact]
public void CredentialsItem_Update_ChangeClearTextPassword_UpdatesObjectAndXNode()
{
// Arrange
using (var mockBaseDirectory = TestDirectory.Create())
{
var origin = new SettingsFile(mockBaseDirectory);
var xelement = new XElement("name",
new XElement("add", new XAttribute("key", "Username"), new XAttribute("value", "user")),
new XElement("add", new XAttribute("key", "ClearTextPassword"), new XAttribute("value", "pass")));
var credentials = new CredentialsItem(xelement, origin);
// Act
credentials.Update(new CredentialsItem("name", "user", "newpass", isPasswordClearText: true, validAuthenticationTypes: null));
// Assert
credentials.Password.Should().Be("newpass");
var credentialElement = credentials.AsXNode() as XElement;
var childElements = credentialElement.Elements().ToList();
childElements.Count.Should().Be(2);
childElements[1].Name.LocalName.Should().Be("add");
var elattr = childElements[1].Attributes().ToList();
elattr.Count.Should().Be(2);
elattr[0].Value.Should().Be("ClearTextPassword");
elattr[1].Value.Should().Be("newpass");
}
}
[Fact]
public void CredentialsItem_Update_MakingPasswordClearText_UpdatesObjectAndXNode()
{
// Arrange
using (var mockBaseDirectory = TestDirectory.Create())
{
var origin = new SettingsFile(mockBaseDirectory);
var xelement = new XElement("name",
new XElement("add", new XAttribute("key", "Username"), new XAttribute("value", "user")),
new XElement("add", new XAttribute("key", "Password"), new XAttribute("value", "pass")));
var credentials = new CredentialsItem(xelement, origin);
// Act
credentials.Update(new CredentialsItem("name", "user", "newpass", isPasswordClearText: true, validAuthenticationTypes: null));
// Assert
credentials.Password.Should().Be("newpass");
var credentialElement = credentials.AsXNode() as XElement;
var childElements = credentialElement.Elements().ToList();
childElements.Count.Should().Be(2);
childElements[1].Name.LocalName.Should().Be("add");
var elattr = childElements[1].Attributes().ToList();
elattr.Count.Should().Be(2);
elattr[0].Value.Should().Be("ClearTextPassword");
elattr[1].Value.Should().Be("newpass");
}
}
[Fact]
public void CredentialsItem_Update_MakingPasswordEncrypted_UpdatesObjectAndXNode()
{
// Arrange
using (var mockBaseDirectory = TestDirectory.Create())
{
var origin = new SettingsFile(mockBaseDirectory);
var xelement = new XElement("name",
new XElement("add", new XAttribute("key", "Username"), new XAttribute("value", "user")),
new XElement("add", new XAttribute("key", "ClearTextPassword"), new XAttribute("value", "pass")));
var credentials = new CredentialsItem(xelement, origin);
// Act
credentials.Update(new CredentialsItem("name", "user", "newpass", isPasswordClearText: false, validAuthenticationTypes: null));
// Assert
credentials.Password.Should().Be("newpass");
var credentialElement = credentials.AsXNode() as XElement;
var childElements = credentialElement.Elements().ToList();
childElements.Count.Should().Be(2);
childElements[1].Name.LocalName.Should().Be("add");
var elattr = childElements[1].Attributes().ToList();
elattr.Count.Should().Be(2);
elattr[0].Value.Should().Be("Password");
elattr[1].Value.Should().Be("newpass");
}
}
[Fact]
public void CredentialsItem_Update_RemovingValidAuthenticationTypes_UpdatesObjectAndFile()
{
// Arrange
using (var mockBaseDirectory = TestDirectory.Create())
{
var origin = new SettingsFile(mockBaseDirectory);
var xelement = new XElement("name",
new XElement("add", new XAttribute("key", "Username"), new XAttribute("value", "user")),
new XElement("add", new XAttribute("key", "ClearTextPassword"), new XAttribute("value", "pass")),
new XElement("add", new XAttribute("key", "ValidAuthenticationTypes"), new XAttribute("value", "one, two, three")));
var credentials = new CredentialsItem(xelement, origin);
// Act
credentials.Update(new CredentialsItem("name", "user", "pass", isPasswordClearText: true, validAuthenticationTypes: null));
// Assert
credentials.ValidAuthenticationTypes.Should().BeNull();
origin.IsDirty.Should().BeTrue();
origin.SaveToDisk();
var credentialElement = credentials.AsXNode() as XElement;
var childElements = credentialElement.Elements().ToList();
childElements.Count.Should().Be(2);
childElements[1].Name.LocalName.Should().Be("add");
var elattr = childElements[0].Attributes().ToList();
elattr.Count.Should().Be(2);
elattr[0].Value.Should().Be("Username");
childElements[1].Name.LocalName.Should().Be("add");
elattr = childElements[1].Attributes().ToList();
elattr.Count.Should().Be(2);
elattr[0].Value.Should().Be("ClearTextPassword");
}
}
[Fact]
public void CredentialsItem_AsXNode_WithSpaceInName_ReturnsCorrectElement()
{
// Arrange
var credentialsItem = new CredentialsItem("credentials name", "username", "password", isPasswordClearText: false, validAuthenticationTypes: null);
// Act
var xnode = credentialsItem.AsXNode();
// Assert
xnode.Should().BeOfType<XElement>();
var xelement = xnode as XElement;
xelement.Name.LocalName.Should().Be("credentials_x0020_name");
var elements = xelement.Elements().ToList();
elements.Count.Should().Be(2);
elements[0].Name.LocalName.Should().Be("add");
var elattr = elements[0].Attributes().ToList();
elattr.Count.Should().Be(2);
elattr[0].Value.Should().Be("Username");
elattr[1].Value.Should().Be("username");
elements[1].Name.LocalName.Should().Be("add");
elattr = elements[1].Attributes().ToList();
elattr.Count.Should().Be(2);
elattr[0].Value.Should().Be("Password");
elattr[1].Value.Should().Be("password");
}
[Fact]
public void CredentialsItem_AsXNode_WithUsernameAndPassword_ReturnsCorrectElement()
{
// Arrange
var credentialsItem = new CredentialsItem("name", "username", "password", isPasswordClearText: false, validAuthenticationTypes: null);
// Act
var xnode = credentialsItem.AsXNode();
// Assert
xnode.Should().BeOfType<XElement>();
var xelement = xnode as XElement;
xelement.Name.LocalName.Should().Be("name");
var elements = xelement.Elements().ToList();
elements.Count.Should().Be(2);
elements[0].Name.LocalName.Should().Be("add");
var elattr = elements[0].Attributes().ToList();
elattr.Count.Should().Be(2);
elattr[0].Value.Should().Be("Username");
elattr[1].Value.Should().Be("username");
elements[1].Name.LocalName.Should().Be("add");
elattr = elements[1].Attributes().ToList();
elattr.Count.Should().Be(2);
elattr[0].Value.Should().Be("Password");
elattr[1].Value.Should().Be("password");
}
[Fact]
public void CredentialsItem_AsXNode_WithUsernameAndClearTextPassword_ReturnsCorrectElement()
{
// Arrange
var credentialsItem = new CredentialsItem("name", "username", "password", isPasswordClearText: true, validAuthenticationTypes: null);
// Act
var xnode = credentialsItem.AsXNode();
// Assert
xnode.Should().BeOfType<XElement>();
var xelement = xnode as XElement;
xelement.Name.LocalName.Should().Be("name");
var elements = xelement.Elements().ToList();
elements.Count.Should().Be(2);
elements[0].Name.LocalName.Should().Be("add");
var elattr = elements[0].Attributes().ToList();
elattr.Count.Should().Be(2);
elattr[0].Value.Should().Be("Username");
elattr[1].Value.Should().Be("username");
elements[1].Name.LocalName.Should().Be("add");
elattr = elements[1].Attributes().ToList();
elattr.Count.Should().Be(2);
elattr[0].Value.Should().Be("ClearTextPassword");
elattr[1].Value.Should().Be("password");
}
[Fact]
public void CredentialsItem_Equals_WithSameElementName_ReturnsTrue()
{
var credentials1 = new CredentialsItem("source", "user", "pass", isPasswordClearText: true, validAuthenticationTypes: "one,two,three");
var credentials2 = new CredentialsItem("source", "user2", "pass", isPasswordClearText: false, validAuthenticationTypes: null);
credentials1.Equals(credentials2).Should().BeTrue();
}
[Fact]
public void CredentialsItem_Equals_WithDifferentElemenName_ReturnsFalse()
{
var credentials1 = new CredentialsItem("source1", "user", "pass", isPasswordClearText: true, validAuthenticationTypes: "one,two,three");
var credentials2 = new CredentialsItem("source2", "user", "pass", isPasswordClearText: true, validAuthenticationTypes: "one,two,three");
credentials1.Equals(credentials2).Should().BeFalse();
}
[Fact]
public void CredentialsItem_ElementName_IsCorrect()
{
var credentialsItem = new CredentialsItem("source", "user", "pass", isPasswordClearText: false, validAuthenticationTypes: null);
credentialsItem.ElementName.Should().Be("source");
}
[Fact]
public void CredentialsItem_Clone_ReturnsItemClone()
{
// Arrange
var config = @"
<configuration>
<packageSourceCredentials>
<NuGet.Org meta1='data1'>
<add key='Username' value='username' />
<add key='Password' value='password' />
<add key='ValidAuthenticationTypes' value='one,two,three' />
</NuGet.Org>
</packageSourceCredentials>
</configuration>";
var nugetConfigPath = "NuGet.Config";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var settingsFile = new SettingsFile(mockBaseDirectory);
settingsFile.TryGetSection("packageSourceCredentials", out var section).Should().BeTrue();
section.Should().NotBeNull();
section.Items.Count.Should().Be(1);
var item = section.Items.First();
item.IsCopy().Should().BeFalse();
item.Origin.Should().NotBeNull();
var clone = item.Clone() as CredentialsItem;
clone.IsCopy().Should().BeTrue();
clone.Origin.Should().NotBeNull();
SettingsTestUtils.DeepEquals(clone, item).Should().BeTrue();
}
}
[Fact]
public void CredentialsItem_Clone_WithSpaceOnName_ReturnsItemClone()
{
// Arrange
var config = @"
<configuration>
<packageSourceCredentials>
<nuget_x0020_org>
<add key='Username' value='username' />
<add key='Password' value='password' />
</nuget_x0020_org>
</packageSourceCredentials>
</configuration>";
var nugetConfigPath = "NuGet.Config";
using (var mockBaseDirectory = TestDirectory.Create())
{
SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
// Act and Assert
var settingsFile = new SettingsFile(mockBaseDirectory);
settingsFile.TryGetSection("packageSourceCredentials", out var section).Should().BeTrue();
section.Should().NotBeNull();
section.Items.Count.Should().Be(1);
var item = section.Items.First();
item.IsCopy().Should().BeFalse();
item.Origin.Should().NotBeNull();
var clone = item.Clone() as CredentialsItem;
clone.IsCopy().Should().BeTrue();
clone.Origin.Should().NotBeNull();
SettingsTestUtils.DeepEquals(clone, item).Should().BeTrue();
}
}
}
}
| 42.591928 | 207 | 0.581561 | [
"Apache-2.0"
] | BdDsl/NuGet.Client | test/NuGet.Core.Tests/NuGet.Configuration.Test/SettingsFileParsingTests/CredentialsItemTests.cs | 28,494 | C# |
using System;
using System.IO;
namespace Sample
{
class Test
{
static void Main(string[] args)
{
// Add a page header and footer during the conversion of HTML to RTF or DOCX.
// If you need more information about "HTML to RTF .Net" email us at:
// support@sautinsoft.com.
AddHeaderAndFooter();
}
public static void AddHeaderAndFooter()
{
SautinSoft.HtmlToRtf h = new SautinSoft.HtmlToRtf();
// After purchasing the license, please insert your serial number here to activate the component.
// h.Serial = "XXXXXXXXX";
string inputFile = @"..\..\Sample.html";
string outputFile = "Result.docx";
// Set page header and footer.
string headerFromHtml = File.ReadAllText(@"..\..\header.html");
string footerFromRtf = File.ReadAllText(@"..\..\footer.rtf");
// Add page header.
h.PageStyle.PageHeader.Html(headerFromHtml);
// Add extra space between header and page contents.
h.PageStyle.PageHeader.MarginBottom.Mm(10);
// Add page footer.
h.PageStyle.PageFooter.Rtf(footerFromRtf);
if (h.OpenHtml(inputFile))
{
bool ok = h.ToDocx(outputFile);
// Open the result for demonstration purposes.
if (ok)
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outputFile) { UseShellExecute = true });
}
}
}
}
| 33.02 | 134 | 0.548758 | [
"MIT"
] | SautinSoft/HTML-to-RTF-Net | CSharp/Properties and Settings/Add page header and footer/sample.cs | 1,651 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowPlayerLook : MonoBehaviour
{
public GameObject PlayerCamera;
[Range(1f, 2.5f)]
public float distance = 2;
[Range(-2f, 2f)]
public float yOffset = 0.5f;
public bool FollowPosition = true;
public bool ConstraintY = true;
public bool LookAtPlayer = true;
private Transform rectTransform;
void Awake()
{
rectTransform = GetComponent<RectTransform>();
}
// Update is called once per frame
void Update()
{
if (FollowPosition)
FollowPlayerPosition();
if (LookAtPlayer)
FollowPlayerEyeRotation();
}
void FollowPlayerPosition()
{
var position = PlayerCamera.transform.position + (PlayerCamera.transform.forward * distance);
if (ConstraintY)
position.y = PlayerCamera.transform.position.y + yOffset;
rectTransform.position = position;
}
void FollowPlayerEyeRotation()
{
var lookPos = PlayerCamera.transform.position - rectTransform.position;
lookPos.y = 0;
Vector3 myEulerAngles = Quaternion.LookRotation(lookPos).eulerAngles;
Quaternion myFixedQuaternion = Quaternion.Euler(-myEulerAngles.x, myEulerAngles.y, myEulerAngles.z);
rectTransform.rotation = myFixedQuaternion;//Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
}
}
| 26.160714 | 126 | 0.672355 | [
"MIT"
] | zraul123/FCAVR | Assets/Scripts/Helpers/FollowPlayerLook.cs | 1,467 | C# |
using System;
namespace SumArrayElements
{
class SumArrayElements
{
static void Main()
{
var n = int.Parse(Console.ReadLine());
var numbers = new int[n];
var result = 0;
for (int i = 0; i < n; i++)
{
var currentNumber = int.Parse(Console.ReadLine());
numbers[i] = currentNumber;
result += numbers[i];
}
Console.WriteLine(result);
}
}
}
| 20.36 | 66 | 0.455796 | [
"MIT"
] | hristokrastev/MasteringC | Arrays_Exercises/SumArrayElements/SumArrayElements/SumArrayElements.cs | 511 | C# |
// <auto-generated />
namespace TrashCollector.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
public sealed partial class Updateforeignkey2 : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(Updateforeignkey2));
string IMigrationMetadata.Id
{
get { return "201710222322233_Update foreign key2"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 27.966667 | 100 | 0.628129 | [
"MIT"
] | jnnfrlocke/TrashCollector | TrashCollector/Migrations/201710222322233_Update foreign key2.Designer.cs | 839 | C# |
using System;
namespace Elmah.Io.NLog.AspNetCore31.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
| 18.75 | 70 | 0.675556 | [
"Apache-2.0"
] | elmahio/elmah.io.nlog | samples/Elmah.Io.NLog.AspNetCore31/Models/ErrorViewModel.cs | 225 | C# |
// <auto-generated />
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
namespace TechMech.Migrations
{
[GeneratedCode("EntityFramework.Migrations", "6.1.1-30610")]
public sealed partial class AddBirthdateToCustomer : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(AddBirthdateToCustomer));
string IMigrationMetadata.Id
{
get { return "201604050626453_AddBirthdateToCustomer"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 26.333333 | 105 | 0.639241 | [
"MIT"
] | kiran8143/TechMech | TechMech/Migrations/201604050626453_AddBirthdateToCustomer.Designer.cs | 790 | 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("BarsReading.Program")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("BarsReading.Program")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2014")]
[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("97fe5fe5-a8cc-4373-8edd-f11bc9ba55c0")]
// 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")] | 39.666667 | 84 | 0.75 | [
"MIT"
] | eduardo-yuschuk/cs_trading | BarsReading.Program/Properties/AssemblyInfo.cs | 1,431 | C# |
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
using System;
using System.Collections.Generic;
#nullable disable
namespace T0001
{
public partial class Wipreturninfo
{
public string Erpcode { get; set; }
public string Cinvcode { get; set; }
public string Cinvname { get; set; }
public decimal? Iquantity { get; set; }
public string Bonded { get; set; }
}
} | 28 | 97 | 0.632353 | [
"MIT"
] | twoutlook/BlazorServerDbContextExample | BlazorServerEFCoreSample/T0001/Wipreturninfo.cs | 478 | C# |
// Copyright (c) 2010-2018 The Bitcoin developers
// Original code was distributed under the MIT software license.
// Copyright (c) 2014-2018 TEDLab Sciences Ltd
// Tedchain code distributed under the GPLv3 license, see COPYING file.
using System;
using System.Collections.Generic;
using System.Linq;
using Tedchain.Infrastructure;
namespace Tedchain.Validation.PermissionBased
{
/// <summary>
/// Represents an implementation of the <see cref="IPermissionSubject"/> interface based on public key hashes.
/// </summary>
public class P2pkhSubject : IPermissionSubject
{
private readonly KeyEncoder keyEncoder;
public P2pkhSubject(IEnumerable<string> addresses, int signaturesRequired, KeyEncoder keyEncoder)
{
this.Addresses = addresses.ToList().AsReadOnly();
this.SignaturesRequired = signaturesRequired;
this.keyEncoder = keyEncoder;
}
/// <summary>
/// Gets the list of valid addresses.
/// </summary>
public IReadOnlyList<string> Addresses { get; }
/// <summary>
/// Gets the number of required signatures for a match.
/// </summary>
public int SignaturesRequired { get; }
public bool IsMatch(IReadOnlyList<SignatureEvidence> authentication)
{
HashSet<string> identities = new HashSet<string>(authentication.Select(evidence => keyEncoder.GetPubKeyHash(evidence.PublicKey)), StringComparer.Ordinal);
return Addresses.Count(address => identities.Contains(address)) >= SignaturesRequired;
}
}
}
| 36.5 | 166 | 0.680573 | [
"Apache-2.0"
] | tedchain/tedchain-technology | src/Tedchain.Validation.PermissionBased/P2pkhSubject.cs | 1,608 | C# |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime.DurableInstancing
{
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using System.Security;
using System.Xml.Linq;
[Serializable]
public class InstanceNotReadyException : InstancePersistenceCommandException
{
public InstanceNotReadyException()
: this(SRCore.InstanceNotReadyDefault, null)
{
}
public InstanceNotReadyException(string message)
: this(message, null)
{
}
public InstanceNotReadyException(string message, Exception innerException)
: base(message, innerException)
{
}
public InstanceNotReadyException(XName commandName, Guid instanceId)
: this(commandName, instanceId, null)
{
}
public InstanceNotReadyException(XName commandName, Guid instanceId, Exception innerException)
: this(commandName, instanceId, ToMessage(instanceId), innerException)
{
}
public InstanceNotReadyException(XName commandName, Guid instanceId, string message, Exception innerException)
: base(commandName, instanceId, message, innerException)
{
}
[SecurityCritical]
protected InstanceNotReadyException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
static string ToMessage(Guid instanceId)
{
if (instanceId != Guid.Empty)
{
return SRCore.InstanceNotReadySpecific(instanceId);
}
return SRCore.InstanceNotReadyDefault;
}
}
}
| 31.066667 | 118 | 0.59603 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/ndp/cdf/src/NetFx40/System.Runtime.DurableInstancing/System/Runtime/DurableInstancing/InstanceNotReadyException.cs | 1,864 | C# |
//------------------------------------------------------------
// Game Framework v3.x
// Copyright © 2013-2017 Jiang Yin. All rights reserved.
// Homepage: http://gameframework.cn/
// Feedback: mailto:jiangyin@gameframework.cn
//------------------------------------------------------------
using GameFramework.Event;
using System;
namespace Hotfix.Runtime
{
/// <summary>
/// 加载数据表更新事件。
/// </summary>
public sealed class LoadDataTableUpdateEventArgs : GameEventArgs
{
/// <summary>
/// 初始化加载数据表更新事件的新实例。
/// </summary>
/// <param name="e">内部事件。</param>
public LoadDataTableUpdateEventArgs(GameFramework.DataTable.LoadDataTableUpdateEventArgs e)
{
LoadDataTableInfo loadDataTableInfo = (LoadDataTableInfo)e.UserData;
DataTableName = loadDataTableInfo.DataTableName;
DataTableType = loadDataTableInfo.DataTableType;
DataTableAssetName = e.DataTableAssetName;
Progress = e.Progress;
UserData = loadDataTableInfo.UserData;
}
/// <summary>
/// 获取加载数据表失败事件编号。
/// </summary>
public override int Id
{
get
{
return (int)EventId.LoadDataTableUpdate;
}
}
/// <summary>
/// 获取数据表名称。
/// </summary>
public string DataTableName
{
get;
private set;
}
/// <summary>
/// 获取数据表类型。
/// </summary>
public Type DataTableType
{
get;
private set;
}
/// <summary>
/// 获取数据表资源名称。
/// </summary>
public string DataTableAssetName
{
get;
private set;
}
/// <summary>
/// 获取加载数据表进度。
/// </summary>
public float Progress
{
get;
private set;
}
/// <summary>
/// 获取用户自定义数据。
/// </summary>
public object UserData
{
get;
private set;
}
}
}
| 23.921348 | 99 | 0.471113 | [
"MIT"
] | wuzhangwuzhang/ILGameFramework | Hotfix/Runtime/Event/LoadDataTableUpdateEventArgs.cs | 2,316 | 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.Collections.Generic;
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using Internal.TypeSystem.Ecma;
namespace ILTrim.DependencyAnalysis
{
/// <summary>
/// Represents an entry in the GenericParam metadata table.
/// </summary>
public sealed class GenericParameterNode : TokenBasedNodeWithDelayedSort
{
public GenericParameterNode(EcmaModule module, GenericParameterHandle handle)
: base(module, handle)
{
}
private GenericParameterHandle Handle => (GenericParameterHandle)_handle;
private int _ownerCodedIndex = -1;
private int _index = -1;
public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory)
{
GenericParameter genericParam = _module.MetadataReader.GetGenericParameter(Handle);
foreach (var genericParamConstrain in genericParam.GetConstraints())
{
yield return new DependencyListEntry(factory.GenericParameterConstraint(_module, genericParamConstrain), "Generic Parameter Constraint of Generic Parameter");
}
}
protected override EntityHandle WriteInternal(ModuleWritingContext writeContext)
{
MetadataReader reader = _module.MetadataReader;
GenericParameter genericParam = reader.GetGenericParameter(Handle);
var builder = writeContext.MetadataBuilder;
return builder.AddGenericParameter(writeContext.TokenMap.MapToken(genericParam.Parent),
genericParam.Attributes,
builder.GetOrAddString(reader.GetString(genericParam.Name)),
genericParam.Index);
}
public override string ToString()
{
MetadataReader reader = _module.MetadataReader;
return reader.GetString(reader.GetGenericParameter(Handle).Name);
}
public override void PrepareForDelayedSort(TokenMap.Builder tokenMap)
{
GenericParameter genericParam = _module.MetadataReader.GetGenericParameter(Handle);
_ownerCodedIndex = CodedIndex.TypeOrMethodDef(tokenMap.MapToken(genericParam.Parent));
_index = genericParam.Index;
}
public override int CompareTo(TokenWriterNode other)
{
if (other is GenericParameterNode otherGenericParameter)
{
Debug.Assert(_ownerCodedIndex >= 0 && otherGenericParameter._ownerCodedIndex >= 0);
return CompareGenericParameters(_ownerCodedIndex, _index, otherGenericParameter._ownerCodedIndex, otherGenericParameter._index);
}
else
{
return base.CompareTo(other);
}
}
internal static int CompareGenericParameters(int thisCodedIndex, int thisIndex, int otherCodedIndex, int otherIndex)
{
if (thisCodedIndex == otherCodedIndex)
return thisIndex.CompareTo(otherIndex);
else
return thisCodedIndex.CompareTo(otherCodedIndex);
}
}
}
| 38.870588 | 174 | 0.673729 | [
"MIT"
] | MichalStrehovsky/iltrim | src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/GenericParameterNode.cs | 3,306 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Models.Api20220330Preview
{
using Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="AzureBlob" />
/// </summary>
public partial class AzureBlobTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="AzureBlob" type/>.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="AzureBlob"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="AzureBlob" /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="AzureBlob" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="AzureBlob" />.</param>
/// <returns>
/// an instance of <see cref="AzureBlob" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Models.Api20220330Preview.IAzureBlob ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Models.Api20220330Preview.IAzureBlob).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return AzureBlob.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return AzureBlob.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return AzureBlob.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 51.671233 | 257 | 0.58815 | [
"MIT"
] | AlanFlorance/azure-powershell | src/DataMigration/DataMigration.Autorest/generated/api/Models/Api20220330Preview/AzureBlob.TypeConverter.cs | 7,399 | C# |
using System;
using System.ComponentModel;
using EfsTools.Attributes;
using EfsTools.Utils;
using Newtonsoft.Json;
namespace EfsTools.Items.Data
{
[Serializable]
public class TxFreqOffsetTableType
{
[ElementsCount(8)]
[ElementType("QMSL_Tx_Cal_Freq_Offset_Row_NV_Type")]
[Description("")]
public QmslTxCalFreqOffsetRowNvType[] Row { get; set; }
}
}
| 22.368421 | 64 | 0.658824 | [
"MIT"
] | HomerSp/EfsTools | EfsTools/Items/Data/TxFreqOffsetTableType.cs | 425 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Mirror
{
public class NetworkClient
{
// the client (can be a regular NetworkClient or a LocalClient)
public static NetworkClient singleton;
[Obsolete("Use NetworkClient.singleton instead. There is always exactly one client.")]
public static List<NetworkClient> allClients => new List<NetworkClient>{singleton};
public readonly Dictionary<int, NetworkMessageDelegate> handlers = new Dictionary<int, NetworkMessageDelegate>();
public NetworkConnection connection { get; protected set; }
protected enum ConnectState
{
None,
Connecting,
Connected,
Disconnected
}
protected ConnectState connectState = ConnectState.None;
public string serverIp { get; private set; } = "";
// active is true while a client is connecting/connected
// (= while the network is active)
public static bool active { get; protected set; }
public bool isConnected => connectState == ConnectState.Connected;
public NetworkClient()
{
if (LogFilter.Debug) Debug.Log("Client created version " + Version.Current);
if (singleton != null)
{
Debug.LogError("NetworkClient: can only create one!");
return;
}
singleton = this;
}
internal void SetHandlers(NetworkConnection conn)
{
conn.SetHandlers(handlers);
}
public void Connect(string ip)
{
if (LogFilter.Debug) Debug.Log("Client Connect: " + ip);
active = true;
RegisterSystemHandlers(false);
Transport.activeTransport.enabled = true;
InitializeTransportHandlers();
serverIp = ip;
connectState = ConnectState.Connecting;
Transport.activeTransport.ClientConnect(ip);
// setup all the handlers
connection = new NetworkConnection(serverIp, 0);
connection.SetHandlers(handlers);
}
private void InitializeTransportHandlers()
{
Transport.activeTransport.OnClientConnected.AddListener(OnConnected);
Transport.activeTransport.OnClientDataReceived.AddListener(OnDataReceived);
Transport.activeTransport.OnClientDisconnected.AddListener(OnDisconnected);
Transport.activeTransport.OnClientError.AddListener(OnError);
}
void OnError(Exception exception)
{
Debug.LogException(exception);
}
void OnDisconnected()
{
connectState = ConnectState.Disconnected;
ClientScene.HandleClientDisconnect(connection);
connection?.InvokeHandler(new DisconnectMessage());
}
protected void OnDataReceived(byte[] data)
{
if (connection != null)
{
connection.TransportReceive(data);
}
else Debug.LogError("Skipped Data message handling because m_Connection is null.");
}
void OnConnected()
{
if (connection != null)
{
// reset network time stats
NetworkTime.Reset();
// the handler may want to send messages to the client
// thus we should set the connected state before calling the handler
connectState = ConnectState.Connected;
NetworkTime.UpdateClient(this);
connection.InvokeHandler(new ConnectMessage());
}
else Debug.LogError("Skipped Connect message handling because m_Connection is null.");
}
public virtual void Disconnect()
{
connectState = ConnectState.Disconnected;
ClientScene.HandleClientDisconnect(connection);
if (connection != null)
{
connection.Disconnect();
connection.Dispose();
connection = null;
RemoveTransportHandlers();
}
// the client's network is not active anymore.
active = false;
}
void RemoveTransportHandlers()
{
// so that we don't register them more than once
Transport.activeTransport.OnClientConnected.RemoveListener(OnConnected);
Transport.activeTransport.OnClientDataReceived.RemoveListener(OnDataReceived);
Transport.activeTransport.OnClientDisconnected.RemoveListener(OnDisconnected);
Transport.activeTransport.OnClientError.RemoveListener(OnError);
}
[Obsolete("Use SendMessage<T> instead with no message id instead")]
public bool Send(short msgType, MessageBase msg)
{
if (connection != null)
{
if (connectState != ConnectState.Connected)
{
Debug.LogError("NetworkClient Send when not connected to a server");
return false;
}
return connection.Send(msgType, msg);
}
Debug.LogError("NetworkClient Send with no connection");
return false;
}
public bool Send<T>(T message) where T : MessageBase
{
if (connection != null)
{
if (connectState != ConnectState.Connected)
{
Debug.LogError("NetworkClient Send when not connected to a server");
return false;
}
return connection.Send(message);
}
Debug.LogError("NetworkClient Send with no connection");
return false;
}
internal virtual void Update()
{
// only update things while connected
if (active && connectState == ConnectState.Connected)
{
NetworkTime.UpdateClient(this);
}
}
/* TODO use or remove
void GenerateConnectError(byte error)
{
Debug.LogError("Mirror Client Error Connect Error: " + error);
GenerateError(error);
}
void GenerateDataError(byte error)
{
NetworkError dataError = (NetworkError)error;
Debug.LogError("Mirror Client Data Error: " + dataError);
GenerateError(error);
}
void GenerateDisconnectError(byte error)
{
NetworkError disconnectError = (NetworkError)error;
Debug.LogError("Mirror Client Disconnect Error: " + disconnectError);
GenerateError(error);
}
void GenerateError(byte error)
{
int msgId = MessageBase.GetId<ErrorMessage>();
if (handlers.TryGetValue(msgId, out NetworkMessageDelegate msgDelegate))
{
ErrorMessage msg = new ErrorMessage
{
value = error
};
// write the message to a local buffer
NetworkWriter writer = new NetworkWriter();
msg.Serialize(writer);
NetworkMessage netMsg = new NetworkMessage
{
msgType = msgId,
reader = new NetworkReader(writer.ToArray()),
conn = connection
};
msgDelegate(netMsg);
}
}
*/
[Obsolete("Use NetworkTime.rtt instead")]
public float GetRTT()
{
return (float)NetworkTime.rtt;
}
internal void RegisterSystemHandlers(bool localClient)
{
// local client / regular client react to some messages differently.
// but we still need to add handlers for all of them to avoid
// 'message id not found' errors.
if (localClient)
{
RegisterHandler<ObjectDestroyMessage>(ClientScene.OnLocalClientObjectDestroy);
RegisterHandler<ObjectHideMessage>(ClientScene.OnLocalClientObjectHide);
RegisterHandler<OwnerMessage>((conn, msg) => {});
RegisterHandler<NetworkPongMessage>((conn, msg) => {});
RegisterHandler<SpawnPrefabMessage>(ClientScene.OnLocalClientSpawnPrefab);
RegisterHandler<SpawnSceneObjectMessage>(ClientScene.OnLocalClientSpawnSceneObject);
RegisterHandler<ObjectSpawnStartedMessage>((conn, msg) => {});
RegisterHandler<ObjectSpawnFinishedMessage>((conn, msg) => {});
RegisterHandler<UpdateVarsMessage>((conn, msg) => {});
}
else
{
RegisterHandler<ObjectDestroyMessage>(ClientScene.OnObjectDestroy);
RegisterHandler<ObjectHideMessage>(ClientScene.OnObjectHide);
RegisterHandler<OwnerMessage>(ClientScene.OnOwnerMessage);
RegisterHandler<NetworkPongMessage>(NetworkTime.OnClientPong);
RegisterHandler<SpawnPrefabMessage>(ClientScene.OnSpawnPrefab);
RegisterHandler<SpawnSceneObjectMessage>(ClientScene.OnSpawnSceneObject);
RegisterHandler<ObjectSpawnStartedMessage>(ClientScene.OnObjectSpawnStarted);
RegisterHandler<ObjectSpawnFinishedMessage>(ClientScene.OnObjectSpawnFinished);
RegisterHandler<UpdateVarsMessage>(ClientScene.OnUpdateVarsMessage);
}
RegisterHandler<ClientAuthorityMessage>(ClientScene.OnClientAuthority);
RegisterHandler<RpcMessage>(ClientScene.OnRPCMessage);
RegisterHandler<SyncEventMessage>(ClientScene.OnSyncEventMessage);
}
[Obsolete("Use RegisterHandler<T> instead")]
public void RegisterHandler(int msgType, NetworkMessageDelegate handler)
{
if (handlers.ContainsKey(msgType))
{
if (LogFilter.Debug) Debug.Log("NetworkClient.RegisterHandler replacing " + msgType);
}
handlers[msgType] = handler;
}
[Obsolete("Use RegisterHandler<T> instead")]
public void RegisterHandler(MsgType msgType, NetworkMessageDelegate handler)
{
RegisterHandler((int)msgType, handler);
}
public void RegisterHandler<T>(Action<NetworkConnection, T> handler) where T : MessageBase, new()
{
int msgType = MessagePacker.GetId<T>();
if (handlers.ContainsKey(msgType))
{
if (LogFilter.Debug) Debug.Log("NetworkClient.RegisterHandler replacing " + msgType);
}
handlers[msgType] = (networkMessage) =>
{
handler(networkMessage.conn, networkMessage.ReadMessage<T>());
};
}
[Obsolete("Use UnregisterHandler<T> instead")]
public void UnregisterHandler(int msgType)
{
handlers.Remove(msgType);
}
[Obsolete("Use UnregisterHandler<T> instead")]
public void UnregisterHandler(MsgType msgType)
{
UnregisterHandler((int)msgType);
}
public void UnregisterHandler<T>() where T : MessageBase
{
// use int to minimize collisions
int msgType = MessagePacker.GetId<T>();
handlers.Remove(msgType);
}
internal static void UpdateClient()
{
singleton?.Update();
}
public void Shutdown()
{
if (LogFilter.Debug) Debug.Log("Shutting down client.");
singleton = null;
active = false;
}
public static void ShutdownAll()
{
singleton?.Shutdown();
singleton = null;
active = false;
ClientScene.Shutdown();
}
}
}
| 35.362832 | 121 | 0.577578 | [
"MIT"
] | TehMightyPotato/Heliograph | Assets/Mirror/Runtime/NetworkClient.cs | 11,988 | C# |
using System;
namespace HelloWorldDI
{
public class HelloWorldService
{
public void Write(string name)
{
Console.WriteLine($"Hello {name}!");
}
}
}
| 15.230769 | 48 | 0.555556 | [
"MIT"
] | Just15/HelloWorldDI | src/HelloWorldDI/HelloWorldService.cs | 200 | 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 pinpoint-2016-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Pinpoint.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Pinpoint.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for EndpointUser Object
/// </summary>
public class EndpointUserUnmarshaller : IUnmarshaller<EndpointUser, XmlUnmarshallerContext>, IUnmarshaller<EndpointUser, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
EndpointUser IUnmarshaller<EndpointUser, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public EndpointUser Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
EndpointUser unmarshalledObject = new EndpointUser();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("UserAttributes", targetDepth))
{
var unmarshaller = new DictionaryUnmarshaller<string, List<string>, StringUnmarshaller, ListUnmarshaller<string, StringUnmarshaller>>(StringUnmarshaller.Instance, new ListUnmarshaller<string, StringUnmarshaller>(StringUnmarshaller.Instance));
unmarshalledObject.UserAttributes = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("UserId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.UserId = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static EndpointUserUnmarshaller _instance = new EndpointUserUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static EndpointUserUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.091837 | 263 | 0.622558 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Pinpoint/Generated/Model/Internal/MarshallTransformations/EndpointUserUnmarshaller.cs | 3,635 | C# |
using YamlDotNet.Core;
using YamlDotNet.Serialization;
namespace k8.Template.Engine.TemplatingConfigsModels
{
public class Parameter
{
public string name { get; set; }
public string displayName { get; set; }
public string description { get; set; }
public bool required { get; set; }
[YamlMember(ScalarStyle = ScalarStyle.SingleQuoted)]
public string value { get; set; }
}
}
| 27.25 | 60 | 0.655963 | [
"MIT"
] | ArtsiomKazlouski/k8.template.engine | src/k8.Template.Engine/TemplatingConfigsModels/Parameter.cs | 438 | C# |
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Cysharp.Threading.Tasks;
using DG.Tweening;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.UI;
namespace Pg.Scene.Game.Direction
{
internal class FailureDirection
: MonoBehaviour
{
static async UniTask DoBounceDown(Text text,
CancellationToken cancellationToken,
float delay,
float duration)
{
await UniTask.Delay(TimeSpan.FromSeconds(delay), cancellationToken: cancellationToken);
text.gameObject.SetActive(value: true);
await text.rectTransform.DOMoveY(endValue: 300f, duration: 0f)
.SetRelative()
.WithCancellation(cancellationToken);
await text.rectTransform.DOMoveY(endValue: -300f, duration)
.SetRelative()
.SetEase(Ease.OutBounce)
.WithCancellation(cancellationToken);
}
[SerializeField]
Text[]? FailureLetters;
[SerializeField]
Image? Background;
void Awake()
{
Assert.IsNotNull(FailureLetters, "FailureLetters != null");
Assert.IsTrue(
FailureLetters!.Any() && FailureLetters!.All(text => text != null),
"FailureLetters!.Any() && FailureLetters!.All(text => text != null)"
);
Assert.IsNotNull(Background, "Background != null");
foreach (var letter in FailureLetters!)
{
letter.gameObject.SetActive(value: false);
}
Background!.enabled = false;
Background!.DOFade(endValue: 0f, duration: 0f);
}
internal UniTask PlayFailure()
{
Background!.enabled = true;
Background!.DOFade(endValue: 0.5f, duration: 0.2f);
Text[] failureLetters = FailureLetters!;
var token = this.GetCancellationTokenOnDestroy();
var delays = new[] {0f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f};
var duration = 0.2f;
var tasks = new List<UniTask>();
for (var letterIndex = 0; letterIndex < failureLetters.Length; ++letterIndex)
{
var letter = failureLetters[letterIndex];
var delay = delays[letterIndex];
tasks.Add(DoBounceDown(letter, token, delay, duration));
}
return UniTask.WhenAll(tasks);
}
}
}
| 32.121951 | 99 | 0.558087 | [
"MIT"
] | kuniyoshi/Pg | Assets/Scripts/Pg/Scene/Game/Direction/FailureDirection.cs | 2,634 | C# |
using System;
using System.Runtime.InteropServices;
namespace RutokenPkcs11Interop.LowLevelAPI41.MechanismParams
{
/// <summary>
/// Structure that provides the parameters to the CKM_GOSTR3410_DERIVE mechanism
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
public struct CK_GOSTR3410_DERIVE_PARAMS
{
/// <summary>
/// Additional key diversification algorithm (CKD)
/// </summary>
public uint Kdf;
/// <summary>
/// Pointer to data with public key of a receiver
/// </summary>
public IntPtr PublicData;
/// <summary>
/// Length of data with public key of a receiver. Must be 64.
/// </summary>
public uint PublicDataLen;
/// <summary>
/// Pointer to a UKM data
/// </summary>
public IntPtr UKM;
/// <summary>
/// Length of UKM data in bytes. Must be 8.
/// </summary>
public uint UKMLen;
}
}
| 27.052632 | 84 | 0.588521 | [
"Apache-2.0"
] | pavelkhrulev/RutokenPkcs11Interop | src/RutokenPkcs11Interop/RutokenPkcs11Interop/LowLevelAPI41/MechanismParams/CK_GOSTR3410_DERIVE_PARAMS.cs | 1,030 | C# |
#region [Copyright (c) 2018 Cristian Alexandru Geambasu]
// Distributed under the terms of an MIT-style license:
//
// The MIT License
//
// Copyright (c) 2018 Cristian Alexandru Geambasu
//
// 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 [Copyright (c) 2018 Cristian Alexandru Geambasu]
using UnityEngine;
using UnityEditor;
using Luminosity.IO;
namespace LuminosityEditor.IO
{
[CustomEditor(typeof(GenericGamepadProfile))]
public class GenericGamepadProfileInspector : Editor
{
private SerializedProperty m_name;
private SerializedProperty m_comment;
private SerializedProperty m_dpadType;
private SerializedProperty m_triggerType;
private SerializedProperty m_leftStickButton;
private SerializedProperty m_rightStickButton;
private SerializedProperty m_leftBumperButton;
private SerializedProperty m_rightBumperButton;
private SerializedProperty m_leftTriggerButton;
private SerializedProperty m_rightTriggerButton;
private SerializedProperty m_dpadUpButton;
private SerializedProperty m_dpadDownButton;
private SerializedProperty m_dpadLeftButton;
private SerializedProperty m_dpadRightButton;
private SerializedProperty m_backButton;
private SerializedProperty m_startButton;
private SerializedProperty m_actionTopButton;
private SerializedProperty m_actionBottomButton;
private SerializedProperty m_actionLeftButton;
private SerializedProperty m_actionRightButton;
private SerializedProperty m_leftStickXAxis;
private SerializedProperty m_leftStickYAxis;
private SerializedProperty m_rightStickXAxis;
private SerializedProperty m_rightStickYAxis;
private SerializedProperty m_dpadXAxis;
private SerializedProperty m_dpadYAxis;
private SerializedProperty m_leftTriggerAxis;
private SerializedProperty m_rightTriggerAxis;
private string[] m_buttonNames;
private string[] m_axisNames;
private void OnEnable()
{
m_name = serializedObject.FindProperty("m_name");
m_comment = serializedObject.FindProperty("m_comment");
m_dpadType = serializedObject.FindProperty("m_dpadType");
m_triggerType = serializedObject.FindProperty("m_triggerType");
m_leftStickButton = serializedObject.FindProperty("m_leftStickButton");
m_rightStickButton = serializedObject.FindProperty("m_rightStickButton");
m_leftBumperButton = serializedObject.FindProperty("m_leftBumperButton");
m_rightBumperButton = serializedObject.FindProperty("m_rightBumperButton");
m_leftTriggerButton = serializedObject.FindProperty("m_leftTriggerButton");
m_rightTriggerButton = serializedObject.FindProperty("m_rightTriggerButton");
m_dpadUpButton = serializedObject.FindProperty("m_dpadUpButton");
m_dpadDownButton = serializedObject.FindProperty("m_dpadDownButton");
m_dpadLeftButton = serializedObject.FindProperty("m_dpadLeftButton");
m_dpadRightButton = serializedObject.FindProperty("m_dpadRightButton");
m_backButton = serializedObject.FindProperty("m_backButton");
m_startButton = serializedObject.FindProperty("m_startButton");
m_actionTopButton = serializedObject.FindProperty("m_actionTopButton");
m_actionBottomButton = serializedObject.FindProperty("m_actionBottomButton");
m_actionLeftButton = serializedObject.FindProperty("m_actionLeftButton");
m_actionRightButton = serializedObject.FindProperty("m_actionRightButton");
m_leftStickXAxis = serializedObject.FindProperty("m_leftStickXAxis");
m_leftStickYAxis = serializedObject.FindProperty("m_leftStickYAxis");
m_rightStickXAxis = serializedObject.FindProperty("m_rightStickXAxis");
m_rightStickYAxis = serializedObject.FindProperty("m_rightStickYAxis");
m_dpadXAxis = serializedObject.FindProperty("m_dpadXAxis");
m_dpadYAxis = serializedObject.FindProperty("m_dpadYAxis");
m_leftTriggerAxis = serializedObject.FindProperty("m_leftTriggerAxis");
m_rightTriggerAxis = serializedObject.FindProperty("m_rightTriggerAxis");
m_buttonNames = EditorToolbox.GenerateJoystickButtonNames();
m_axisNames = EditorToolbox.GenerateJoystickAxisNames();
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.Space();
DrawHeader("Description");
EditorGUILayout.PropertyField(m_name);
EditorGUILayout.PropertyField(m_comment);
// SETTINGS
DrawHeader("Settings");
EditorGUILayout.PropertyField(m_dpadType);
EditorGUILayout.PropertyField(m_triggerType);
// BUTTONS
DrawHeader("Buttons");
DrawButtonField(m_leftStickButton);
DrawButtonField(m_rightStickButton);
DrawButtonField(m_leftBumperButton);
DrawButtonField(m_rightBumperButton);
if(m_triggerType.enumValueIndex == (int)GamepadTriggerType.Button)
{
DrawButtonField(m_leftTriggerButton);
DrawButtonField(m_rightTriggerButton);
}
if(m_dpadType.enumValueIndex == (int)GamepadDPadType.Button)
{
DrawButtonField(m_dpadUpButton);
DrawButtonField(m_dpadDownButton);
DrawButtonField(m_dpadLeftButton);
DrawButtonField(m_dpadRightButton);
}
DrawButtonField(m_backButton);
DrawButtonField(m_startButton);
DrawButtonField(m_actionTopButton);
DrawButtonField(m_actionBottomButton);
DrawButtonField(m_actionLeftButton);
DrawButtonField(m_actionRightButton);
// AXES
DrawHeader("Axes");
DrawAxisField(m_leftStickXAxis);
DrawAxisField(m_leftStickYAxis);
DrawAxisField(m_rightStickXAxis);
DrawAxisField(m_rightStickYAxis);
if(m_triggerType.enumValueIndex == (int)GamepadTriggerType.Axis)
{
DrawAxisField(m_leftTriggerAxis);
DrawAxisField(m_rightTriggerAxis);
}
if(m_dpadType.enumValueIndex == (int)GamepadDPadType.Axis)
{
DrawAxisField(m_dpadXAxis);
DrawAxisField(m_dpadYAxis);
}
serializedObject.ApplyModifiedProperties();
}
private void DrawHeader(string label)
{
EditorGUILayout.Space();
EditorGUILayout.LabelField(label, EditorStyles.boldLabel);
}
private void DrawButtonField(SerializedProperty button)
{
button.intValue = EditorGUILayout.Popup(button.displayName, button.intValue, m_buttonNames);
}
private void DrawAxisField(SerializedProperty axis)
{
axis.intValue = EditorGUILayout.Popup(axis.displayName, axis.intValue, m_axisNames);
}
}
} | 46.105556 | 104 | 0.696469 | [
"MIT-0",
"MIT"
] | Chillu1/InputManager | Assets/InputManager/Source/Editor/Scripts/GenericGamepadProfileInspector.cs | 8,301 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Klinkby.RestClient
{
public class RestClient : IDisposable
{
private const string JsonMimeType = "application/json";
private readonly bool _httpClientOwned;
private readonly HttpClient _httpClient;
private readonly JsonSerializer _serializer;
private bool _disposedValue = false; // To detect redundant calls
public RestClient(JsonSerializer serializer = null, string mime = null, HttpClient httpClient = null)
{
_serializer = serializer ?? JsonSerializer.CreateDefault();
_httpClientOwned = null == httpClient;
_httpClient = httpClient ?? CreateDefaultClient(mime ?? JsonMimeType);
}
public async Task<TResult> GetAsync<TResult>(Uri endPoint, IDictionary<string, string> urlParams, CancellationToken ct)
{
if (null == endPoint) throw new ArgumentNullException(nameof(endPoint));
endPoint = AddParams(endPoint, urlParams);
Debug.Write($"GET {endPoint}");
using (var res = await _httpClient.GetAsync(endPoint, ct))
{
return await ParseResultAsync<TResult>(res);
}
}
public async Task PostAsync(Uri endPoint, object body, IDictionary<string, string> urlParams, CancellationToken ct)
{
if (null == endPoint) throw new ArgumentNullException(nameof(endPoint));
endPoint = AddParams(endPoint, urlParams);
Debug.Write($"POST {endPoint}");
await WithStreamContentAsync(body, async sc =>
{
using (var res = await _httpClient.PostAsync(endPoint, sc, ct))
{
EnsureSuccessStatusCode(res);
}
});
}
public async Task<TResult> PostAsync<TResult>(Uri endPoint, object body, IDictionary<string, string> urlParams, CancellationToken ct)
{
if (null == endPoint) throw new ArgumentNullException(nameof(endPoint));
endPoint = AddParams(endPoint, urlParams);
Debug.Write($"POST {endPoint}");
TResult result = default(TResult);
await WithStreamContentAsync(body, async sc =>
{
using (var res = await _httpClient.PostAsync(endPoint, sc, ct))
{
result = await ParseResultAsync<TResult>(res);
}
});
return result;
}
public async Task PutAsync(Uri endPoint, object body, IDictionary<string, string> urlParams, CancellationToken ct)
{
if (null == endPoint) throw new ArgumentNullException(nameof(endPoint));
endPoint = AddParams(endPoint, urlParams);
Debug.Write($"PUT {endPoint}");
await WithStreamContentAsync(body, async sc =>
{
using (var res = await _httpClient.PutAsync(endPoint, sc, ct))
{
EnsureSuccessStatusCode(res);
}
});
}
public async Task<TResult> PutAsync<TResult>(Uri endPoint, object body, IDictionary<string, string> urlParams, CancellationToken ct)
{
if (null == endPoint) throw new ArgumentNullException(nameof(endPoint));
endPoint = AddParams(endPoint, urlParams);
Debug.Write($"PUT {endPoint}");
TResult result = default(TResult);
await WithStreamContentAsync(body, async sc =>
{
using (var res = await _httpClient.PutAsync(endPoint, sc, ct))
{
result = await ParseResultAsync<TResult>(res);
}
});
return result;
}
public async Task DeleteAsync(Uri endPoint, IDictionary<string, string> urlParams, CancellationToken ct)
{
if (null == endPoint) throw new ArgumentNullException(nameof(endPoint));
endPoint = AddParams(endPoint, urlParams);
Debug.Write($"DELETE {endPoint}");
using (var res = await _httpClient.DeleteAsync(endPoint, ct))
{
EnsureSuccessStatusCode(res);
}
}
private async Task WithStreamContentAsync(object body, Func<StreamContent, Task> withStreamContent)
{
using (var ms = new MemoryStream())
{
var jw = new JsonTextWriter(new StreamWriter(ms));
_serializer.Serialize(jw, body);
jw.Flush();
Debug.Write($" {ms.Length} bytes");
ms.Seek(0, SeekOrigin.Begin);
using (var sc = new StreamContent(ms))
{
sc.Headers.ContentType = new MediaTypeHeaderValue(JsonMimeType);
await withStreamContent(sc);
}
}
}
private static void EnsureSuccessStatusCode(HttpResponseMessage res)
{
Debug.WriteLine($" ({res.StatusCode})");
res.EnsureSuccessStatusCode();
}
private static HttpClient CreateDefaultClient(string mime)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(mime));
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("KlinkbyRestClient", "1.0"));
return client;
}
private async Task<TResult> ParseResultAsync<TResult>(HttpResponseMessage res)
{
EnsureSuccessStatusCode(res);
using (var stream = await res.Content.ReadAsStreamAsync())
{
Debug.WriteLine($" Parse {stream.Length} bytes");
var jr = new JsonTextReader(new StreamReader(stream));
return _serializer.Deserialize<TResult>(jr);
}
}
private static Uri AddParams(Uri endPoint, IDictionary<string, string> urlParams)
{
if (null != urlParams)
{
var paramsJoined = string.Join(
"&",
urlParams
.Where(x => !string.IsNullOrEmpty(x.Key))
.Select(x =>
Uri.EscapeDataString(x.Key)
+ "="
+ Uri.EscapeDataString(x.Value ?? "")
).ToArray()
);
endPoint = new Uri(
endPoint.AbsoluteUri
+ (string.IsNullOrEmpty(endPoint.Query) ? "?" : "&")
+ paramsJoined
);
}
return endPoint;
}
#region IDisposable Support
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing && _httpClientOwned)
{
_httpClient.Dispose();
}
_disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
#endregion
}
}
| 38.454545 | 142 | 0.53927 | [
"MIT"
] | klinkby/klinkby.restclient | RestClient.cs | 7,616 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace Modalmais.Transacoes.API
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 24.909091 | 70 | 0.565693 | [
"Apache-2.0"
] | LucasTMP/Microservices-Bank | Modalmais/src/Modalmais.Transacoes.API/Program.cs | 548 | C# |
namespace Knapcode.PoGoNotifications.Models
{
public class NotificationOptions
{
public string GoogleMapsApiKey { get; set; }
public string PokemonIconUrlFormat { get; set; }
public GroupMeOptions GroupMeOptions { get; set; }
public CheckRepublicOptions CheckRepublicOptions { get; set; }
public NotificationAreaOptions[] NotificationAreas { get; set; }
public bool UseNotificationImage { get; set; }
public bool UseNotificationLocation { get; set; }
}
}
| 37.428571 | 72 | 0.688931 | [
"MIT"
] | joelverhagen/PoGoNotifications | src/Knapcode.PoGoNotifications/Models/Options/NotificationOptions.cs | 526 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;
namespace WebApplication22partials.App_Start
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.js", "~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/Site.css"));
}
}
} | 26.185185 | 124 | 0.618105 | [
"MIT"
] | medhajoshi27/AllProjectmedha | WebApplication22partials/WebApplication22partials/App_Start/BundleConfig.cs | 709 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading.Tasks;
namespace Cave
{
/// <summary>Gets access to the current platform type.</summary>
[ExcludeFromCodeCoverage]
public static class Platform
{
/// <summary>Gets the <see cref="PlatformType" /> of the current platform.</summary>
public static PlatformType Type => GetCached(nameof(Type), GetPlatformType);
/// <summary>Gets the system version string.</summary>
/// <value>The system version string.</value>
public static string SystemVersionString => GetCached(nameof(SystemVersionString), GetSystemVersionString);
/// <summary>Gets a value indicating whether we run under mono or not.</summary>
public static bool IsMono => GetCached(nameof(IsMono), GetIsMono);
/// <summary>Gets a value indicating whether we run at android or not.</summary>
public static bool IsAndroid => GetCached(nameof(IsAndroid), GetIsAndroid);
/// <summary>Gets a value indicating whether we run at a microsoft os or not.</summary>
public static bool IsMicrosoft => GetCached(nameof(IsMicrosoft), GetIsMicrosoft);
static readonly Dictionary<string, object> cachedValues = new();
static T GetCached<T>(string name, Func<T> getter)
{
if (!cachedValues.TryGetValue(name, out var value))
{
value = getter();
cachedValues[name] = value;
}
return (T)value;
}
static PlatformType GetPlatformType()
{
switch ((int)Environment.OSVersion.Platform)
{
case 0: /*Win32S*/
case 1: /*Win32NT*/
case 2: /*Win32Windows*/
return PlatformType.Windows;
case 3: /*Windows CE / Compact Framework*/
return PlatformType.CompactFramework;
case 4: /*Unix, mono returns this on all platforms except windows*/
if (AppDom.FindAssembly("Mono.Android", false) != null)
{
return PlatformType.Android;
}
try
{
if (File.Exists("/usr/lib/libc.dylib"))
{
return PlatformType.MacOS;
}
}
catch (Exception ex)
{
Trace.TraceInformation("Exception on File.Exists(/usr/lib/libc.dylib).");
Trace.TraceInformation(ex.ToString());
/*Exception on Android on this one... why ?*/
}
var osType = SystemVersionString.ToUpperInvariant();
if (osType.StartsWith("LINUX", StringComparison.OrdinalIgnoreCase))
{
return PlatformType.Linux;
}
if (osType.StartsWith("DARWIN", StringComparison.OrdinalIgnoreCase))
{
return PlatformType.MacOS;
}
if (osType.StartsWith("SOLARIS", StringComparison.OrdinalIgnoreCase))
{
return PlatformType.Solaris;
}
if (osType.StartsWith("BSD", StringComparison.OrdinalIgnoreCase))
{
return PlatformType.BSD;
}
if (osType.StartsWith("MSYS", StringComparison.OrdinalIgnoreCase))
{
return PlatformType.Windows;
}
if (osType.StartsWith("CYGWIN", StringComparison.OrdinalIgnoreCase))
{
return PlatformType.Windows;
}
return PlatformType.UnknownUnix;
case 5: /*Xbox*/
return PlatformType.Xbox;
case 6: /*MacOSX*/
return PlatformType.MacOS;
case 128:
return PlatformType.UnknownUnix;
default:
return PlatformType.Unknown;
}
}
static string GetSystemVersionString()
{
var systemVersionString = Environment.OSVersion.VersionString;
if (IsMicrosoft)
{
// all done
}
else if (IsAndroid)
{
// TODO Android.OS.Build
systemVersionString = "Android " + systemVersionString;
}
else if (File.Exists("/proc/version"))
{
systemVersionString = File.ReadAllText("/proc/version");
}
else
{
var versionString = string.Empty;
var task = Task.Factory.StartNew(() =>
{
var process = Process.Start(new ProcessStartInfo("uname", "-a")
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true
});
versionString = process.StandardOutput.ReadToEnd();
});
if (task.Wait(1000))
{
systemVersionString = versionString;
}
}
return systemVersionString.BeforeFirst('\n');
}
[SuppressMessage("Style", "IDE0066:Keep switch")]
static bool GetIsMicrosoft()
{
switch ((int)Environment.OSVersion.Platform)
{
case 0: /*Win32S*/
case 1: /*Win32NT*/
case 2: /*Win32Windows*/
case 3: /*Windows CE / Compact Framework*/
case 5: /*Xbox*/
return true;
default:
case 4: /*Unix*/
case 6: /*MacOSX*/
case 128:
return false;
}
}
#if alternative
static PlatformType GetPlatformType()
{
if (AppDom.FindAssembly("Mono.Android", false) != null)
{
return PlatformType.Android;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return PlatformType.Windows;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return PlatformType.MacOS;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return PlatformType.Linux;
}
try
{
if (File.Exists("/usr/lib/libc.dylib"))
{
return PlatformType.MacOS;
}
}
catch
{
/*Exception on Android on this one... why ?*/
}
string osType = RuntimeInformation.OSDescription.ToLower();
if (osType.StartsWith("linux"))
{
return PlatformType.Linux;
}
if (osType.StartsWith("darwin"))
{
return PlatformType.MacOS;
}
if (osType.StartsWith("solaris"))
{
return PlatformType.Solaris;
}
if (osType.StartsWith("bsd"))
{
return PlatformType.BSD;
}
if (osType.StartsWith("msys"))
{
return PlatformType.Windows;
}
if (osType.StartsWith("cygwin"))
{
return PlatformType.Windows;
}
return PlatformType.UnknownUnix;
}
static string GetSystemVersionString()
{
var systemVersionString = RuntimeInformation.OSDescription;
if (IsMicrosoft)
{
// all done
}
else if (IsAndroid)
{
// TODO Android.OS.Build
systemVersionString = "Android " + systemVersionString;
}
else
{
Process process = Process.Start(new ProcessStartInfo("uname", "-a") { CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput =
true, });
var task = Task.Factory.StartNew(() => { systemVersionString = process.StandardOutput.ReadToEnd(); });
if (!process.WaitForExit(10000))
{
try
{
process.Kill();
}
catch
{
}
}
task.Wait();
int i = systemVersionString?.IndexOf('\n') ?? -1;
if (i > -1)
{
systemVersionString = systemVersionString.Substring(0, i);
}
}
return systemVersionString;
}
static bool GetIsMicrosoft()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return true;
}
return false;
}
#endif
static bool GetIsMono() => AppDom.FindType("Mono.Runtime", null, AppDom.LoadFlags.NoException) != null;
static bool GetIsAndroid() => AppDom.FindType("Android.Runtime", null, AppDom.LoadFlags.NoException) != null;
}
}
| 34.207018 | 158 | 0.473177 | [
"MIT"
] | CaveSystems/cave-extensions | Cave.Extensions/Platform.cs | 9,749 | C# |
using System;
namespace Facade
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| 13.384615 | 46 | 0.505747 | [
"MIT"
] | vivekmishra-sft/DesignPatterns | Structural/Facade/Program.cs | 176 | 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 chime-sdk-media-pipelines-2021-07-15.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.ChimeSDKMediaPipelines.Model
{
/// <summary>
/// A media capture pipeline object consisting of an ID, source type, source ARN, a sink
/// type, a sink ARN, and a configuration object.
/// </summary>
public partial class MediaCapturePipeline
{
private ChimeSdkMeetingConfiguration _chimeSdkMeetingConfiguration;
private DateTime? _createdTimestamp;
private string _mediaPipelineArn;
private string _mediaPipelineId;
private string _sinkArn;
private MediaPipelineSinkType _sinkType;
private string _sourceArn;
private MediaPipelineSourceType _sourceType;
private MediaPipelineStatus _status;
private DateTime? _updatedTimestamp;
/// <summary>
/// Gets and sets the property ChimeSdkMeetingConfiguration.
/// <para>
/// The configuration for a specified media capture pipeline. <code>SourceType</code>
/// must be <code>ChimeSdkMeeting</code>.
/// </para>
/// </summary>
public ChimeSdkMeetingConfiguration ChimeSdkMeetingConfiguration
{
get { return this._chimeSdkMeetingConfiguration; }
set { this._chimeSdkMeetingConfiguration = value; }
}
// Check to see if ChimeSdkMeetingConfiguration property is set
internal bool IsSetChimeSdkMeetingConfiguration()
{
return this._chimeSdkMeetingConfiguration != null;
}
/// <summary>
/// Gets and sets the property CreatedTimestamp.
/// <para>
/// The time at which the capture pipeline was created, in ISO 8601 format.
/// </para>
/// </summary>
public DateTime CreatedTimestamp
{
get { return this._createdTimestamp.GetValueOrDefault(); }
set { this._createdTimestamp = value; }
}
// Check to see if CreatedTimestamp property is set
internal bool IsSetCreatedTimestamp()
{
return this._createdTimestamp.HasValue;
}
/// <summary>
/// Gets and sets the property MediaPipelineArn.
/// <para>
/// The ARN of a media capture pipeline.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1011)]
public string MediaPipelineArn
{
get { return this._mediaPipelineArn; }
set { this._mediaPipelineArn = value; }
}
// Check to see if MediaPipelineArn property is set
internal bool IsSetMediaPipelineArn()
{
return this._mediaPipelineArn != null;
}
/// <summary>
/// Gets and sets the property MediaPipelineId.
/// <para>
/// The ID of a media capture pipeline.
/// </para>
/// </summary>
[AWSProperty(Min=36, Max=36)]
public string MediaPipelineId
{
get { return this._mediaPipelineId; }
set { this._mediaPipelineId = value; }
}
// Check to see if MediaPipelineId property is set
internal bool IsSetMediaPipelineId()
{
return this._mediaPipelineId != null;
}
/// <summary>
/// Gets and sets the property SinkArn.
/// <para>
/// ARN of the destination to which the media artifacts are saved.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1024)]
public string SinkArn
{
get { return this._sinkArn; }
set { this._sinkArn = value; }
}
// Check to see if SinkArn property is set
internal bool IsSetSinkArn()
{
return this._sinkArn != null;
}
/// <summary>
/// Gets and sets the property SinkType.
/// <para>
/// Destination type to which the media artifacts are saved. You must use an S3 Bucket.
/// </para>
/// </summary>
public MediaPipelineSinkType SinkType
{
get { return this._sinkType; }
set { this._sinkType = value; }
}
// Check to see if SinkType property is set
internal bool IsSetSinkType()
{
return this._sinkType != null;
}
/// <summary>
/// Gets and sets the property SourceArn.
/// <para>
/// ARN of the source from which the media artifacts are saved.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1024)]
public string SourceArn
{
get { return this._sourceArn; }
set { this._sourceArn = value; }
}
// Check to see if SourceArn property is set
internal bool IsSetSourceArn()
{
return this._sourceArn != null;
}
/// <summary>
/// Gets and sets the property SourceType.
/// <para>
/// Source type from which media artifacts are saved. You must use <code>ChimeMeeting</code>.
/// </para>
/// </summary>
public MediaPipelineSourceType SourceType
{
get { return this._sourceType; }
set { this._sourceType = value; }
}
// Check to see if SourceType property is set
internal bool IsSetSourceType()
{
return this._sourceType != null;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The status of the media capture pipeline.
/// </para>
/// </summary>
public MediaPipelineStatus Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
/// <summary>
/// Gets and sets the property UpdatedTimestamp.
/// <para>
/// The time at which the capture pipeline was updated, in ISO 8601 format.
/// </para>
/// </summary>
public DateTime UpdatedTimestamp
{
get { return this._updatedTimestamp.GetValueOrDefault(); }
set { this._updatedTimestamp = value; }
}
// Check to see if UpdatedTimestamp property is set
internal bool IsSetUpdatedTimestamp()
{
return this._updatedTimestamp.HasValue;
}
}
} | 31.452991 | 123 | 0.579348 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/ChimeSDKMediaPipelines/Generated/Model/MediaCapturePipeline.cs | 7,360 | C# |
using KenticoInspector.Core.Constants;
using KenticoInspector.Reports.RobotsTxtConfigurationSummary;
using KenticoInspector.Reports.RobotsTxtConfigurationSummary.Models;
using KenticoInspector.Reports.Tests.Helpers;
using Moq;
using Moq.Protected;
using NUnit.Framework;
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace KenticoInspector.Reports.Tests
{
[TestFixture(10)]
[TestFixture(11)]
[TestFixture(12)]
public class RobotsTxtConfigurationSummaryTest : AbstractReportTest<Report, Terms>
{
private Report _mockReport;
public RobotsTxtConfigurationSummaryTest(int majorVersion) : base(majorVersion)
{
}
[Test]
public void Should_ReturnGoodStatus_WhenRobotsTxtFound()
{
// Arrange
_mockReport = ConfigureReportAndHandlerWithHttpClientReturning(HttpStatusCode.OK, out Mock<HttpMessageHandler> mockHttpMessageHandler);
var mockInstance = _mockInstanceService.Object.CurrentInstance;
// Act
var results = _mockReport.GetResults();
// Assert
Assert.That(results.Status == ReportResultsStatus.Good);
var baseUri = new Uri(mockInstance.Url);
var expectedUri = new Uri(baseUri, Constants.RobotsTxtRelativePath);
AssertUrlCalled(mockHttpMessageHandler, expectedUri);
}
private static void AssertUrlCalled(Mock<HttpMessageHandler> handlerMock, Uri expectedUri)
{
handlerMock.Protected().Verify(
"SendAsync",
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(req =>
req.Method == HttpMethod.Get
&& req.RequestUri == expectedUri
),
ItExpr.IsAny<CancellationToken>()
);
}
[Test]
public void Should_ReturnGoodStatus_WhenSiteIsInSubDirectoryAndRobotsTxtFound()
{
// Arrange
_mockReport = ConfigureReportAndHandlerWithHttpClientReturning(HttpStatusCode.OK, out Mock<HttpMessageHandler> mockHttpMessageHandler);
var mockInstance = _mockInstanceService.Object.CurrentInstance;
var baseUrl = mockInstance.Url;
mockInstance.Url += "/subdirectory";
// Act
var results = _mockReport.GetResults();
// Assert
Assert.That(results.Status == ReportResultsStatus.Good);
var expectedUri = new Uri($"{baseUrl}/{Constants.RobotsTxtRelativePath}");
AssertUrlCalled(mockHttpMessageHandler, expectedUri);
}
[Test]
public void Should_ReturnWarningStatus_WhenRobotsTxtNotFound()
{
// Arrange
_mockReport = ConfigureReportAndHandlerWithHttpClientReturning(HttpStatusCode.NotFound, out Mock<HttpMessageHandler> mockHttpMessageHandler);
// Act
var results = _mockReport.GetResults();
// Assert
Assert.That(results.Status == ReportResultsStatus.Warning);
}
private Report ConfigureReportAndHandlerWithHttpClientReturning(HttpStatusCode httpStatusCode, out Mock<HttpMessageHandler> mockHttpMessageHandler)
{
mockHttpMessageHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mockHttpMessageHandler
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage() { StatusCode = httpStatusCode })
.Verifiable();
var httpClient = new HttpClient(mockHttpMessageHandler.Object);
var report = new Report(_mockDatabaseService.Object, _mockInstanceService.Object, _mockReportMetadataService.Object, httpClient);
MockReportMetadataServiceHelper.SetupReportMetadataService<Terms>(_mockReportMetadataService, report);
return report;
}
}
} | 35.709402 | 155 | 0.651269 | [
"MIT"
] | David-Moreira/KInspector | KenticoInspector.Reports.Tests/RobotsTxtConfigurationSummaryTest.cs | 4,180 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Checkout.BasketService
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
| 24.72 | 76 | 0.697411 | [
"MIT"
] | kashifsoofi/basket-service | Checkout.BasketService/Program.cs | 620 | C# |
using System.Collections;
using TMPro;
using UnityEngine;
namespace TextMesh_Pro.Scripts
{
public class Benchmark01 : MonoBehaviour
{
public int benchmarkType = 0;
public TMP_FontAsset tmProFont;
public Font textMeshFont;
private TextMeshPro mTextMeshPro;
private TextContainer mTextContainer;
private TextMesh mTextMesh;
private const string Label01 = "The <#0050FF>count is: </color>{0}";
private const string Label02 = "The <color=#0050FF>count is: </color>";
//private string m_string;
//private int m_frame;
private Material mMaterial01;
private Material mMaterial02;
IEnumerator Start()
{
if (benchmarkType == 0) // TextMesh Pro Component
{
mTextMeshPro = gameObject.AddComponent<TextMeshPro>();
mTextMeshPro.autoSizeTextContainer = true;
//m_textMeshPro.anchorDampening = true;
if (tmProFont != null)
mTextMeshPro.font = tmProFont;
//m_textMeshPro.font = Resources.Load("Fonts & Materials/Anton SDF", typeof(TextMeshProFont)) as TextMeshProFont; // Make sure the Anton SDF exists before calling this...
//m_textMeshPro.fontSharedMaterial = Resources.Load("Fonts & Materials/Anton SDF", typeof(Material)) as Material; // Same as above make sure this material exists.
mTextMeshPro.fontSize = 48;
mTextMeshPro.alignment = TextAlignmentOptions.Center;
//m_textMeshPro.anchor = AnchorPositions.Center;
mTextMeshPro.extraPadding = true;
//m_textMeshPro.outlineWidth = 0.25f;
//m_textMeshPro.fontSharedMaterial.SetFloat("_OutlineWidth", 0.2f);
//m_textMeshPro.fontSharedMaterial.EnableKeyword("UNDERLAY_ON");
//m_textMeshPro.lineJustification = LineJustificationTypes.Center;
mTextMeshPro.enableWordWrapping = false;
//m_textMeshPro.lineLength = 60;
//m_textMeshPro.characterSpacing = 0.2f;
//m_textMeshPro.fontColor = new Color32(255, 255, 255, 255);
mMaterial01 = mTextMeshPro.font.material;
mMaterial02 = Resources.Load<Material>("Fonts & Materials/LiberationSans SDF - Drop Shadow"); // Make sure the LiberationSans SDF exists before calling this...
}
else if (benchmarkType == 1) // TextMesh
{
mTextMesh = gameObject.AddComponent<TextMesh>();
if (textMeshFont != null)
{
mTextMesh.font = textMeshFont;
mTextMesh.GetComponent<Renderer>().sharedMaterial = mTextMesh.font.material;
}
else
{
mTextMesh.font = Resources.Load("Fonts/ARIAL", typeof(Font)) as Font;
mTextMesh.GetComponent<Renderer>().sharedMaterial = mTextMesh.font.material;
}
mTextMesh.fontSize = 48;
mTextMesh.anchor = TextAnchor.MiddleCenter;
//m_textMesh.color = new Color32(255, 255, 0, 255);
}
for (int i = 0; i <= 1000000; i++)
{
if (benchmarkType == 0)
{
mTextMeshPro.SetText(Label01, i % 1000);
if (i % 1000 == 999)
mTextMeshPro.fontSharedMaterial = mTextMeshPro.fontSharedMaterial == mMaterial01 ? mTextMeshPro.fontSharedMaterial = mMaterial02 : mTextMeshPro.fontSharedMaterial = mMaterial01;
}
else if (benchmarkType == 1)
mTextMesh.text = Label02 + (i % 1000).ToString();
yield return null;
}
yield return null;
}
/*
void Update()
{
if (BenchmarkType == 0)
{
m_textMeshPro.text = (m_frame % 1000).ToString();
}
else if (BenchmarkType == 1)
{
m_textMesh.text = (m_frame % 1000).ToString();
}
m_frame += 1;
}
*/
}
}
| 33.325581 | 201 | 0.551756 | [
"MIT"
] | MarcoNaik/Emoji-FPS-Roguelike | Assets/TextMesh Pro/Examples & Extras/Scripts/Benchmark01.cs | 4,299 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NnCase.Converter.K210.Model.Layers;
using NnCase.Converter.Model;
using NnCase.Converter.Model.Layers;
using NnCase.Converter.Transforms;
namespace NnCase.Converter.K210.Transforms
{
public class K210SeparableConv2dTransform : Transform
{
protected override bool OnTryMatch(Layer layer, TransformContext context)
{
try
{
if (layer is SpaceToBatchNd || layer is Pad)
{
context.MatchedLayers.Add(layer);
context.Inputs.Add(layer.InputConnectors[0]);
foreach (var nextLayer in layer.OutputConnectors[0].Connections.Select(o => o.To.Owner))
{
if (nextLayer is DepthwiseConv2d dwConv2d)
{
if (dwConv2d.KernelWidth != 3 || dwConv2d.KernelHeight != 3 || dwConv2d.StrideHeight != 2 || dwConv2d.StrideWidth != 2 ||
dwConv2d.Padding != Padding.Valid)
return false;
context.MatchedLayers.Add(nextLayer);
context.Inputs.Add(dwConv2d.Input);
if (dwConv2d.Output.Connections.Count == 1)
{
var middleLayer = dwConv2d.Output.Connections[0].To.Owner;
while (true)
{
if (middleLayer is Conv2d conv2d)
{
if (conv2d.KernelWidth != 1 || conv2d.KernelHeight != 1 || conv2d.StrideHeight != 1 || conv2d.StrideWidth != 1)
return false;
context.MatchedLayers.Add(conv2d);
context.Outputs.Add(conv2d.Output);
return true;
}
else
{
if (middleLayer.OutputConnectors.Count == 1 && middleLayer.OutputConnectors[0].Connections.Count == 1)
{
switch (middleLayer)
{
case Quantize _:
case Dequantize _:
case LeakyRelu _:
context.MatchedLayers.Add(middleLayer);
middleLayer = middleLayer.OutputConnectors[0].Connections[0].To.Owner;
break;
default:
return false;
}
}
else
{
return false;
}
}
}
}
}
else
{
continue;
}
return false;
}
}
return false;
}
catch
{
return false;
}
}
public override void Process(TransformContext context)
{
var space = context.MatchedLayers[0];
var dwConv2d = (DepthwiseConv2d)context.MatchedLayers[1];
var conv2d = (Conv2d)context.MatchedLayers.Last();
var input = space.InputConnectors[0].Connection.From;
var output = conv2d.Output;
space.InputConnectors[0].ClearConnection();
var newDwConv2d = new DepthwiseConv2d(input.Dimensions, dwConv2d.Weights, dwConv2d.Bias, Padding.Same, 1, 1, dwConv2d.FusedActivationFunction);
var quantize = new Quantize(newDwConv2d.Output.Dimensions);
var upload = new K210Upload(quantize.Output.Dimensions);
var newConv2d = new K210Conv2d(upload.Output.Dimensions, K210Conv2dType.Conv2d, conv2d.Weights, conv2d.Bias, K210PoolType.LeftTop, conv2d.FusedActivationFunction, null);
var dequantize = new Dequantize(newConv2d.Output.Dimensions);
newDwConv2d.Input.SetConnection(input);
upload.Input.SetConnection(quantize.Output);
newConv2d.Input.SetConnection(upload.Output);
dequantize.Input.SetConnection(newConv2d.Output);
var oldOuts = output.Connections.Select(o => o.To).ToList();
if (context.MatchedLayers.Count == 3)
{
quantize.Input.SetConnection(newDwConv2d.Output);
}
else
{
var newOutput = newDwConv2d.Output;
foreach (var middleLayer in context.MatchedLayers.Skip(2).Take(context.MatchedLayers.Count - 3))
{
Layer newLayer;
switch (middleLayer)
{
case Quantize _:
newLayer = new Quantize(newOutput.Dimensions);
break;
case Dequantize _:
newLayer = new Dequantize(newOutput.Dimensions);
break;
case LeakyRelu l:
newLayer = new LeakyRelu(newOutput.Dimensions, l.Slope);
break;
default:
throw new NotImplementedException();
}
newLayer.InputConnectors[0].SetConnection(newOutput);
newOutput = newLayer.OutputConnectors[0];
}
quantize.Input.SetConnection(newOutput);
}
foreach (var oldOut in oldOuts)
oldOut.SetConnection(dequantize.Output);
}
}
}
| 43.543624 | 181 | 0.430795 | [
"Apache-2.0"
] | svija/nncase | src/NnCase.Converter.K210/Transforms/K210SeparableConv2dTransform.cs | 6,490 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AlgoraArt.WebApp.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
namespace AlgoraArt.WebApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class ConfirmEmailModel : PageModel
{
private readonly UserManager<ApplicationUser> _userManager;
public ConfirmEmailModel(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
[TempData]
public string StatusMessage { get; set; }
public async Task<IActionResult> OnGetAsync(string userId, string code)
{
if (userId == null || code == null)
{
return RedirectToPage("/Index");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return NotFound($"Unable to load user with ID '{userId}'.");
}
code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
var result = await _userManager.ConfirmEmailAsync(user, code);
StatusMessage = result.Succeeded ? "Thank you for confirming your email." : "Error confirming your email.";
return Page();
}
}
}
| 30.979167 | 119 | 0.647613 | [
"MIT"
] | mrsadengineer/AlgoraArt | AlgoraArt.WebApp/Areas/Identity/Pages/Account/ConfirmEmail.cshtml.cs | 1,489 | C# |
#region Copyright (c) 2014 Systematic
// **********************************************************************************
// The MIT License (MIT)
//
// Copyright (c) 2014 Systematic
//
// 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 NUnit.Framework;
using NUnit.Framework.Constraints;
namespace Systematic.NUnit.Test.Constraints
{
[TestFixture]
// ReSharper disable InconsistentNaming
public class ObjectPropertiesNotEqualsConstraintTest
{
#region No Modifyers
[Test]
public void Matches_PrimitiveEqual_ReturnsFalse()
{
//Note: Because primitives has no properties as such, might wan't to implement this as "Is.EqualTo" instead, but for now we accept this.
Constraint constraint = HAS.Properties.NotEqualTo("one");
Assert.That(constraint.Matches("one"), Is.False);
}
[Test]
public void Matches_PrimitiveNotEqual_ReturnsFalse()
{
Constraint constraint = HAS.Properties.NotEqualTo("one");
Assert.That(constraint.Matches("two"), Is.False);
}
#endregion
#region Using Ignore
[Test]
public void Matches_SimpleEqualWithIgnore_ReturnsFalse()
{
SimpleObject actual = new SimpleObject { StringValue = "Hello", Int32Value = 42 };
SimpleObject expected = new SimpleObject { StringValue = "Hello World", Int32Value = 42 };
Constraint constraint = HAS.Properties.NotEqualTo(expected).Ignore(x => x.StringValue);
Assert.That(constraint.Matches(actual), Is.False);
}
[Test]
public void Matches_SimpleNotEqualWithIgnore_ReturnsTrue()
{
SimpleObject actual = new SimpleObject { StringValue = "Hello", Int32Value = 42 };
SimpleObject expected = new SimpleObject { StringValue = "Hello World", Int32Value = 42 };
Constraint constraint = HAS.Properties.NotEqualTo(expected).Ignore(x => x.Int32Value);
Assert.That(constraint.Matches(actual), Is.True);
}
[Test]
public void Matches_ComplexEqualWithIgnore_ReturnsFalse()
{
ComplexObject actual = new ComplexObject { Simple = new SimpleObject { StringValue = "Hello", Int32Value = 42 }, StringValue = "Hello", Int32Value = 42 };
ComplexObject expected = new ComplexObject { Simple = new SimpleObject { StringValue = "Hello", Int32Value = 42 }, StringValue = "Hello World", Int32Value = 42 };
Constraint constraint = HAS.Properties.NotEqualTo(expected).Ignore(x => x.StringValue);
Assert.That(constraint.Matches(actual), Is.False);
}
[Test]
public void Matches_ComplexNotEqualWithIgnore_ReturnsTrue()
{
ComplexObject actual = new ComplexObject { Simple = new SimpleObject { StringValue = "Hello", Int32Value = 42 }, StringValue = "Hello", Int32Value = 42 };
ComplexObject expected = new ComplexObject { Simple = new SimpleObject { StringValue = "Hello", Int32Value = 42 }, StringValue = "Hello World", Int32Value = 42 };
Constraint constraint = HAS.Properties.NotEqualTo(expected).Ignore(x => x.Int32Value);
Assert.That(constraint.Matches(actual), Is.True);
}
[Test]
public void Matches_ComplexEqualWithIgnoreComplex_ReturnsFalse()
{
ComplexObject actual = new ComplexObject { Simple = new SimpleObject { StringValue = "Hello", Int32Value = 42 }, StringValue = "Hello", Int32Value = 42 };
ComplexObject expected = new ComplexObject { Simple = new SimpleObject { StringValue = "Hello World", Int32Value = 42 }, StringValue = "Hello", Int32Value = 42 };
Constraint constraint = HAS.Properties.NotEqualTo(expected).Ignore(x => x.Simple);
Assert.That(constraint.Matches(actual), Is.False);
}
[Test]
public void Matches_ComplexNotEqualWithIgnoreComplex_ReturnsTrue()
{
ComplexObject actual = new ComplexObject { Simple = new SimpleObject { StringValue = "Hello", Int32Value = 42 }, StringValue = "Hello", Int32Value = 42 };
ComplexObject expected = new ComplexObject { Simple = new SimpleObject { StringValue = "Hello", Int32Value = 42 }, StringValue = "Hello World", Int32Value = 42 };
Constraint constraint = HAS.Properties.NotEqualTo(expected).Ignore(x => x.Simple);
Assert.That(constraint.Matches(actual), Is.True);
}
#endregion
}
} | 48.067797 | 174 | 0.652151 | [
"MIT"
] | systematic-com/nunit | src/Systematic.NUnit.Test/Constraints/ObjectPropertiesNotEqualsConstraintTest.cs | 5,672 | C# |
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using MediatR;
using SampleAngular.Application.Common.Interfaces;
using SampleAngular.Application.Common.Pagings;
using SampleAngular.Application.Storage.Manufacturers.Models;
namespace SampleAngular.Application.Storage.Manufacturers.Queries
{
public class ListQuery : IRequest<ListViewModel>
{
public IPagingViewModel<DetailViewModel> Info { get; set; }
private class Handler : IRequestHandler<ListQuery, ListViewModel>
{
private readonly ISampleAngularContext _context;
private readonly IMapper _mapper;
public Handler(ISampleAngularContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public async Task<ListViewModel> Handle(ListQuery request,
CancellationToken cancellationToken)
{
request.Info.Collection = _context.Manufacturers
.ProjectTo<DetailViewModel>(_mapper.ConfigurationProvider);
return new ListViewModel
{Pagination = request.Info.PagingDetails, Manufacturers = request.Info.EntitiesPerPage.ToList()};
}
}
}
} | 34.384615 | 117 | 0.671887 | [
"Apache-2.0"
] | liannoi/sample-angular | src/system/core/application/Storage/Manufacturers/Queries/ListQuery.cs | 1,341 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace MSFramework.Ef.SqlServer
{
public static class ServiceCollectionExtensions
{
public static EntityFrameworkBuilder AddSqlServer<TDbContext>(
this EntityFrameworkBuilder builder, IConfiguration configuration) where TDbContext : DbContextBase
{
builder.Services.AddDbContext<TDbContext>(x =>
{
var dbContextType = typeof(TDbContext);
var entryAssemblyName = dbContextType.Assembly.GetName().Name;
var store = new EntityFrameworkOptionsConfiguration(configuration);
var option = store.Get(dbContextType);
x.UseSqlServer(option.ConnectionString, options => { options.MigrationsAssembly(entryAssemblyName); });
});
return builder;
}
}
} | 32.56 | 107 | 0.786241 | [
"MIT"
] | jonechenug/MSFramework | src/MSFramework.Ef.SqlServer/ServiceCollectionExtensions.cs | 814 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Scripting.Hosting;
namespace IServiceOriented.ServiceBus.Scripting
{
public class ScriptContext
{
public ScriptContext()
{
ScriptRuntime = ScriptRuntime.CreateFromConfiguration();
}
static ScriptContext()
{
Current = new ScriptContext();
}
public ScriptRuntime ScriptRuntime
{
get;
private set;
}
public static ScriptContext Current
{
get;
private set;
}
}
}
| 18.2 | 68 | 0.55416 | [
"MIT"
] | Parlew/iserviceoriented | IServiceOriented.ServiceBus.Scripting/ScriptContext.cs | 639 | C# |
// WARNING
//
// This file has been generated automatically by Xamarin Studio from the outlets and
// actions declared in your storyboard file.
// Manual changes to this file will not be maintained.
//
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;
namespace EccDHIosC
{
[Register ("ViewController")]
partial class ViewController
{
void ReleaseDesignerOutlets ()
{
}
}
}
| 18.681818 | 84 | 0.746959 | [
"MIT"
] | babusri/EccDHIosC | EccDHIosC/ViewController.designer.cs | 411 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Zephyr.Utils.ExcelLibrary.BinaryFileFormat
{
public partial class SubRecord : Record
{
public SubRecord() : base() { }
public SubRecord(SubRecord record) : base(record) { }
public new static SubRecord ReadBase(Stream stream)
{
BinaryReader reader = new BinaryReader(stream);
SubRecord record = new SubRecord();
record.Type = reader.ReadUInt16();
record.Size = reader.ReadUInt16();
record.Data = reader.ReadBytes(record.Size);
return record;
}
}
}
| 26.76 | 61 | 0.623318 | [
"MIT"
] | zhupangithub/WEBERP | Code/Zephyr.Net/Zephyr.Utils/Document/Excel/ExcelLibrary/Office/Excel/BinaryFileFormat/SubRecord.cs | 671 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.Debugging
{
[ExportLanguageService(typeof(ILanguageDebugInfoService), LanguageNames.CSharp), Shared]
internal partial class CSharpLanguageDebugInfoService : ILanguageDebugInfoService
{
[ImportingConstructor]
public CSharpLanguageDebugInfoService()
{
}
public Task<DebugLocationInfo> GetLocationInfoAsync(Document document, int position, CancellationToken cancellationToken)
{
return LocationInfoGetter.GetInfoAsync(document, position, cancellationToken);
}
public Task<DebugDataTipInfo> GetDataTipInfoAsync(
Document document, int position, CancellationToken cancellationToken)
{
return DataTipInfoGetter.GetInfoAsync(document, position, cancellationToken);
}
}
}
| 37.21875 | 161 | 0.746432 | [
"Apache-2.0"
] | GrahamTheCoder/roslyn | src/Features/CSharp/Portable/Debugging/CSharpLanguageDebugInfoService.cs | 1,193 | C# |
namespace tabuleiro {
abstract class Peca {
public Posicao posicao {get; set; }
public Cor cor {get; protected set; }
public int quantidadeMovimento {get; protected set; }
public Tabuleiro tabuleiro {get; protected set; }
public Peca(Tabuleiro tabuleiro, Cor cor)
{
this.posicao = null;
this.tabuleiro = tabuleiro;
this.cor = cor;
this.quantidadeMovimento = 0;
}
public void IncrementarMovimento()
{
quantidadeMovimento++;
}
public void DecrementarMovimento() {
quantidadeMovimento--;
}
public bool ExisteMovimentosPossiveis() {
bool[,] mat = MovimentosPossiveis();
for(int i = 0; i < tabuleiro.linhas; i++) {
for(int j = 0; j < tabuleiro.colunas; j++) {
if(mat[i, j]) {
return true;
}
}
}
return false;
}
public bool PoderMoverPara(Posicao posicao) {
return MovimentosPossiveis()[posicao.linha, posicao.coluna];
}
public abstract bool[,] MovimentosPossiveis();
}
}
| 26.270833 | 72 | 0.505948 | [
"MIT"
] | fernanduandrade/csharp-studies | UdemyCourse/Xadrez/tabuleiro/Peca.cs | 1,261 | 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 DomainAwareSingleton.Properties {
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", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <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("DomainAwareSingleton.Properties.Resources", typeof(Resources).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;
}
}
}
}
| 44.796875 | 187 | 0.602372 | [
"MIT"
] | monze/CrossDomainSingleton | Source/DomainAwareSingleton/Properties/Resources.Designer.cs | 2,869 | C# |
using UnityEngine;
using UnityEngine.AI;
namespace CleanCore.AI
{
public class GetRandomNavmeshLocationUseCase
{
/// <summary>
/// Retrun a random navmesh point
/// </summary>
/// <param name="_radius"></param>
/// <returns></returns>
public Vector3 RandomNavmeshLocation(float _radius, Transform transform)
{
Vector3 randomDirection = Random.insideUnitSphere * _radius;
randomDirection += transform.position;
Vector3 finalPosition = Vector3.zero;
if (NavMesh.SamplePosition(randomDirection, out NavMeshHit hit, _radius, 1))
{
finalPosition = hit.position;
}
return finalPosition;
}
}
} | 31.52 | 89 | 0.574873 | [
"MIT"
] | LaloBerro/CleanCore | Runtime/AI/GetRandomNavmeshLocationUseCase.cs | 790 | C# |
//2014 BSD,WinterDev
//MatterHackers: BSD
// Much of the ui to the drawing functions still needs to be C#'ed and cleaned up. A lot of
// it still follows the originall agg function names. I have been cleaning these up over time
// and intend to do much more refactoring of these things over the long term.
using System;
using Mini;
namespace PixelFarm.Agg.SimplePainter
{
[Info(OrderCode = "01")]
[Info("SimplePainter")]
public class SimplePainterSample1 : DemoBase
{
public override void Init()
{
}
public override void Draw(CanvasPainter p)
{
p.Clear(ColorRGBA.White);
// draw a circle
p.FillColor = ColorRGBA.Blue;
p.FillCircle(50, 50, 30);
p.StrokeColor = new ColorRGBA(20, 200, 200);
p.Line(10, 100, 520, 50);
// draw a filled box
p.FillRectangle(60, 260, 200, 280, ColorRGBA.Yellow);
// and an outline around it
p.Rectangle(60, 260, 200, 280, ColorRGBA.Magenta);
p.DrawString("A Simple Example", 300, 400);
p.DrawString("A Simple Example2", 300, 350);
p.DrawString("A Simple Example3", 300, 300);
p.DrawString("A Simple Example4", 300, 250);
}
}
} | 35.027027 | 94 | 0.595679 | [
"MIT"
] | prepare/MiniAggLegacy | a_mini/projects/Mini/3_Samples/01_DrawSamples/SimplePainterSample.cs | 1,298 | C# |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// 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 System.Linq;
using Sensus.Shared;
using Sensus.Shared.Probes.Location;
using Xamarin.Forms;
namespace Sensus.Shared.UI
{
/// <summary>
/// Displays proximity triggers.
/// </summary>
public class ProximityTriggersPage : ContentPage
{
/// <summary>
/// Initializes a new instance of the <see cref="SensusUI.ProximityTriggersPage"/> class.
/// </summary>
/// <param name="proximityProbe">Proximity probe to display triggers for.</param>
public ProximityTriggersPage(IPointsOfInterestProximityProbe proximityProbe)
{
Title = "Proximity Triggers";
ListView triggerList = new ListView();
triggerList.ItemTemplate = new DataTemplate(typeof(TextCell));
triggerList.ItemTemplate.SetBinding(TextCell.TextProperty, new Binding(".", stringFormat: "{0}"));
triggerList.ItemsSource = proximityProbe.Triggers;
triggerList.ItemTapped += async (o, e) =>
{
if (triggerList.SelectedItem == null)
return;
PointOfInterestProximityTrigger selectedTrigger = triggerList.SelectedItem as PointOfInterestProximityTrigger;
string selectedAction = await DisplayActionSheet(selectedTrigger.ToString(), "Cancel", null, "Delete");
if (selectedAction == "Delete")
{
if (await DisplayAlert("Delete " + selectedTrigger + "?", "This action cannot be undone.", "Delete", "Cancel"))
{
proximityProbe.Triggers.Remove(selectedTrigger);
triggerList.SelectedItem = null; // reset manually since it isn't done automatically
}
}
};
Content = triggerList;
ToolbarItems.Add(new ToolbarItem(null, "plus.png", async () =>
{
if (SensusServiceHelper.Get().PointsOfInterest.Union(proximityProbe.Protocol.PointsOfInterest).Count() > 0)
await Navigation.PushAsync(new AddProximityTriggerPage(proximityProbe));
else
SensusServiceHelper.Get().FlashNotificationAsync("You must define points of interest before adding triggers.");
}));
}
}
} | 43.797101 | 139 | 0.617472 | [
"Apache-2.0"
] | w-bonelli/sensus | Sensus.Shared/UI/ProximityTriggersPage.cs | 3,024 | C# |
/*
* Copyright 2010-2013 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.
*/
using System.Collections.Generic;
using Amazon.IdentityManagement.Model;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.IdentityManagement.Model.Internal.MarshallTransformations
{
/// <summary>
/// GetAccountSummaryResult Unmarshaller
/// </summary>
internal class GetAccountSummaryResultUnmarshaller : IUnmarshaller<GetAccountSummaryResult, XmlUnmarshallerContext>, IUnmarshaller<GetAccountSummaryResult, JsonUnmarshallerContext>
{
public GetAccountSummaryResult Unmarshall(XmlUnmarshallerContext context)
{
GetAccountSummaryResult getAccountSummaryResult = new GetAccountSummaryResult();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.Read())
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("SummaryMap/entry", targetDepth))
{
KeyValueUnmarshaller<string, int, StringUnmarshaller, IntUnmarshaller> unmarshaller = new KeyValueUnmarshaller<string, int, StringUnmarshaller, IntUnmarshaller>(StringUnmarshaller.GetInstance(), IntUnmarshaller.GetInstance());
KeyValuePair<string, int> kvp = unmarshaller.Unmarshall(context);
getAccountSummaryResult.SummaryMap.Add(kvp.Key, kvp.Value);
continue;
}
}
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
return getAccountSummaryResult;
}
}
return getAccountSummaryResult;
}
public GetAccountSummaryResult Unmarshall(JsonUnmarshallerContext context)
{
return null;
}
private static GetAccountSummaryResultUnmarshaller instance;
public static GetAccountSummaryResultUnmarshaller GetInstance()
{
if (instance == null)
instance = new GetAccountSummaryResultUnmarshaller();
return instance;
}
}
}
| 38.157895 | 250 | 0.635862 | [
"Apache-2.0"
] | jdluzen/aws-sdk-net-android | AWSSDK/Amazon.IdentityManagement/Model/Internal/MarshallTransformations/GetAccountSummaryResultUnmarshaller.cs | 2,900 | C# |
using Elasticsearch.Net;
using FluentAssertions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Nest.Tests.Unit.ObjectInitializer.Warmers
{
[TestFixture]
public class PutWarmerRequestTests : BaseJsonTests
{
private readonly IElasticsearchResponse _status;
public PutWarmerRequestTests()
{
QueryContainer query = new MatchAllQuery();
var request = new PutWarmerRequest("warmer_1")
{
Indices = new IndexNameMarker[] { "my-index" },
SearchDescriptor = new SearchRequest { Query = query }
};
var response = this._client.PutWarmer(request);
this._status = response.ConnectionStatus;
}
[Test]
public void Url()
{
this._status.RequestUrl.Should().EndWith("/my-index/_warmer/warmer_1");
this._status.RequestMethod.Should().Be("PUT");
}
[Test]
public void PutWarmerBody()
{
this.JsonEquals(this._status.Request, MethodInfo.GetCurrentMethod());
}
}
}
| 22.477273 | 74 | 0.73003 | [
"Apache-2.0"
] | Bloomerang/elasticsearch-net | src/Tests/Nest.Tests.Unit/ObjectInitializer/Warmers/PutWarmerRequestTests.cs | 991 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime
{
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using static Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Extensions;
public class RestException : Exception, IDisposable
{
public System.Net.HttpStatusCode StatusCode { get; set; }
public string Code { get; protected set; }
protected string message;
public HttpRequestMessage RequestMessage { get; protected set; }
public HttpResponseHeaders ResponseHeaders { get; protected set; }
public string ResponseBody { get; protected set; }
public string ClientRequestId { get; protected set; }
public string RequestId { get; protected set; }
public override string Message => message;
public string Action { get; protected set; }
public RestException(System.Net.Http.HttpResponseMessage response)
{
StatusCode = response.StatusCode;
//CloneWithContent will not work here since the content is disposed after sendAsync
//Besides, it seems there is no need for the request content cloned here.
RequestMessage = response.RequestMessage.Clone();
ResponseBody = response.Content.ReadAsStringAsync().Result;
ResponseHeaders = response.Headers;
RequestId = response.GetFirstHeader("x-ms-request-id");
ClientRequestId = response.GetFirstHeader("x-ms-client-request-id");
try
{
// try to parse the body as JSON, and see if a code and message are in there.
var json = Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject;
// error message could be in properties.statusMessage
{ message = If(json?.Property("properties"), out var p)
&& If(p?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString>("statusMessage"), out var sm)
? (string)sm : (string)Message; }
// see if there is an error block in the body
json = json?.Property("error") ?? json;
{ Code = If(json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString>("code"), out var c) ? (string)c : (string)StatusCode.ToString(); }
{ message = If(json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString>("message"), out var m) ? (string)m : (string)Message; }
{ Action = If(json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString>("action"), out var a) ? (string)a : (string)Action; }
}
#if DEBUG
catch (System.Exception E)
{
System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}");
}
#else
catch
{
// couldn't get the code/message from the body response.
// we'll create one below.
}
#endif
if (string.IsNullOrEmpty(message))
{
if (StatusCode >= System.Net.HttpStatusCode.BadRequest && StatusCode < System.Net.HttpStatusCode.InternalServerError)
{
message = $"The server responded with a Request Error, Status: {StatusCode}";
}
else if (StatusCode >= System.Net.HttpStatusCode.InternalServerError)
{
message = $"The server responded with a Server Error, Status: {StatusCode}";
}
else
{
message = $"The server responded with an unrecognized response, Status: {StatusCode}";
}
}
}
public void Dispose()
{
((IDisposable)RequestMessage).Dispose();
}
}
public class RestException<T> : RestException
{
public T Error { get; protected set; }
public RestException(System.Net.Http.HttpResponseMessage response, T error) : base(response)
{
Error = error;
}
}
public class UndeclaredResponseException : RestException
{
public UndeclaredResponseException(System.Net.Http.HttpResponseMessage response) : base(response)
{
}
}
} | 45.357798 | 187 | 0.576052 | [
"MIT"
] | Amrinder-Singh29/azure-powershell | src/Functions/generated/runtime/UndeclaredResponseException.cs | 4,836 | C# |
using System;
namespace ENode.Infrastructure
{
public class ProcessingPublishableExceptionMessage : IProcessingMessage<ProcessingPublishableExceptionMessage, IPublishableException>
{
private ProcessingMessageMailbox<ProcessingPublishableExceptionMessage, IPublishableException> _mailbox;
private IMessageProcessContext _processContext;
public IPublishableException Message { get; private set; }
public ProcessingPublishableExceptionMessage(IPublishableException message, IMessageProcessContext processContext)
{
Message = message;
_processContext = processContext;
}
public void SetMailbox(ProcessingMessageMailbox<ProcessingPublishableExceptionMessage, IPublishableException> mailbox)
{
_mailbox = mailbox;
}
public void Complete()
{
_processContext.NotifyMessageProcessed();
if (_mailbox != null)
{
_mailbox.CompleteMessage(this);
}
}
}
}
| 32.9375 | 137 | 0.684061 | [
"MIT"
] | fatli/enode-master | src/ENode/Infrastructure/ProcessingPublishableExceptionMessage.cs | 1,056 | C# |
//
// AtPacket.cs
//
// Copyright (c) František Boháček. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using NosSmooth.PacketSerializer.Abstractions.Attributes;
namespace NosSmooth.Packets.Server.Maps;
/// <summary>
/// At packet. Sent when unknown TODO.
/// </summary>
/// <param name="CharacterId">The id of the character.</param>
/// <param name="MapId">The map id.</param>
/// <param name="X">The x coordinate of the character.</param>
/// <param name="Y">The y coordinate of the character.</param>
[PacketHeader("at", PacketSource.Server)]
[GenerateSerializer(true)]
public record AtPacket
(
[PacketIndex(0)]
long CharacterId,
[PacketIndex(1)]
int MapId,
[PacketIndex(2)]
short X,
[PacketIndex(3)]
short Y
) : IPacket; | 27.966667 | 102 | 0.694875 | [
"MIT"
] | Rutherther/NosSmooth | Packets/NosSmooth.Packets/Server/Maps/AtPacket.cs | 844 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Project.Domain.Repository
{
public interface IUnitOfWork : IDisposable
{
IDeviceRepository Devices { get; }
IConsumeRepository Consumes { get; }
IZoneRepository Zones { get; }
Task<int> CommitAsync(CancellationToken cancellationToken = default(CancellationToken));
}
} | 26.2 | 96 | 0.712468 | [
"MIT"
] | henrygustavo/cqrs-api | Project.Domain/Repository/IUnitOfWork.cs | 395 | C# |
using System;
using NetRuntimeSystem = System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.ComponentModel;
using System.Reflection;
using System.Collections.Generic;
using NetOffice;
namespace NetOffice.PowerPointApi
{
///<summary>
/// DispatchInterface PPSpinner
/// SupportByVersion PowerPoint, 9
///</summary>
[SupportByVersionAttribute("PowerPoint", 9)]
[EntityTypeAttribute(EntityType.IsDispatchInterface)]
public class PPSpinner : PPControl
{
#pragma warning disable
#region Type Information
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(PPSpinner);
return _type;
}
}
#endregion
#region Construction
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public PPSpinner(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public PPSpinner(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public PPSpinner(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public PPSpinner(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public PPSpinner(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public PPSpinner() : base()
{
}
/// <param name="progId">registered ProgID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public PPSpinner(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion PowerPoint 9
/// Get/Set
/// </summary>
[SupportByVersionAttribute("PowerPoint", 9)]
public Int32 Minimum
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Minimum", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Minimum", paramsArray);
}
}
/// <summary>
/// SupportByVersion PowerPoint 9
/// Get/Set
/// </summary>
[SupportByVersionAttribute("PowerPoint", 9)]
public Int32 Maximum
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Maximum", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Maximum", paramsArray);
}
}
/// <summary>
/// SupportByVersion PowerPoint 9
/// Get/Set
/// </summary>
[SupportByVersionAttribute("PowerPoint", 9)]
public Int32 Increment
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Increment", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Increment", paramsArray);
}
}
/// <summary>
/// SupportByVersion PowerPoint 9
/// Get/Set
/// </summary>
[SupportByVersionAttribute("PowerPoint", 9)]
public Int32 PageChange
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "PageChange", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "PageChange", paramsArray);
}
}
/// <summary>
/// SupportByVersion PowerPoint 9
/// Get/Set
/// </summary>
[SupportByVersionAttribute("PowerPoint", 9)]
public Int32 CurrentValue
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "CurrentValue", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "CurrentValue", paramsArray);
}
}
/// <summary>
/// SupportByVersion PowerPoint 9
/// Get/Set
/// </summary>
[SupportByVersionAttribute("PowerPoint", 9)]
public string OnAChange
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnAChange", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnAChange", paramsArray);
}
}
#endregion
#region Methods
#endregion
#pragma warning restore
}
} | 27.868778 | 164 | 0.684689 | [
"MIT"
] | brunobola/NetOffice | Source/PowerPoint/DispatchInterfaces/PPSpinner.cs | 6,161 | C# |
using FluentAutomation.Interfaces;
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
namespace FluentAutomation.Tests
{
/// <summary>
/// Base Test that opens the test to the AUT
/// </summary>
public class BaseTest : FluentTest<IWebDriver>
{
public BaseTest()
{
FluentSession.EnableStickySession();
Config.WaitUntilTimeout(TimeSpan.FromMilliseconds(1000));
// Create Page Objects
this.InputsPage = new Pages.InputsPage(this);
this.AlertsPage = new Pages.AlertsPage(this);
this.ScrollingPage = new Pages.ScrollingPage(this);
this.TextPage = new Pages.TextPage(this);
this.DragPage = new Pages.DragPage(this);
this.SwitchPage = new Pages.SwitchPage(this);
// Default tests use chrome and load the site
//FluentAutomation.SeleniumWebDriver.Bootstrap(SeleniumWebDriver.Browser.Chrome); //, SeleniumWebDriver.Browser.InternetExplorer, SeleniumWebDriver.Browser.Firefox);
// Test browserstack local
//WbTstr.Configure()
// .EnableDebug()
// .UseBrowserStackAsRemoteDriver()
// .SetBrowserStackBuildIdentifier(buildResultKey)
// .EnableBrowserStackLocal()
// .PreferedBrowser().IsChrome()
// .PreferedOperatingSystem().IsWindows()
// .PreferedScreenResolution().IsAny();
WbTstr.Bootstrap();
FluentSession.DisableStickySession();
I.Open(SiteUrl);
}
public string SiteUrl
{
get
{
return ConfigReader.GetSetting("WebsiteUnderTestBaseUrl");
}
}
public Pages.InputsPage InputsPage = null;
public Pages.AlertsPage AlertsPage = null;
public Pages.ScrollingPage ScrollingPage = null;
public Pages.TextPage TextPage = null;
public Pages.DragPage DragPage = null;
public Pages.SwitchPage SwitchPage = null;
}
public class AssertBaseTest : BaseTest
{
public AssertBaseTest()
: base()
{
Config.OnExpectFailed((ex, state) =>
{
// For the purpose of these tests, allow expects to throw (break test)
throw ex;
});
}
}
}
| 31.628205 | 177 | 0.592623 | [
"MIT"
] | mirabeau-nl/WbTstr.Net | FluentAutomation.Tests/BaseTest.cs | 2,469 | C# |
//
// Copyright (C) 2012 DataStax 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
//
// 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 System;
namespace Cassandra
{
/// <summary>
/// Base class for statements that contains the options.
/// </summary>
public abstract class Statement : IStatement
{
private ConsistencyLevel? _consistency;
private int _pageSize;
private byte[] _pagingState;
private IRetryPolicy _retryPolicy;
private ConsistencyLevel _serialConsistency;
private bool _skipMetadata;
private bool _traceQuery;
private object[] _values;
public virtual object[] QueryValues
{
get { return _values; }
}
public bool SkipMetadata
{
get { return _skipMetadata; }
}
public ConsistencyLevel? ConsistencyLevel
{
get { return _consistency; }
}
/// <summary>
/// Gets the serial consistency level for this query.
/// </summary>
public ConsistencyLevel SerialConsistencyLevel
{
get { return _serialConsistency; }
}
public int PageSize
{
get { return _pageSize; }
}
public bool IsTracing
{
get { return _traceQuery; }
}
public IRetryPolicy RetryPolicy
{
get { return _retryPolicy; }
}
public byte[] PagingState
{
get { return _pagingState; }
}
/// <summary>
/// The routing key (in binary raw form) to use for token aware routing of this
/// query. <p> The routing key is optional in the sense that implementers are
/// free to return <c>null</c>. The routing key is an hint used for token
/// aware routing (see
/// <link>TokenAwarePolicy</link>), and if
/// provided should correspond to the binary value for the query partition key.
/// However, not providing a routing key never causes a query to fail and if the
/// load balancing policy used is not token aware, then the routing key can be
/// safely ignored.</p>
/// </summary>
/// <returns>the routing key for this query or <c>null</c>.</returns>
public abstract RoutingKey RoutingKey { get; }
// We don't want to expose the constructor, because the code rely on this being only subclassed by Statement and BoundStatement
protected Statement()
{
//this._consistency = QueryOptions.DefaultConsistencyLevel;
}
protected Statement(QueryProtocolOptions queryProtocolOptions)
{
_pagingState = queryProtocolOptions.PagingState;
_values = queryProtocolOptions.Values;
_consistency = queryProtocolOptions.Consistency;
_pageSize = queryProtocolOptions.PageSize;
_serialConsistency = queryProtocolOptions.SerialConsistency;
}
internal Statement SetSkipMetadata(bool val)
{
_skipMetadata = val;
return this;
}
/// <summary>
/// Bound values to the variables of this statement. This method provides a
/// convenience to bound all the variables of the <c>BoundStatement</c> in
/// one call.
/// </summary>
/// <param name="values"> the values to bind to the variables of the newly
/// created BoundStatement. The first element of <c>values</c> will
/// be bound to the first bind variable,
/// etc.. It is legal to provide less values than the statement has bound
/// variables. In that case, the remaining variable need to be bound before
/// execution. If more values than variables are provided however, an
/// IllegalArgumentException wil be raised. </param>
///
/// <returns>this bound statement. </returns>
internal IStatement SetValues(object[] values)
{
_values = values;
return this;
}
public IStatement SetPagingState(byte[] pagingState)
{
_pagingState = pagingState;
return this;
}
/// <summary>
/// Sets the consistency level for the query. <p> The default consistency level,
/// if this method is not called, is ConsistencyLevel.ONE.</p>
/// </summary>
/// <param name="consistency"> the consistency level to set. </param>
///
/// <returns>this <c>Query</c> object.</returns>
public IStatement SetConsistencyLevel(ConsistencyLevel? consistency)
{
_consistency = consistency;
return this;
}
/// <summary>
/// Sets the serial consistency level for the query.
/// The serial consistency level is only used by conditional updates (so INSERT, UPDATE
/// and DELETE with an IF condition). For those, the serial consistency level defines
/// the consistency level of the serial phase (or "paxos" phase) while the
/// normal consistency level defines the consistency for the "learn" phase, i.e. what
/// type of reads will be guaranteed to see the update right away. For instance, if
/// a conditional write has a regular consistency of QUORUM (and is successful), then a
/// QUORUM read is guaranteed to see that write. But if the regular consistency of that
/// write is ANY, then only a read with a consistency of SERIAL is guaranteed to see it
/// (even a read with consistency ALL is not guaranteed to be enough).
/// </summary>
/// <param name="serialConsistency">Can be set only to ConsistencyLevel.Serial or
/// ConsistencyLevel.LocalSerial. Setting it to ConsistencyLevel.Serial guarantees full
/// linearizability while ConsistencyLevel.LocalSerial guarantees it only in the local datacenter. </param>
/// <returns>this <c>Query</c> object.</returns>
public IStatement SetSerialConsistencyLevel(ConsistencyLevel serialConsistency)
{
if (serialConsistency != Cassandra.ConsistencyLevel.Serial && serialConsistency != Cassandra.ConsistencyLevel.LocalSerial)
throw new ArgumentException("The serial consistency can only be set to ConsistencyLevel.LocalSerial or ConsistencyLevel.Serial.");
_serialConsistency = serialConsistency;
return this;
}
/// <summary>
/// Enable tracing for this query. By default (i.e. unless you call this method),
/// tracing is not enabled.
/// </summary>
///
/// <returns>this <c>Query</c> object.</returns>
public IStatement EnableTracing(bool enable = true)
{
_traceQuery = enable;
return this;
}
public IStatement DisableTracing()
{
_traceQuery = false;
return this;
}
/// <summary>
/// Sets the retry policy to use for this query. <p> The default retry policy, if
/// this method is not called, is the one returned by
/// <link>Policies#RetryPolicy</link> in the
/// cluster configuration. This method is thus only useful in case you want to
/// punctually override the default policy for this request.</p>
/// </summary>
/// <param name="policy"> the retry policy to use for this query. </param>
///
/// <returns>this <c>Query</c> object.</returns>
public IStatement SetRetryPolicy(IRetryPolicy policy)
{
_retryPolicy = policy;
return this;
}
internal virtual IQueryRequest CreateBatchRequest()
{
throw new InvalidOperationException("Cannot insert this query into the batch");
}
/// <summary>
/// Sets the page size for this query.
/// The page size controls how much resulting rows will be retrieved
/// simultaneously (the goal being to avoid loading too much results
/// in memory for queries yielding large results). Please note that
/// while value as low as 1 can be used, it is highly discouraged to
/// use such a low value in practice as it will yield very poor
/// performance. If in doubt, leaving the default is probably a good
/// idea.
/// <p>
/// Also note that only {@code SELECT} queries ever make use of that
/// setting.
/// </p>
///
/// @param fetchSize the fetch size to use. If {@code fetchSize <= 0},
/// the default fetch size will be used. To disable paging of the
/// result set, use {@code fetchSize == Integer.MAX_VALUE}.
/// @return this {@code Statement} object.
/// </summary>
/// <param name="pageSize">the page size to use. If set to 0 or less, the default value will be used.
/// To disable paging of the result set, use int.MaxValue</param>
/// <returns>this <c>Query</c> object.</returns>
public IStatement SetPageSize(int pageSize)
{
_pageSize = pageSize;
return this;
}
}
} | 39.833333 | 146 | 0.608531 | [
"Apache-2.0"
] | Youscribe/csharp-driver | src/Cassandra/Statement.cs | 9,801 | C# |
using System;
using System.Collections.Generic;
using Microsoft.ApplicationInsights;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Runtime;
namespace Orleans.TelemetryConsumers.AI
{
/// <summary>
/// Telemetry consumer class for ApplicationInsights.
/// </summary>
public class AITelemetryConsumer : ITraceTelemetryConsumer, IEventTelemetryConsumer, IExceptionTelemetryConsumer,
IDependencyTelemetryConsumer, IMetricTelemetryConsumer, IRequestTelemetryConsumer
{
private readonly TelemetryClient _client;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="options">The instrumentation key for ApplicationInsights.</param>
public AITelemetryConsumer(IOptions<ApplicationInsightsTelemetryConsumerOptions> options)
{
var instrumentationKey = options.Value.InstrumentationKey;
this._client = instrumentationKey != null
? new TelemetryClient(new Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration { InstrumentationKey = instrumentationKey })
#pragma warning disable CS0618 // Type or member is obsolete
: new TelemetryClient(Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active);
#pragma warning restore CS0618 // Type or member is obsolete
}
/// <inheritdoc />
public virtual void DecrementMetric(string name) =>
this._client.TrackMetric(name, -1, null);
/// <inheritdoc />
public virtual void DecrementMetric(string name, double value) =>
this._client.TrackMetric(name, value * -1, null);
/// <inheritdoc />
public virtual void IncrementMetric(string name) =>
this._client.TrackMetric(name, 1, null);
/// <inheritdoc />
public virtual void IncrementMetric(string name, double value) =>
this._client.TrackMetric(name, value, null);
/// <inheritdoc />
public virtual void TrackDependency(string dependencyName, string commandName, DateTimeOffset startTime, TimeSpan duration, bool success) =>
this._client.TrackDependency("Orleans", dependencyName, commandName, startTime, duration, success);
/// <inheritdoc />
public virtual void TrackEvent(string eventName, IDictionary<string, string> properties = null, IDictionary<string, double> metrics = null) =>
this._client.TrackEvent(eventName, properties, metrics);
/// <inheritdoc />
public virtual void TrackException(Exception exception, IDictionary<string, string> properties = null, IDictionary<string, double> metrics = null) =>
this._client.TrackException(exception, properties, metrics);
/// <inheritdoc />
public virtual void TrackMetric(string name, TimeSpan value, IDictionary<string, string> properties = null) =>
this._client.TrackMetric(name, value.TotalMilliseconds, properties);
/// <inheritdoc />
public virtual void TrackMetric(string name, double value, IDictionary<string, string> properties = null) =>
this._client.TrackMetric(name, value, properties);
/// <inheritdoc />
public virtual void TrackRequest(string name, DateTimeOffset startTime, TimeSpan duration, string responseCode, bool success) =>
this._client.TrackRequest(name, startTime, duration, responseCode, success);
/// <inheritdoc />
public virtual void TrackTrace(string message) => this.TrackTrace(message, null);
/// <inheritdoc />
public virtual void TrackTrace(string message, IDictionary<string, string> properties)
{
if (properties != null)
{
this._client.TrackTrace(message, Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Information, properties);
}
else
{
this._client.TrackTrace(message);
}
}
/// <inheritdoc />
public virtual void TrackTrace(string message, Severity severity) =>
this.TrackTrace(message, severity, null);
/// <inheritdoc />
public virtual void TrackTrace(string message, Severity severity, IDictionary<string, string> properties)
{
Microsoft.ApplicationInsights.DataContracts.SeverityLevel sev;
switch (severity)
{
case Severity.Off:
return;
case Severity.Error:
sev = Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Error;
break;
case Severity.Warning:
sev = Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Warning;
break;
case Severity.Verbose:
case Severity.Verbose2:
case Severity.Verbose3:
sev = Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Verbose;
break;
default:
sev = Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Information;
break;
}
if (properties == null)
{
this._client.TrackTrace(message, sev);
}
else
{
this._client.TrackTrace(message, sev, properties);
}
}
/// <inheritdoc />
public virtual void Flush() { }
/// <inheritdoc />
public virtual void Close() { }
}
}
| 41.873134 | 157 | 0.632864 | [
"MIT"
] | Arithmomaniac/orleans | src/TelemetryConsumers/Orleans.TelemetryConsumers.AI/AITelemetryConsumer.cs | 5,611 | C# |
//------------------------------------------------------------
// Author: 烟雨迷离半世殇
// Mail: 1778139321@qq.com
// Data: 2019年5月14日 22:44:27
//------------------------------------------------------------
using System.Collections.Generic;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Options;
using Sirenix.OdinInspector;
using UnityEngine;
namespace ET
{
[Title("Buff数据块", TitleAlignment = TitleAlignments.Centered)]
[HideLabel]
[BsonDeserializerRegister]
public class BuffDataBase
{
/// <summary>
/// Buff归属的数据块的Id,不是buff的Id,是buff数据所在的数据块Id(也就是NP_DataSupportor的Id)
/// </summary>
[HideInInspector]
[BoxGroup("必填项")]
[LabelText("Buff归属的数据块Id")]
public long BelongToBuffDataSupportorId;
/// <summary>
/// 用于区分Buff,每个Buff Id都是独一无二的
/// 因为我们不能,也不应该关心具体Buff的Id,所以这里直接自动生成
/// </summary>
[HideInInspector]
[LabelText("Buff的Id")]
[BoxGroup("必填项")]
public long BuffId = IdGenerater.Instance.GenerateId();
[BoxGroup("必填项")]
[LabelText("Buff归属技能的Id"), GUIColor(1, 140 / 255f, 0)]
public VTD_Id BelongToSkillId = new VTD_Id();
[LabelText("Buff的添加目标")]
[BoxGroup("必填项")]
public BuffTargetTypes BuffTargetTypes;
[LabelText("Buff的基本特征")]
[BoxGroup("必填项")]
public BuffBaseType BuffBaseType;
[ShowIf("Base_isVisualable")]
[LabelText("Buff图标的名称")]
[BoxGroup("选填项")]
public string SpriteABInfo;
[BoxGroup("选填项")]
[LabelText("Buff是否状态栏可见")]
public bool Base_isVisualable;
[LabelText("要抛出的事件ID,如果有的话")]
[BoxGroup("选填项")]
public List<VTD_EventId> EventIds = new List<VTD_EventId>();
[Tooltip("是否可以叠加(不能叠加就刷新,叠加满也刷新)")]
[LabelText("是否叠加")]
[BoxGroup("选填项")]
public bool CanOverlay;
[ShowIf("CanOverlay")]
[LabelText("叠加层数")]
[MinValue(1)]
[BoxGroup("选填项")]
public int TargetOverlay = 1;
[ShowIf("CanOverlay")]
[LabelText("最大叠加数")]
[BoxGroup("选填项")]
public int MaxOverlay;
[LabelText("Buff持续时间")]
[Tooltip("-1代表永久,0代表此处设置无效,1000 = 1s")]
[BoxGroup("选填项")]
public long SustainTime;
[LabelText("Buff效果为")]
[BoxGroup("选填项")]
public BuffWorkTypes BuffWorkType;
[LabelText("Buff基础数值影响者")]
[BoxGroup("选填项")]
public BuffBaseDataEffectTypes BaseBuffBaseDataEffectTypes;
[BoxGroup("选填项")]
[Tooltip("基础数值,比如技能面板伤害100/200/300这种")]
[BsonDictionaryOptions(DictionaryRepresentation.ArrayOfArrays)]
public Dictionary<int, float> ValueToBeChanged = new Dictionary<int, float>();
[Tooltip("具体的加成(可能会一个效果多种加成方式),例如法强加成")]
[BoxGroup("选填项")]
[BsonDictionaryOptions(DictionaryRepresentation.ArrayOfArrays)]
public Dictionary<BuffAdditionTypes, float> AdditionValue = new Dictionary<BuffAdditionTypes, float>();
}
} | 30.386139 | 111 | 0.591724 | [
"MIT"
] | futouyiba/ClubET | Unity/Assets/Model/NKGMOBA/Battle/SkillSystem/BuffData/SkillBuffDataBase/BuffDataBase.cs | 3,611 | 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("PackageManagerTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PackageManagerTests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("965fc421-1293-4bcf-933f-04b3c9eda0c4")]
// 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")]
| 38.135135 | 84 | 0.747697 | [
"Apache-2.0",
"MIT"
] | frankfralick/Dynamo | test/Libraries/PackageManagerTests/Properties/AssemblyInfo.cs | 1,414 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.VisualStudio.Composition
{
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Composition.Reflection;
internal static partial class ByValueEquality
{
internal static IEqualityComparer<IReadOnlyDictionary<string, object?>> Metadata
{
get { return MetadataDictionaryEqualityComparer.Default; }
}
internal static IEqualityComparer<IReadOnlyDictionary<TKey, TValue>> Dictionary<TKey, TValue>(IEqualityComparer<TValue>? valueComparer = null)
where TKey : notnull
{
return DictionaryEqualityComparer<TKey, TValue>.Get(valueComparer);
}
internal static IEqualityComparer<IReadOnlyDictionary<TKey, ImmutableHashSet<TValue>>> DictionaryOfImmutableHashSet<TKey, TValue>()
where TKey : notnull
{
return DictionaryOfImmutableHashSetEqualityComparer<TKey, TValue>.Default;
}
internal static IEqualityComparer<IReadOnlyCollection<T>> EquivalentIgnoreOrder<T>()
{
return CollectionIgnoreOrder<T>.Default;
}
private class CollectionIgnoreOrder<T> : IEqualityComparer<IReadOnlyCollection<T>>
{
internal static readonly CollectionIgnoreOrder<T> Default = new CollectionIgnoreOrder<T>();
private CollectionIgnoreOrder()
{
}
protected virtual IEqualityComparer<T> ValueComparer
{
get { return EqualityComparer<T>.Default; }
}
public bool Equals(IReadOnlyCollection<T>? x, IReadOnlyCollection<T>? y)
{
if (object.ReferenceEquals(x, y))
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (x.Count != y.Count)
{
return false;
}
IEqualityComparer<T> valueComparer = this.ValueComparer;
var matchingIndexesInY = new bool[y.Count];
var yList = y as IReadOnlyList<T> ?? y.ToList();
foreach (T item in x)
{
int j;
for (j = 0; j < y.Count; j++)
{
if (!matchingIndexesInY[j] && valueComparer.Equals(item, yList[j]))
{
// We found a match. Avoid finding the same item again.
matchingIndexesInY[j] = true;
break;
}
}
if (j == y.Count)
{
// no match
return false;
}
}
return true;
}
public int GetHashCode(IReadOnlyCollection<T> obj)
{
int hashCode = obj.Count;
foreach (T item in obj)
{
hashCode += item is null ? 0 : item.GetHashCode();
}
return hashCode;
}
}
private class DictionaryEqualityComparer<TKey, TValue> : IEqualityComparer<IReadOnlyDictionary<TKey, TValue>>
where TKey : notnull
{
private readonly IEqualityComparer<TValue> valueComparer;
internal static readonly DictionaryEqualityComparer<TKey, TValue> Default = new DictionaryEqualityComparer<TKey, TValue>();
protected DictionaryEqualityComparer(IEqualityComparer<TValue>? valueComparer = null)
{
this.valueComparer = valueComparer ?? EqualityComparer<TValue>.Default;
}
internal static DictionaryEqualityComparer<TKey, TValue> Get(IEqualityComparer<TValue>? valueComparer = null)
{
if (valueComparer == null || valueComparer == EqualityComparer<TValue>.Default)
{
return Default;
}
else
{
return new DictionaryEqualityComparer<TKey, TValue>(valueComparer);
}
}
public virtual bool Equals(IReadOnlyDictionary<TKey, TValue>? x, IReadOnlyDictionary<TKey, TValue>? y)
{
if (object.ReferenceEquals(x, y))
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (x.Count != y.Count)
{
return false;
}
foreach (var pair in x)
{
TValue otherValue;
if (!y.TryGetValue(pair.Key, out otherValue))
{
return false;
}
if (!this.valueComparer.Equals(pair.Value, otherValue))
{
return false;
}
}
return true;
}
public virtual int GetHashCode(IReadOnlyDictionary<TKey, TValue> obj)
{
int hash = obj.Count;
foreach (var pair in obj)
{
hash += pair.Key.GetHashCode();
}
return obj.Count;
}
}
private class MetadataDictionaryEqualityComparer : DictionaryEqualityComparer<string, object?>
{
internal static new readonly MetadataDictionaryEqualityComparer Default = new MetadataDictionaryEqualityComparer();
protected MetadataDictionaryEqualityComparer()
: base(MetadataValueComparer.Default)
{
}
public override int GetHashCode(IReadOnlyDictionary<string, object?> obj)
{
// We don't want to hash the entire contents. So just look for one key that tends to be on most
// metadata and usually has a fairly distinguishing value and hash on that.
string? typeIdentity;
if (obj.TryGetValue(CompositionConstants.ExportTypeIdentityMetadataName, out typeIdentity))
{
return typeIdentity.GetHashCode();
}
// We can't do any better without hashing the entire dictionary.
return 1;
}
public override bool Equals(IReadOnlyDictionary<string, object?>? x, IReadOnlyDictionary<string, object?>? y)
{
if (object.ReferenceEquals(x, y))
{
return true;
}
// Be sure we're comparing TypeRefs instead of resolved Types to avoid loading assemblies unnecessarily.
return base.Equals(LazyMetadataWrapper.TryUnwrap(x), LazyMetadataWrapper.TryUnwrap(y));
}
private class MetadataValueComparer : IEqualityComparer<object?>
{
internal static readonly MetadataValueComparer Default = new MetadataValueComparer();
private MetadataValueComparer()
{
}
public new bool Equals(object? x, object? y)
{
if (x == y)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (x is LazyMetadataWrapper.ISubstitutedValue xSubstituted)
{
return xSubstituted.Equals(y);
}
if (y is LazyMetadataWrapper.ISubstitutedValue ySubstituted)
{
return ySubstituted.Equals(x);
}
if (x.GetType() != y.GetType())
{
// Consider Type[] and RuntimeType[] arrays as equivalent.
if (!(x.GetType().IsArray && y.GetType().IsArray &&
typeof(Type).GetTypeInfo().IsAssignableFrom(x.GetType().GetElementType()) &&
typeof(Type).GetTypeInfo().IsAssignableFrom(y.GetType().GetElementType())))
{
return false;
}
}
if (x.GetType().IsArray)
{
return ArrayEquals((Array)x, (Array)y, v => v);
}
else
{
return x.Equals(y);
}
}
private static bool ArrayEquals(Array xArray, Array yArray, Func<object?, object?> translator)
{
if (xArray.Length != yArray.Length)
{
return false;
}
for (int i = 0; i < xArray.Length; i++)
{
if (!EqualityComparer<object?>.Default.Equals(translator(xArray.GetValue(i)), translator(yArray.GetValue(i))))
{
return false;
}
}
return true;
}
public int GetHashCode(object? obj)
{
throw new NotImplementedException();
}
}
}
private class DictionaryOfImmutableHashSetEqualityComparer<TKey, TValue> : DictionaryEqualityComparer<TKey, ImmutableHashSet<TValue>>
where TKey : notnull
{
internal static new readonly DictionaryOfImmutableHashSetEqualityComparer<TKey, TValue> Default = new DictionaryOfImmutableHashSetEqualityComparer<TKey, TValue>();
protected DictionaryOfImmutableHashSetEqualityComparer()
: base(SetEqualityComparer.Default)
{
}
private class SetEqualityComparer : IEqualityComparer<ImmutableHashSet<TValue>>
{
internal static readonly SetEqualityComparer Default = new SetEqualityComparer();
private SetEqualityComparer()
{
}
public bool Equals(ImmutableHashSet<TValue>? x, ImmutableHashSet<TValue>? y)
{
if (x == null ^ y == null)
{
return false;
}
if (x == null)
{
return true;
}
return x.SetEquals(y);
}
public int GetHashCode(ImmutableHashSet<TValue> obj)
{
return obj.Count;
}
}
}
}
}
| 34.932927 | 175 | 0.482545 | [
"MIT"
] | JoeRobich/vs-mef | src/Microsoft.VisualStudio.Composition/ByValueEquality.cs | 11,460 | C# |
using FastSQL.Core;
using FastSQL.Sync.Core;
using FastSQL.Sync.Core.Indexer;
using FastSQL.Sync.Core.Processors;
using FastSQL.Sync.Core.Repositories;
using System;
using System.Collections.Generic;
using System.Text;
namespace FastSQL.Magento2.Integration.Indexers
{
public class OrderIndexer : BaseEntityIndexer
{
public OrderIndexer(
OrderProcessor processor,
OrderIndexerOptionManager optionManager,
FastAdapter adapter) : base(processor, optionManager, adapter)
{
}
}
}
| 25.954545 | 75 | 0.688266 | [
"MIT"
] | st2forget/fastSQL | src/api/Vendors/Magento2/FastSQL.Magento2.Integration/Indexers/OrderIndexer.cs | 573 | C# |
using System;
using Urho;
namespace Urho.Actions
{
public class CallFuncND : CallFuncN
{
public Action<Node, object> CallFunctionND { get; }
public object Data { get; }
#region Constructors
public CallFuncND(Action<Node, object> selector, object d) : base()
{
Data = d;
CallFunctionND = selector;
}
#endregion Constructors
protected internal override ActionState StartAction(Node target)
{
return new CallFuncNDState (this, target);
}
}
public class CallFuncNDState : CallFuncState
{
protected Action<Node, object> CallFunctionND { get; set; }
protected object Data { get; set; }
public CallFuncNDState (CallFuncND action, Node target)
: base(action, target)
{
CallFunctionND = action.CallFunctionND;
Data = action.Data;
}
public override void Execute()
{
if (null != CallFunctionND)
{
CallFunctionND(Target, Data);
}
}
}
} | 19.319149 | 69 | 0.688326 | [
"MIT"
] | Acidburn0zzz/urho | Bindings/Portable/Actions/Instants/Callfunc/CallFuncND.cs | 910 | 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("FunctionalTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FunctionalTests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("bdc8736e-b513-4468-aa28-a9c31c474ea0")]
// 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.918919 | 84 | 0.746258 | [
"MIT"
] | nchetan/poc | CSharp/UnitTestProofOfConcept/FunctionalTests/Properties/AssemblyInfo.cs | 1,406 | C# |
using System.Collections.Generic;
using EmbyStat.Common.Models.Entities;
using EmbyStat.Repositories.Interfaces;
using EmbyStat.Services.Interfaces;
namespace EmbyStat.Services
{
public class LanguageService : ILanguageService
{
private readonly ILanguageRepository _languageRepository;
public LanguageService(ILanguageRepository languageRepository)
{
_languageRepository = languageRepository;
}
public IEnumerable<Language> GetLanguages()
{
return _languageRepository.GetLanguages();
}
}
}
| 25.521739 | 70 | 0.710392 | [
"MIT"
] | BankaiNoJutsu/EmbyStat | EmbyStat.Services/LanguageService.cs | 589 | C# |
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using MArchive.DataContext;
using MArchive.Domain.Lookup;
using MArchiveLibrary.Repository;
using MArchiveLibrary.ObjectMapping;
using MArchiveLibrary.ExtendedDataContext;
namespace MArchive.BL {
public class WriterBL : BLBase {
private const string CacheAreaKey = "MArchive_Writer";
public static WriterDO Save ( WriterDO inputDO, int userID ) {
Repository<INF_Writer> rep = new Repository<INF_Writer> ( MArchiveDataContextProvider.Instance );
INF_Writer objectToAdd = null;
if ( inputDO.ID == 0 ) {
objectToAdd = new INF_Writer ( );
ObjectMapper.MapObjects ( inputDO, objectToAdd, AuditInfo.Fields );
rep.InsertOnSubmit ( objectToAdd );
} else {
objectToAdd = rep.GetAll ( ).Single ( x => x.ID == inputDO.ID );
ObjectMapper.MapObjects ( inputDO, objectToAdd, AuditInfo.Fields );
}
rep.DCP.CommitChanges(userID);
InvalidateCache(CacheAreaKey);
ObjectMapper.MapObjects ( objectToAdd, inputDO );
return inputDO;
}
internal static WriterDO GetDOByID( int ID ) {
return GetAllDO( ).Single( q => q.ID == ID );
}
public static List<WriterDO> GetAllDO ( ) {
return Mapper.Map<List<INF_Writer>, List<WriterDO>>( GetAll( ).ToList( ) );
}
public static List<INF_Writer> GetAll() {
string functionName = "GetAll";
if (ReadCache<List<INF_Writer>>(CacheAreaKey, functionName) != null) { return ReadCache<List<INF_Writer>>(CacheAreaKey, functionName); }
Repository<INF_Writer> rep = new Repository<INF_Writer> ( MArchiveDataContextProvider.Instance );
var list = rep.GetAll().ToList();
WriteCache(CacheAreaKey, functionName, list);
return list;
}
}
} | 33.12963 | 148 | 0.69033 | [
"MIT"
] | chakian/movie-archive | MArchive.BL/WriterBL.cs | 1,791 | C# |
#pragma checksum "C:\Users\ALAIN\Documents\Revature\AlainDuplanP0\P1\P1\P1\Views\Stores\Error.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "1d4aa1e998cf261dadbfe6b7158cd49d7eb2ff1c"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Stores_Error), @"mvc.1.0.view", @"/Views/Stores/Error.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\Users\ALAIN\Documents\Revature\AlainDuplanP0\P1\P1\P1\Views\_ViewImports.cshtml"
using P1;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\ALAIN\Documents\Revature\AlainDuplanP0\P1\P1\P1\Views\_ViewImports.cshtml"
using P1.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"1d4aa1e998cf261dadbfe6b7158cd49d7eb2ff1c", @"/Views/Stores/Error.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"cf0a83b8b5988f3038230479476a297be027ee35", @"/Views/_ViewImports.cshtml")]
public class Views_Stores_Error : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 1 "C:\Users\ALAIN\Documents\Revature\AlainDuplanP0\P1\P1\P1\Views\Stores\Error.cshtml"
ViewData["Title"] = "Error";
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n<h1>An unknown Error has occurs and our database has not been updated</h1>\r\n\r\n<div>\r\n <button class=\"btn-light\"><a href=\"javascript:void(0);\" onclick=\"history.go(-1);\">Back</a></button>\r\n</div>\r\n\r\n\r\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 50.583333 | 255 | 0.752224 | [
"MIT"
] | 06012021-dotnet-uta/AlainDuplanP1 | P1/P1/P1/obj/Debug/net5.0/Razor/Views/Stores/Error.cshtml.g.cs | 3,035 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.